Shaders From Zero · Episode 18

Shape Library

Shape Library is Episode 18 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 18 · Shaders From Zero · Season 3

Episode 17 rendered exactly one shape — a sphere — because length(p) - r is the easiest SDF in three dimensions. Real scenes need more. A box for a wall, a torus for a ring, a cylinder for a pillar, a capsule for a limb. This episode is the 3D SDF library you'll reach for in every raymarcher you ever write.

Same camera, same march loop, same depth shading as Episode 17. The only thing that changes between stages is the scene SDF. That's the leverage of raymarching: once the loop is correct, every new primitive is a 5-line function.

0 fps
3D SDF primitives · union/subtract/smin · mod()
sdBox(p, vec3(0.7)) at (0, 0.8, 0). The 3D cube primitive.

Box in 3D

The box SDF is the workhorse of architectural and mechanical scenes. It looks intimidating; it's really just the 3D extension of the 2D box from Episode 06.

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);
}

The parameter b is the half-extents of the box — half the width on each axis. sdBox(p, vec3(1.0)) gives you a 2×2×2 cube centered at the origin (1.0 wide in each direction, in each sign).

The formula has two parts. length(max(q, 0.0)) handles points outside the box — distance to the nearest corner/edge/face. The min(max(q.x, max(q.y, q.z)), 0.0) term handles points inside the box, returning a negative distance to the nearest face. Together they form a correct signed distance everywhere in space.

Torus

Donuts are surprisingly fundamental — rings, tires, washers, halos. The torus SDF is the cleanest demonstration of a 2D-to-3D trick: collapse one axis to a ring, then measure to the tube around it.

float sdTorus(vec3 p, vec2 t) {
  vec2 q = vec2(length(p.xz) - t.x, p.y);
  return length(q) - t.y;
}

t.x is the major radius (size of the ring around the Y axis). t.y is the minor radius (thickness of the tube). The line length(p.xz) - t.x measures how far you are from the ring circle in the XZ plane; combined with p.y it gives a 2D coordinate in the cross-section of the donut. Then it's just a circle SDF: length(q) - t.y.

Cylinder (capped)

Capped means it has a top and bottom — a finite pillar, not an infinite tube. h is the half-height, r is the radius.

float sdCappedCylinder(vec3 p, float h, float r) {
  vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h);
  return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));
}

Same trick as the box: length(p.xz) reduces the XZ plane to a single radial distance, then you do a 2D box SDF in (radius, height) space. This pattern — collapse one or two axes, then solve in 2D — shows up everywhere in 3D SDFs once you start looking.

Capsule (point-to-point)

A capsule is a cylinder with hemispherical caps — the shape of a pill, a bone, a limb segment. The cleanest version takes two endpoints and a radius, so you can drape it between arbitrary positions.

float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {
  vec3 pa = p - a, ba = b - a;
  float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return length(pa - ba * h) - r;
}

The math projects p onto the line segment from a to b, clamps so it stays between the endpoints, then returns the distance from p to that projected point minus the radius. This is the SDF you use for stick-figure characters in raymarched scenes — five capsules and a sphere, and you have a body.

Combining SDFs (recap)

From Episode 06, lifted unchanged into 3D — these are pure scalar operations that don't care about dimension:

  • Union — show both shapes: min(a, b)
  • Intersection — only where both exist: max(a, b)
  • Subtraction — a with b carved out: max(a, -b)

The negate-then-max trick for subtraction works because flipping the sign of an SDF flips inside and outside. max(a, -b) asks for "points inside a AND outside b".

Smooth-min in 3D

The same smin from Episode 06, identical formula. It blends two shapes with a curved interpolation instead of a hard seam — like sticking two pieces of clay together and squishing the joint smooth.

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);
}

k is the blend radius — the size of the smooth region around the joint. Small k (around 0.05) gives a tight, almost-hard seam. Large k (0.5+) melts the shapes together until they barely have separate silhouettes. This single function is what makes raymarched scenes look organic; you cannot get this effect with polygons.

Domain repetition

Here's where raymarching gets unfair. To tile a shape infinitely in space, you don't duplicate the SDF — you fold space itself. Use mod to wrap the input coordinates into a single repeating cell:

vec3 q = p;
q.xz = mod(p.xz + 1.5, 3.0) - 1.5;   // repeat every 3 units on XZ plane
float d = sdTorus(q, vec2(0.8, 0.25));

The + 1.5 shifts the origin to the center of the cell; the - 1.5 at the end recenters the cell on zero. Without that pair of half-period offsets, the repetition centers on cell corners instead of cell middles and the shapes look like they're cut in half along the boundaries.

One SDF call, infinite shapes. The march loop sees the wrapped coordinates and has no idea this isn't a single object. Repetition is essentially free.

Common pitfalls

  • Wrong type for half-extents. sdBox(p, 1.0) fails to compile — b is a vec3. Use vec3(1.0).
  • smin blend radius too wide. If k is bigger than the gaps between your shapes, everything melts into one undifferentiated blob. Start small (0.1–0.3) and increase only if you want explicit melt.
  • Domain repeat without the half-period offset. mod(p.xz, 3.0) alone (no + 1.5 / - 1.5) puts the repetition center on cell corners, slicing shapes in half. Add the half period both before and after the mod.
  • Forgot to translate p before the SDF. Every primitive is implicitly at the origin. To place it elsewhere, subtract the target position from p: sdBox(p - vec3(2.0, 0.0, 0.0), vec3(0.5)). Forget this and all your shapes stack at the origin.

Exercises

  1. Combine a sphere and a box with smin(d1, d2, 0.3) — drag one shape past the other by changing the translation and watch the blend snap into a smooth joint as they overlap.
  2. Stack three differently-scaled toroids on the Y axis, each rotated 90° relative to the previous. Easiest version: don't rotate — just stack and union with min.
  3. Subtract a thin cylinder from a box to drill a hole through it. max(box, -cyl). Then drill three holes at different positions and orientations using min(-cyl1, min(-cyl2, -cyl3)) as the subtractor.

What's next

Episode 19 — Lighting & Normals. The shapes in this episode look flat because we're coloring by ray distance, not by surface orientation. Next episode we compute surface normals from the SDF itself (with no mesh in sight) and finally shade these things like real 3D objects.