GLSL Signed Distance Function for a Box (AABB)
This article provides a concise technical breakdown of formulating an exact Signed Distance Function (SDF) for an axis-aligned bounding box (AABB) in GLSL. You will learn the canonical GLSL implementation popularized by Inigo Quilez, how coordinate folding simplifies the calculation, and the exact mathematical derivation distinguishing points outside the box from points inside.
The Canonical GLSL Implementation
An axis-aligned box is typically defined by its center position
(assumed here to be at the origin vec3(0.0)) and its
half-extents vector b (the distances from the center to
each face along the X, Y, and Z axes).
float sdBox(vec3 p, vec3 b) {
vec3 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
}Step-by-Step Breakdown
1. Exploiting Octant
Symmetry with abs(p)
Because an axis-aligned box is symmetric across the XY, YZ, and XZ
planes, any query point p can be mirrored into the first
positive octant using abs(p). This reduces the problem from
evaluating eight octants to evaluating only one, drastically simplifying
boundary checks.
2. Calculating the Offset
Vector q
The vector q = abs(p) - b measures the signed distance
component-wise from the mirrored point to the box corner.
- If a component of
qis positive, the point lies beyond the box boundary on that axis. - If a component of
qis negative, the point is within the box boundary along that axis.
3. Calculating the Exterior Distance
When a point is outside the box, its distance to the nearest face, edge, or vertex is computed via:
length(max(q, 0.0))The max(q, 0.0) operation clamps negative components to
zero.
- If
pis outside a single face, two components ofqare negative and clamped to zero, leaving the standard Euclidean distance to that face. - If
pis outside an edge or corner, two or three components remain positive, andlength()computes the Euclidean distance to that edge or corner. - If
pis inside the box, all components ofqare negative, causingmax(q, 0.0)to yieldvec3(0.0), whose length is0.0.
4. Calculating the Interior Distance
When a point is inside the box, the distance must be negative, corresponding to the distance to the closest face:
min(max(q.x, max(q.y, q.z)), 0.0)The term max(q.x, max(q.y, q.z)) finds the component of
q closest to zero, which represents the nearest boundary
plane. The outer min(..., 0.0) ensures that this term only
contributes a negative value when the point is strictly inside the box.
For exterior points, this term evaluates to 0.0.
5. Combining Exterior and Interior Terms
Adding both components together:
length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0)Because exterior points produce a zero interior term and interior points produce a zero exterior term, this single expression cleanly produces the correct signed Euclidean distance everywhere in 3D space without branching.