Introduction#
Most of this site draws shapes with triangles. There’s a completely different way, much loved by shader programmers: describe a shape with a function that tells you, for any point, how far it is from the shape’s edge. A shape described this way is a signed distance field, or SDF. This post, the first of four, covers:
- What a signed distance is
- How the distance functions for circles, boxes, lines and polygons actually work
- Drawing them with perfectly smooth edges
- Moving, turning, scaling, rounding and hollowing a shape with a line of code each
The next part combines shapes and bends space; SDF part 3 uses SDFs for crisp text; SDF part 4 draws whole 3D scenes with them. It helps to have read Fragment Shaders and the vectors and dot product posts.
What Is a Signed Distance?#
For any point, a signed distance function (also called an SDF) returns the distance to the nearest edge of the shape, as a number that is:
- Positive outside the shape
- Negative inside it
- Zero exactly on the edge
“Signed” just means the number has a plus or minus sign that says which side you’re on. The collection of these distances, one for every point, is the distance field.
A fragment shader can call the function for every pixel and colour the pixel by the sign: negative means inside, so paint it. That’s a complete shape, with no triangles.
A Gallery of Shapes#
Choose a shape below. Switch to Distance field to see the distance at every point as contour lines (orange outside, blue inside, a line every 0.1 units, white on the edge itself). Hover over or tap anywhere to measure: the pink circle around the point has a radius equal to the distance, so it always just touches the nearest edge. Drag the shape by its centre.
Shapes described by signed distance functions
The shader code for this picture, with the current numbers filled in:
The code under the demo is what the fragment shader runs for every pixel; the lines that move, turn, scale, round and hollow the shape are explained further down. Try Raw distances (grey): each pixel’s distance is shown directly as a shade, mid grey on the edge, darker inside and lighter outside. That’s exactly what a distance field looks like when it’s saved as a texture, as SDF part 3 does for text.
The circle#
The simplest possible SDF. The distance from a point to a circle’s edge is its distance to the centre, minus the radius:
float sdCircle(vec2 p, float r) { return length(p) - r; }
In words: p is the point being measured, as an (x, y) position measured from the circle’s centre; r is the circle’s radius; length(p) is how far p is from the centre (Pythagoras, from the vectors post). float and vec2 just say what kind of value each one is: a single number, or a pair of numbers.
A point 0.8 from the centre of a circle of radius 0.5 is 0.3 outside; a point 0.2 from the centre is 0.3 inside (−0.3).
The box: using symmetry#
A box centred on the origin looks the same in all four corners, so the function first folds every point into the top-right quarter with abs(p). Then abs(p) − b says how far the point sticks out past the box, in x and in y:
float sdBox(vec2 p, vec2 b) {
vec2 q = abs(p) - b; // how far past the edges, in x and y
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0); // outside part + inside part
}
Here p is the point, measured from the box’s centre, and b holds the box’s half-width and half-height (b.x and b.y), so a box 1.2 wide and 0.7 tall has b = (0.6, 0.35). abs(p) makes both of p’s numbers positive, which is the folding; q is how far past the edges the folded point is, in x and in y (negative means not past that edge). On a pair of numbers, max(q, 0.0) works on each number separately, turning the negative ones into 0.
If the point sticks out in both x and y, it’s beyond a corner, and the distance is the length of that diagonal (length(max(q, 0.0))). If it sticks out in only one direction, that’s the distance to the nearest edge. Inside the box, both parts of q are negative, and the second term picks the nearest edge as a negative distance. Look at the distance field: outside, the contours turn into quarter-circles around each corner.
The line segment: projection#
The distance to a line segment from a to b is the distance to the nearest point on it. That nearest point comes from the dot product: project the point onto the line, then clamp (lerp, clamp and friends) so it can’t go past either end. A line has no inside, so its distance is never negative. Add some rounding to it in the demo and it becomes a solid capsule: every point within that distance of the segment.
Polygons#
The hexagon and triangle use the same trick as the box, cleverly: fold the point using the shape’s symmetry until only one edge needs measuring. Inigo Quilez has worked out exact distance functions for dozens of shapes; see Further Reading.
Drawing Them Smoothly#
The test “is the distance below 0?” gives hard, jagged edges, as with any yes-or-no test (Rasterisation). But because we know the actual distance, we can do better: fade from inside to outside over about one pixel. The function fwidth(d) tells us how much the distance changes from one pixel to the next (the fwidth post), so:
float d = sdBox(p, vec2(0.6, 0.35));
float w = fwidth(d);
float inside = 1.0 - smoothstep(-w, w, d); // 1 inside, 0 outside, blended across one pixel
This edge stays perfectly smooth at any zoom, which is one of the main reasons SDFs are so popular for user interfaces, icons and text.
Moving, Turning, Scaling, Rounding and Hollowing#
Here’s the clever bit. To move a shape, you don’t change the shape: you change the point before measuring, in the opposite direction. To draw a circle centred at (0.3, 0.2), measure sdCircle(p − vec2(0.3, 0.2), r). To turn the shape by 30°, turn the point by −30° first. To scale it by 2, measure the point divided by 2, then multiply the answer by 2 so it’s still a true distance. It’s the same idea as the view matrix moving the world instead of the camera.
Two more operators work on the distance itself:
- Rounding: subtract a number,
d − r, where d is the distance the shape’s function gave and r is how much to round by. Every edge moves outwards by r, and sharp corners become round. Try it on the box and the triangle. - Hollowing, often called onion:
abs(d) − thickness, where thickness is half the width of the shell you want. Takingabsmakes both sides of the edge positive, so you’re left with a thin shell around the original edge. Apply it twice for two shells.
These functions are cheap: a few multiplications, an abs, a max and a square root, all things graphics cards do in an instruction or two. A fragment shader can easily evaluate dozens of shapes per pixel at full frame rate. The catch is that the cost is paid for every pixel the shader covers, whether the shape is there or not, so large SDF scenes are usually drawn only inside a rectangle around each shape, or with the distances pre-computed into a texture (as SDF part 3 does).
Questions You Might Have#
Are SDFs actually used in games?
Yes, widely: for crisp text and icons (SDF part 3), user interface shapes, decals, and effects. Unreal Engine, for example, stores simplified distance fields of the scene for soft shadows and ambient occlusion.
Summary#
- A signed distance function gives the distance to a shape’s edge: positive outside, negative inside, zero on it.
- Circle: length(p) − r. Box and polygons use symmetry (
abs) to fold the point. Segments use a clamped projection. fwidthandsmoothstepturn a distance into a smooth, one-pixel edge at any size.- Move, turn and scale by changing the point the opposite way; round with d − r; hollow with abs(d) − t.
Next: combining shapes and bending space.
Further Reading#
- Inigo Quilez, 2D distance functions: the definitive collection of exact 2D SDFs, with live examples.
- The Book of Shaders, Shapes: drawing shapes with distance functions, step by step.