Last updated on

Signed Distance Fields: A Visual Introduction

ENNLESPT-BR


Signed distance fields (SDFs) describe a shape with a single function. Instead of storing triangles or curve segments, you store a rule that answers two questions for any point in space: how far away is the nearest surface, and am I inside or outside?

Those two answers cover more ground than they first appear to. Rendering, collision, lighting, animation, and navigation all ask distance-and-side questions, and an SDF answers each one by evaluating the same function at a different point. Because the shape lives in a formula, you can move it, repeat it, blend it, and carve it with ordinary arithmetic.

This page builds the mental model with interactive 2D examples, then maps out where each idea leads. The major sections point to dedicated articles that work through the theory, the code, and the tradeoffs in full.

What a Signed Distance Field Stores

For any point p\mathbf{p}, an SDF returns a signed scalar d(p)d(\mathbf{p}):

  • positive outside the shape
  • zero on the surface
  • negative inside the shape

The absolute value ∣d(p)∣|d(\mathbf{p})| is the shortest distance to the boundary, and the sign says which side you are on. A value of d(p)=−0.12d(\mathbf{p}) = -0.12 means the point sits 0.12 units inside the shape. A value of d(p)=0.12d(\mathbf{p}) = 0.12 means it sits 0.12 units outside. At zero, you are on the surface. That one number carries both a side label and a distance, which is more than a binary inside/outside mask can tell you.

The extra information is what makes the field reusable. A mesh records where the surface is; an SDF records how far every point in space is from it. Offsetting the surface is then a single subtraction. Evaluating d(p)−md(\mathbf{p}) - m grows the shape by mm, and d(p)+md(\mathbf{p}) + m shrinks it, which gives you collision buffers, bevels, and shells without rebuilding the geometry.

——
InsideSurfaceOutside

The explorer renders six primitives (circle, box, rounded box, line segment, capsule, and regular polygon) as continuous heatmaps, where color tracks the signed distance and a black line marks the zero contour. Hover anywhere to read the exact value and an Inside, Surface, or Outside label. Switching shapes keeps the same reading process while the formula changes underneath, and the formula is printed above the sliders so you can connect each parameter to the field it produces. Dragging the endpoints of the segment and capsule shows that the field follows the geometry immediately, with no mesh to rebuild.

Below the surface, each primitive is a compact expression. That is the next idea to make concrete.

Signed Distance Formulas for Simple Shapes

Every SDF scene starts from primitives with compact formulas, and the circle is the natural first example:

d(p)=∥p−c∥−rd(\mathbf{p}) = |\mathbf{p} - \mathbf{c}| - r

The term ∥p−c∥|\mathbf{p} - \mathbf{c}| is the Euclidean distance from the sample point p\mathbf{p} to the center c\mathbf{c}. Subtracting the radius rr moves the zero crossing out to the boundary. On the boundary the distance to the center equals rr, so the expression is zero; outside it is positive; inside it is negative, and the magnitude reports how deep the point sits. In code it is a single line:

float circleSDF(vec2 p, vec2 center, float r) {
    return length(p - center) - r;
}

The box follows the same distance-minus-extent idea, applied per axis. For a box centered at c\mathbf{c} with half-size b\mathbf{b}:

q=∣p−c∣−bd(p)=∥max⁡(q,0)∥+min⁡(max⁡(qx,qy),0)\begin{aligned} \mathbf{q} &= |\mathbf{p} - \mathbf{c}| - \mathbf{b} \ d(\mathbf{p}) &= |\max(\mathbf{q}, 0)| + \min(\max(q_x, q_y), 0) \end{aligned}

∥max⁡(q,0)∥|\max(\mathbf{q}, 0)| measures how far the point is from the nearest face when it is outside, and the second term reports penetration depth when it is inside. Adding them produces one signed value that follows the same contract as the circle: positive outside, zero on the surface, negative inside.

The same circle formula generalizes directly to three dimensions, which gives the signed distance field for a sphere, one of the few shapes with an exact distance everywhere in space. For a broader catalog covering triangles, capsules, toruses, and more, see Iñigo Quilez’s distance function reference.

Combining Shapes with Constructive Solid Geometry

A single primitive rarely makes a scene. Most shapes are built by combining fields, and the technique has a formal name: constructive solid geometry (CSG). With meshes, boolean operations require cutting and re-triangulating surfaces. With SDFs, they reduce to a few comparisons on distance values.

Three operators cover most cases:

  • union: min(a, b)
  • intersection: max(a, b)
  • subtraction (A minus B): max(a, -b)

At any point, the nearest surface decides the combined value, so the minimum of two signed distances is the distance to their union. Intersection keeps only the region inside both shapes, which is why it takes the maximum. Subtraction flips the sign of the second field so that its interior carves away the first. Holes, cutouts, and negative space are all modeled this way, and the same operation drives real-time destruction: each crater is one more subtraction in the tree, followed by Marching Cubes to extract a fresh mesh for rendering. The destructible terrain article follows that carve-and-extract pipeline in detail.

0.50
0 primitives
InsideOutside

The visualization opens in Subtraction mode, with a ring carving a rounded hole out of a box. Blue marks outside and red marks inside, and switching the operation updates the whole field: Union merges the shapes along their nearest edges, Intersection keeps only the overlap, and the hover readout reports the exact combined distance at any point. Add primitives from the palette and drag them into place to watch the field recompose.

Smooth Blending

Hard min and max leave sharp creases where shapes meet, which is often exactly what you want. For organic joins, a smooth minimum (smin) rounds the transition. One common form uses a blend width kk:

h=clamp(0.5+0.5b−ak,0,1),smin(a,b,k)=mix(b,a,h)−kh(1−h)h = \mathrm{clamp}\left(0.5 + 0.5\frac{b-a}{k}, 0, 1\right), \quad \mathrm{smin}(a,b,k) = \mathrm{mix}(b,a,h) - k h(1-h)

Small kk behaves almost like hard min, and larger kk widens the blended region until the shapes flow into each other. The same construction has smooth intersection and subtraction variants.

0.50
0 primitives
InsideOutside

This instance starts in Smooth Union. Raising the blend slider widens the seam; switching back to Union shows the sharp version of the same overlap for comparison. The hover readout shows how the value at a point changes as kk softens the transition.

Smoothing is convenient, but it changes local curvature and relaxes the strict distance guarantee, a tradeoff that matters when a ray marcher depends on safe step sizes.

Transforming, Repeating, and Perturbing Space

Many SDF operations never touch the shape formula. They transform the coordinates before evaluation:

  1. Translation: evaluate at p−t\mathbf{p} - \mathbf{t}
  2. Rotation: evaluate at R−1pR^{-1}\mathbf{p}
  3. Scale: evaluate at p/s\mathbf{p}/s and multiply the result by ss
  4. Repetition: wrap coordinates with mod or fract to tile a shape across space

Because every instance shares one formula, a single circle definition can become a grid of circles, and one primitive can populate an entire scene. The scale case is the one to watch: dividing the input by ss stretches space, so the raw result must be multiplied by ss to restore a true distance.

Domain operations also combine with noise. Feeding perturbed coordinates into an SDF produces rocky, molten, or cloud-like surfaces while keeping the function-first workflow. Value, Perlin, and fractal noise are covered in the noise functions article.

Surface Normals from the Gradient

Once a query finds a surface point, the next question is usually which way the surface faces. Lighting, reflections, and collision response all need that direction. An SDF answers it without a stored normal buffer, because distance increases fastest in the direction that points away from the nearest surface. That direction is the gradient ∇d(p)\nabla d(\mathbf{p}), and at the boundary it is the outward surface normal.

Gradient arrow Surface normal

The visualization overlays gradient arrows on the heatmap. Every arrow points away from the nearest surface, and arrows close to the zero contour are highlighted because there the gradient is the normal. Hover to place a probe and read the distance, gradient direction, and gradient magnitude; click to pin it, then drag the epsilon slider. A small epsilon (0.001) crowds the finite-difference samples together and the direction becomes noisy; a large epsilon (0.5) smooths the result but bends it away from the true normal near corners and high curvature. The default 0.01 balances the two for analytical SDFs.

The finite-difference estimate samples the field at small offsets along each axis:

∇d(p)≈[d(p+εx)−d(p−εx)d(p+εy)−d(p−εy)]\nabla d(\mathbf{p}) \approx \begin{bmatrix} d(\mathbf{p}+\varepsilon_x)-d(\mathbf{p}-\varepsilon_x) \ d(\mathbf{p}+\varepsilon_y)-d(\mathbf{p}-\varepsilon_y) \end{bmatrix}

The orange dots around the probe mark those sample points. Notice that the gradient magnitude stays near 1 across the whole field. This is the eikonal property (∣∇d∣=1|\nabla d| = 1) that exact SDFs satisfy, and it is why the gradient is already a unit vector: after estimating it, normalize before feeding it into lighting.

Exact Fields, Approximate Fields, and Step Safety

Not every signed distance field reports a true distance. A formula like the circle returns the exact Euclidean distance everywhere. A field sampled from a mesh, a smooth CSG blend, or a noise-modulated surface returns a value that is signed and distance-like but may be inaccurate.

The direction of the error matters. A field that underestimates distance (returning 0.2 when the true value is 0.5) makes a ray marcher take smaller steps, so it still converges. A field that overestimates (returning 0.5 when the true value is 0.2) can let a ray step through a thin wall. Exact fields are preferred wherever safety margins matter, such as long camera rays or collision detection, and approximate fields need tighter thresholds. The ray marching article covers the step-safety rules in detail.

Font glyphs, scanned models, and artist-authored meshes have no compact formula, so their fields are computed and stored instead. The sampled signed distance fields article follows the full pipeline, from finding the nearest triangle for each sample to resolving inside and outside and choosing a resolution.

Where SDFs Fit in a Pipeline

SDFs are one geometry representation among several, and they fit best where shapes are procedural, deformable, or queried from many places. Different applications tap the field in different ways. A particle system evaluates distance and gradient for every particle in flight, so the per-query cost matters more than the complexity of the shape being tested. A navigation system reads the field value as clearance and the gradient as a direction toward or away from obstacles. Soft shadows and ambient occlusion use the field as a cheap occluder test along light rays instead of relying on shadow maps.

The table below maps the common questions to the field evaluation that answers them and to the article that covers that application in depth.

Question What the SDF provides Read next
Where does a ray hit the scene? distance-guided steps along the ray Ray marching
Is this point inside a volume? the sign of the field Collision detection
How do two objects separate? penetration depth from the magnitude, direction from the gradient Collision detection
Where does a particle bounce? distance and gradient at the particle Physics and particle systems
How much clearance does a spot have? the field value, with the gradient pointing to the nearest obstacle AI pathfinding and navigation
How soft is a shadow? the closest a light ray comes to occluding geometry Shadows and ambient occlusion
Where did an explosion carve? a CSG subtraction in the field Destructible terrain

Meshes remain the better choice for artist-authored topology, UV workflows, and hardware triangle rasterization, and most GPU pipelines are built around them. SDFs win when you need cheap repeated distance queries or shapes that change every frame. Production engines usually keep both: rasterized meshes for the visible scene and distance fields for the spatial queries behind it. The SDFs in game development article lays out that hybrid strategy across collision, physics, AI, lighting, and terrain.

Summary

A signed distance field stores shape as one scalar function with two guarantees: the magnitude is the distance to the nearest surface, and the sign says which side you are on. From that single representation you can:

  1. march rays with distance-guided safe steps
  2. compose scenes with min and max
  3. estimate surface normals from the gradient
  4. transform and repeat coordinates to build complex layouts

Most advanced SDF techniques are variations of one loop: evaluate the field, use the result, repeat. Once the contract is clear, the linked articles become variations on that same idea.