Shaders From Zero · Episode 06
SDFs — Signed Distance Fields
SDFs — Signed Distance Fields is Episode 06 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
So far we've colored every pixel by reading its UV. What if instead of reading UV, we asked: "how far is this pixel from a shape I'm imagining?" That question turns into a signed distance field — SDF — and SDFs let you draw any shape in math, combine them with addition and minimum, and animate them like clay. This is how Pixar prototypes characters, how Shadertoy shows off, and how a huge chunk of modern procedural rendering survives without a triangle in sight.
By the end of this episode you'll know how to draw a circle and a box from a single
line of math each, blend them like dough with smin, and tile an infinite
grid of animated shapes from a single SDF and a mod(). No texture, no
geometry, no draw calls. One quad, one fragment shader, and a small library of
distance functions.
What an SDF is
A signed distance field is a function. The 2D version takes a point in the plane and returns one number:
float sd(vec2 p) {
// returns:
// negative → p is inside the shape
// zero → p is exactly on the surface
// positive → p is outside; value = distance to nearest surface
}
That distance property is the magic. It's not just "in or out" — it's "how far
in or out." A pixel that's 0.01 from the edge knows it. A pixel that's
0.4 from the edge knows that too. You can do AA, you can do glow, you can
do soft shadows, you can do raymarching — all because you have a continuous, signed,
Euclidean distance to fall back on.
You draw with an SDF by thresholding the distance:
step(0.0, d)— returns 1 when outside, 0 when inside. A hard binary mask. Aliased. Good for one-pixel debug toggles, bad for anything you want to look nice.smoothstep(0.01, -0.01, d)— returns a smooth 1-to-0 ramp across a narrow band centered on the surface. Anti-aliased. This is what you actually use.
Notice the order in the second one: high threshold first, low threshold second. That flips the ramp so the inside of the shape is 1 and the outside is 0. Get used to that flip — you'll write it constantly.
Centering matters
SDFs assume your coordinate system is centered on the origin. A circle of radius
0.3 at the origin lives between -0.3 and +0.3
on both axes. If you hand it raw UVs (which range from 0 to 1), the "center" of your
surface is at (0.5, 0.5) and your circle ends up tucked in the bottom-left
corner, half off-screen.
So always start with:
vec2 p = vUv - 0.5; // now p ranges roughly −0.5 to +0.5, centered on origin
If your surface isn't square, you also want aspect correction so circles stay round:
p.x *= aspect; // aspect = width / height, passed in as a uniform
We're using a square PlaneGeometry(1.8, 1.8) in the demo, so we get to
skip aspect correction. If you transplant this code onto a non-square surface and your
circle goes oval, that's the one-line fix.
The circle — the "hello world" of SDFs
The simplest SDF there is:
float sdCircle(vec2 p, float r) {
return length(p) - r;
}
Read it. length(p) is the Euclidean distance from p to the
origin. Subtracting r shifts the zero crossing outward by r
units. So points inside the circle of radius r get a negative number;
points outside get a positive number equal to "how far past the rim you are." That's
a perfect signed distance field for a circle. Three characters of math.
Drawing it:
vec2 p = vUv - 0.5;
float d = sdCircle(p, 0.3);
vec3 col = mix(vec3(0.95, 0.55, 0.2), vec3(0.08), step(0.0, d));
gl_FragColor = vec4(col, 1.0);
That's Stage 1. Hard edge, aliased. Look closely at the rim and you can see the stairstep. We'll fix that in a moment.
The box
The classic 2D box SDF. This one isn't obvious; learn the formula and move on:
float sdBox(vec2 p, vec2 b) {
vec2 d = abs(p) - b;
return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
}
Walking through it, briefly:
abs(p)mirrors everything into the first quadrant — a box is symmetric about both axes, so we only need to solve it there.- bsubtracts the box's half-extents. Nowdis the signed gap to each edge.max(d, 0.0)zeros out negative components — only the "outside" axes contribute to the outside distance.length(...)measures the diagonal distance to the corner.- The second term,
min(max(d.x, d.y), 0.0), handles the inside-points where both components ofdare negative.
Don't dwell too long on the derivation. The formula is the formula. Type it in, use it, recognize it on Shadertoy when you see it. Inigo Quilez has the full catalog of 2D and 3D primitives on his site.
Drawing — sharp vs soft edges
You have a distance. You want pixels. Two ways:
// Sharp, aliased — Stage 1
float fill = 1.0 - step(0.0, d);
// Soft, AA — Stage 2 (and everything after)
float fw = 0.005;
float fill = smoothstep(fw, -fw, d);
The "filter width" fw is the half-width of the soft band. A small
constant like 0.005 works for our 1.8-unit surface. For a more principled
value, use 2.0 / uResolution.y — that gives you exactly one pixel of
blur regardless of the surface size. Either is fine.
Open the demo, toggle between Stage 1 and Stage 2. Look at the rim. Stage 2 is what you actually ship.
Combining SDFs
The reason SDFs matter is composition. Three operators do almost everything:
| Operator | GLSL | What it does |
|---|---|---|
| Union | min(d1, d2) | Both shapes drawn; whichever is closer wins. |
| Intersection | max(d1, d2) | Only where both shapes overlap. |
| Subtraction | max(d1, -d2) | d1 with d2 carved out of it. Note the minus. |
Three lines of CSG. The minus sign in subtraction is the whole trick — flipping the
sign of a distance turns "inside" into "outside," and max takes whichever
is further out, so the negated shape becomes a hole.
Smooth-min — the secret of "metaball" shapes
min gives you a union, but at the joint where the two shapes meet, the
surface has a hard crease. To get a smooth, organic blend — the look people associate
with metaballs, with rendered clay, with Pixar character sculpts — you replace
min with smin:
float smin(float a, float b, float k) {
float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);
return mix(b, a, h) - k * h * (1.0 - h);
}
The k parameter is the blend radius. A small k keeps the
two shapes nearly intact with just a fillet at the joint. A large k melts
them together into a single blob.
smin(a, b, 0.05)— tight blend, barely-visible fillet.smin(a, b, 0.15)— comfortable metaball blend. (Stage 4 uses this.)smin(a, b, 0.5)— loose blob, the shapes lose all identity.
This is the function. Memorize the form, paste it into every SDF shader you ever
write. There are other smin variants (polynomial, exponential, power) —
Inigo's site has the full collection — but the polynomial above is the workhorse.
Repetition — domain repeat
Here's the move that makes people think SDFs are wizardry. You can tile an SDF across infinite space by transforming the coordinate instead of the shape:
vec2 q = mod(p + 0.5, 1.0) - 0.5;
float d = sdCircle(q, 0.2);
Read the first line carefully. mod(p + 0.5, 1.0) wraps each component
of p into the range [0, 1). Subtracting 0.5
re-centers each cell, so q always lives in [-0.5, 0.5). From
the SDF's point of view, every cell looks like the same single tile with a circle in
the middle. You get an infinite grid of circles for the same cost as one circle.
To control the tile size, scale p before the mod:
mod(p * 4.0 + 0.5, 1.0) - 0.5 gives you a 4×4 grid across the visible
area. To animate, do whatever you want with length(p) or q
on the way in.
Inigo's distfunctions2d article is the reference here. Bookmark it. The full repeat trick, plus mirrored repeats, limited repeats, and polar repeats, all live there. You will never need to derive any of this yourself.
Common first-day pitfalls
- Forgot to center the UV. Your "circle at origin" is in the
bottom-left corner because you passed
vUvstraight in instead ofvUv - 0.5. Always center first. - Aspect ratio not corrected. Your perfectly circular SDF renders
as an oval on a 16:10 canvas. Fix with
p.x *= aspect;after the centering. Square plane in this demo so we skip it — easy to forget when you copy this code somewhere else. - Used
step()for the fill and got jagged edges. Switch tosmoothstepwith a small filter width. The order matters:smoothstep(fw, -fw, d)notsmoothstep(-fw, fw, d), or you'll paint the outside instead of the inside. sminblend radiusktoo large. Your two distinct shapes have melted into one shapeless blob. Start at0.1–0.2and tune from there.- Mixed up
minandmaxfor CSG. Union ismin(closer wins). Intersection ismax(further wins). Subtraction ismax(d1, -d2)— the minus is mandatory, not optional. - Animated the shape, forgot to subtract
0.5frommod. Your tiled circles are stuck at the corners of each cell instead of centered. The+ 0.5beforemodand- 0.5after is what centers them.
Exercises
- Add a third shape — a small box, say
sdBox(p - vec2(0.25, 0.0), vec2(0.05))— to Stage 4 andsminit into the existing blend. Three-way metaball. - Modify Stage 5 so the tile size is driven by a uniform you slide between
2.0and8.0. (Multiplypbefore themod.) - Implement
sdRing(p, r, t)asabs(length(p) - r) - tand use it instead ofsdCirclein Stage 5. You should see a rippling grid of donuts.
What's next
Episode 07 — Vertex Shaders. So far we've only ever colored pixels;
the geometry has sat there like a billboard. Next episode we move the geometry itself
— displacing vertices with uTime, with noise, with normals — and the
surface becomes alive. The fragment shader stays a passenger; the vertex shader
finally gets to drive.