SDF

SDF stands for Signed Distance Field and is usually used in fragment shaders to draw shapes.

The idea is that we send a 2D or 3D point to a SDF shape function and that function returns how far that point is from the shape. There are many possible shapes, as long as they can be expressed mathematically.

  • We get the distance of the UV coordinate (the fragment we are drawing) to the center of the disc.
  • We decide on a radius.
  • If the distance we got earlier is less than the radius, we are in the disc and we can draw the pixel.
  • If the distance exceeds the radius, we have moved beyond the disc and we draw nothing.

This is what we did in the Shader patterns lesson and this would be the SDF function to draw a circle.

It obviously gets more complicated for more complex shapes (especially 3D shapes).

Inigo Quilez (@iquilezles) wrote great articles with good examples of SDF functions:

SDF fonts

For fonts, it’s even more complex because the shape can’t really be calculated mathematically.

To fix that, developers have created scripts that generate textures containing the distance information for each character of a font.

We can then use that texture to indicate the distance between the fragment we are drawing and the supposed character.

If the distance is closer to a specific value, we draw the text; otherwise, we draw nothing.

You might think that it’s the same as drawing a text in a texture and using that texture, but it goes beyond that. The value we get is the distance between the point we are drawing and the character.

This enables things like easily changing the thickness of the font, adding a blur all around the font, drawing huge text, and having a lot of words while using the same collection of characters.

You might also think that we should still be able to see the pixels if the font distance is encoded in a texture, but the natural interpolation between pixels of a texture makes it almost unnoticeable unless the text is really huge or the encoded font resolution is too small.

The process of creating the texture from a font is long and complex. Fortunately, some developers have already done most of the heavy lifting in the Troika library (and more precisely troika-three-text) and drei is implementing that solution in the Text helper.

Implementing

Import Text from @react-three/drei:

import { Text, Html, PivotControls, TransformControls, OrbitControls } from '@react-three/drei'

And a <Text> anywhere in the scene (the content inside <Text> will be used as the text):

export default function Experience()
{
    // ...

    return <>

        {/* ... */}

        <Text>I LOVE R3F</Text>

    </>
}

Leave a comment

Your email address will not be published. Required fields are marked *