Shapes as functions of position
Up to now, every shape you've drawn came from a formula evaluated per pixel: length(centered) < 0.3 for a circle, a smoothstep around a threshold for a soft edge. Chapter 7 even slipped in a few distance-based shapes. This chapter turns that habit into a method.
A signed distance field (SDF) describes a shape with a single function. You give it a position and it answers one question: how far is this point from the shape's edge, and is it inside or outside? It doesn't store vertices or pixels. Because the answer is a plain number, you can combine shapes with min and max, blend them like clay, grow or hollow them out by adding a constant, and get an anti-aliased edge at any size. You'll find SDFs behind text rendering, UI effects, and most of the 2D and 3D demos on Shadertoy.
The two ways of thinking about a circle look like this:
// Traditional thinking: "Draw a circle by plotting points"
for (angle = 0; angle < 2π; angle += step) {
x = centerX + radius * cos(angle);
y = centerY + radius * sin(angle);
plot(x, y);
}
// Distance field thinking: "A circle is all points distance R from center"
float distanceToCircle(float2 point, float2 center, float radius) {
return length(point - center) - radius;
// Negative = inside, Positive = outside, Zero = exactly on edge
}
The second version is a natural fit for a fragment shader. The GPU already asks "what color is this pixel?" for every pixel, and the SDF answers the related question "where is this pixel relative to the shape?" in one line.
Signed distance functions
The sign convention: negative inside
Every SDF in this chapter follows the same convention:
- negative values mean the point is inside the shape
- positive values mean it's outside
- zero means it's exactly on the edge
The magnitude is the distance to the nearest point on the edge, in whatever units your coordinates use.
Here's the circle SDF worked through with real numbers. Take the centered coordinates from earlier chapters (centered = uv - 0.5, so the middle of the view is (0, 0)) and a circle of radius 0.25:
point length(point) length(point) - 0.25 meaning
(0, 0) 0.0 -0.25 center: 0.25 inside the edge
(0.1, 0) 0.1 -0.15 inside, 0.15 from the edge
(0.25, 0) 0.25 0.0 exactly on the edge
(0.3, 0.4) 0.5 +0.25 outside, 0.25 away
Holding on to this convention matters later. The boolean operations below only work because "less than zero" always means "inside".
Circle and rectangle
// Circle SDF - the fundamental building block
float circleSDF(float2 point, float2 center, float radius) {
// Calculate distance from point to center
float distanceToCenter = length(point - center);
// Subtract radius:
// - If we're closer than radius → negative (inside)
// - If we're farther than radius → positive (outside)
return distanceToCenter - radius;
}
// Rectangle SDF - trickier but more useful
float rectangleSDF(float2 point, float2 center, float2 size) {
// Translate so rectangle is centered at origin
float2 translated = point - center;
// Work in absolute space (first quadrant only)
float2 absPoint = abs(translated);
// Distance to rectangle corner
float2 halfSize = size * 0.5;
float2 cornerDistance = absPoint - halfSize;
// Outside distance: how far we are from the corner
float outsideDistance = length(max(cornerDistance, 0.0));
// Inside distance: how far we are from the nearest edge
float insideDistance = min(max(cornerDistance.x, cornerDistance.y), 0.0);
return outsideDistance + insideDistance;
}
How the box SDF works, step by step
The rectangle function is the one people copy without understanding, so let's take it apart. It's the same formula Inigo Quilez publishes as sdBox on his site, which is the standard reference for 2D and 3D distance functions:
float sdBox(float2 p, float2 b) { // b = half-size of the box
float2 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}
Step 1: abs(p) folds the plane. A rectangle centered at the origin is symmetric in x and y, so a point at (-0.5, 0.1) is exactly as far from the edge as (0.5, 0.1). After abs, every point lives in the top-right quarter and you only need to solve that one corner.
Step 2: q = abs(p) - b measures how far past each edge the point is. q.x is the signed distance to the right edge (as if that edge were an infinite line), and q.y the signed distance to the top edge. A negative component means "still within the box along that axis".
Step 3: the sign pattern of q tells you which region you're in:
│
q.x < 0, q.y > 0 │ q.x > 0, q.y > 0
(above the box) │ (past the corner: nearest point is the corner)
│
────────────────────●──────────────────────
│
q.x < 0, q.y < 0 │ q.x > 0, q.y < 0
(inside) │ (right of the box)
│
● = the box corner (b.x, b.y), after abs() has folded everything into this quarter
Step 4: outside the box, length(max(q, 0.0)) gives the distance. max(q, 0.0) zeroes any component that's still within the box. If you're directly to the right, only q.x survives and the length is just q.x. If you're diagonally out past the corner, both survive and you get the straight-line distance to the corner.
Step 5: inside the box, both components of q are negative and max(q, 0.0) is (0, 0), so the first term is zero. The nearest edge is the one with the least negative q component, which is max(q.x, q.y). The min(..., 0.0) around it makes sure this term only contributes when you're inside.
Here are three points traced through a box with half-size b = (0.3, 0.2):
p q = abs(p) - b length(max(q,0)) min(max(q.x,q.y),0) result
(0.5, 0.1) (0.2, -0.1) 0.2 0 0.2 right of the box
(0.5, 0.4) (0.2, 0.2) 0.283 0 0.283 diagonal from the corner
(0.1, 0.05) (-0.2, -0.15) 0 -0.15 -0.15 inside, nearest the top edge
The rectangleSDF above takes the full size and halves it itself, so rectangleSDF(p, center, float2(0.6, 0.4)) matches sdBox(p - center, float2(0.3, 0.2)).
Turning distance into pixels
The SDF gives you a number per pixel. To see a shape you need a coverage value between 0 (background) and 1 (shape). The preview below shows three ways to get one:
SDF Circle with Visualization Options
Basic circle SDF demonstrating three visualization methods: smooth anti-aliased edges, hard pixel-perfect edges, and distance field visualization
[[ stitchable ]] half4 sdfCircle(
float2 position,
half4 color,
float2 size,
float radius // Circle radius (0.0 to 0.5)
) {
// Convert to UV coordinates
float2 uv = position / size;
// Center the coordinate system
float2 centered = uv - 0.5;
// Calculate signed distance to circle
float distance = length(centered) - radius;
// Convert distance to color
// Method 1: Hard edge using step
float hardEdge = step(0.0, -distance); // 1 inside, 0 outside
// Method 2: Smooth edge using smoothstep
float pixelWidth = fwidth(distance); // How fast distance changes per pixel
float smoothEdge = 1.0 - smoothstep(-pixelWidth, pixelWidth, distance);
// Method 3: Visualize the distance field itself
float distanceViz = distance * 0.5 + 0.5; // Remap to 0-1 for visualization
// Choose which visualization to return
float result = smoothEdge; // Use smooth edge for final result
return half4(result, result, result, 1.0);
}The hard edge, step(0.0, -distance), is 1 wherever the distance is zero or negative. It's correct but aliased: each pixel is fully in or fully out, so curved edges show stair steps.
The smooth edge is the one you'll use almost everywhere. You met fwidth() in Chapter 7: it returns how much a value changes from one pixel to the next. For an SDF that means "how many distance units one pixel covers". Say the view is 300 pixels wide. In uv units one pixel is 1 / 300 ≈ 0.0033, and since the circle's distance changes by about one unit per unit moved, fwidth(distance) is roughly 0.0033 (up to about 1.4 times that on diagonals, because fwidth adds the x and y changes). So smoothstep(-0.0033, 0.0033, distance) fades the edge over about two pixels, centered on the true boundary. Make the view 900 pixels wide and fwidth shrinks to about 0.0011, so the fade is still about two pixels. That's why this edge stays crisp at any size. The 1.0 - flips the result so the inside is 1.
The third option remaps the raw distance into a gray value. It's a debugging view: dark inside, light outside, mid-gray at the edge. Return distanceViz instead of smoothEdge whenever a shape looks wrong and you want to see what the field is doing.
One caveat: position / size stretches uv to the view's aspect ratio, so in a non-square view this "circle" becomes an ellipse and the distances are no longer true distances. Correct for aspect as you did in Chapter 2 if your view isn't square.
Boolean operations: min and max
Because every SDF uses the same sign convention, you can combine two of them with the simplest functions there are:
// Boolean operations on distance fields
float unionSDF(float d1, float d2) {
return min(d1, d2); // Closest surface wins
}
float intersectionSDF(float d1, float d2) {
return max(d1, d2); // Farthest surface wins
}
float differenceSDF(float d1, float d2) {
return max(d1, -d2); // Remove d2 from d1
}
// Smooth versions for organic blending
float smoothUnion(float d1, float d2, float smoothness) {
float h = max(smoothness - abs(d1 - d2), 0.0) / smoothness;
return min(d1, d2) - h * h * smoothness * 0.25;
}
float smoothSubtraction(float d1, float d2, float smoothness) {
// Note the order: returns shape d2 with shape d1 carved out of it
float h = max(smoothness - abs(-d1 - d2), 0.0) / smoothness;
return max(-d1, d2) + h * h * smoothness * 0.25;
}
float smoothIntersection(float d1, float d2, float smoothness) {
float h = max(smoothness - abs(d1 - d2), 0.0) / smoothness;
return max(d1, d2) + h * h * smoothness * 0.25;
}
Here's why min and max do the right thing. A point is inside the union if it's inside either shape, so it needs at least one negative distance. min returns the smaller value, which is negative whenever either input is. A point is inside the intersection only if it's inside both shapes. max returns the larger value, which is negative only when both inputs are. For difference, -d2 flips shape 2 inside out: what was inside becomes positive and everything outside becomes negative. Intersecting shape 1 with "everything outside shape 2" leaves shape 1 with shape 2 removed.
Two points traced through all three operations:
point d1 d2 union min intersection max difference max(d1, -d2)
in circle 2 only 0.05 -0.02 -0.02 in 0.05 out 0.05 out
in both circles -0.03 -0.01 -0.03 in -0.01 in 0.01 out (carved away)
The results aren't always the exact distance. min is exact outside both shapes, while the max-based operations can underestimate the distance in some regions. For drawing that doesn't matter: the sign is correct everywhere and the values near the edge are right, which is all the anti-aliasing step needs.
Smooth minimum: blending shapes like clay
A hard min meets at a crease. smoothUnion (often called smin) rounds that crease off by pulling the result down where the two distances are similar. It's Inigo Quilez's quadratic smooth minimum:
h = max(k - abs(d1 - d2), 0.0) / kis 1 whend1 == d2, falls to 0 when they differ bykor more, and stays 0 beyond that.min(d1, d2) - h * h * k * 0.25subtracts a correction that is largest (k / 4) where the two shapes are equally close, and zero once one shape is clearly nearer.
So k is the width of the blending zone, in the same units as your distances. Outside that zone you get a plain min.
A worked example with k = 0.1, at a point in the gap between two circles:
d1 = 0.02,d2 = 0.04. Plainmingives 0.02, so the point is outside.abs(d1 - d2) = 0.02, soh = (0.1 - 0.02) / 0.1 = 0.8.- The correction is
0.8 * 0.8 * 0.1 * 0.25 = 0.016, giving0.02 - 0.016 = 0.004. The point is now almost on the edge. - At the midpoint, where
d1 = d2 = 0.02,h = 1and the correction is the full0.025, so the result is-0.005: inside. The gap has filled in and the two circles are joined by a bridge.
smoothIntersection and smoothSubtraction are the same trick applied to max, with the correction added instead of subtracted. All three divide by smoothness, so never call them with 0. The demo below falls back to the hard versions when the slider is near zero for that reason.
Watch the argument order of smoothSubtraction(d1, d2, k): it returns d2 minus d1. That's why the demo calls smoothSubtraction(circle2, circle1, smoothness) to get the same result as the hard max(circle1, -circle2).
Boolean operations demo
SDF Boolean Operations
Interactive demonstration of SDF boolean operations: union (combine shapes), intersection (overlap only), and difference (subtract shapes) with adjustable smoothness
[[ stitchable ]] half4 sdfBooleanOps(
float2 position,
half4 color,
float2 size,
float operation, // 0=union, 1=intersection, 2=difference
float smoothness // 0=hard, 0.1=smooth
) {
float2 uv = position / size;
float2 centered = uv - 0.5;
// Define two overlapping shapes
float circle1 = length(centered - float2(-0.1, 0.0)) - 0.15; // Left circle
float circle2 = length(centered - float2(0.1, 0.0)) - 0.15; // Right circle
float result = 0.0;
if (operation < 0.5) {
// Union: combine both shapes
if (smoothness > 0.001) {
result = smoothUnion(circle1, circle2, smoothness);
} else {
result = min(circle1, circle2);
}
} else if (operation < 1.5) {
// Intersection: only where both shapes overlap
if (smoothness > 0.001) {
result = smoothIntersection(circle1, circle2, smoothness);
} else {
result = max(circle1, circle2);
}
} else {
// Difference: subtract right circle from left circle
if (smoothness > 0.001) {
result = smoothSubtraction(circle2, circle1, smoothness);
} else {
result = max(circle1, -circle2);
}
}
// Convert SDF to visible shape
float pixelWidth = fwidth(result);
float shape = 1.0 - smoothstep(-pixelWidth, pixelWidth, result);
return half4(shape, shape, shape, 1.0);
}More shapes
Star
float starSDF(float2 point, float2 center, float radius, int points) {
float2 p = point - center;
// Convert to polar coordinates
float angle = atan2(p.y, p.x);
float distance = length(p);
// Create star pattern by modulating radius
float angleStep = 6.28318530718 / float(points); // 2π divided by number of points
// Use fmod for proper modulo operation, then center the range
float sectorAngle = fmod(angle + 3.14159265359, angleStep) - angleStep * 0.5;
// Inner and outer radius for star points
float outerRadius = radius;
float innerRadius = radius * 0.5;
// Distance varies based on angle - creates star points
// Use absolute value for symmetry within each sector
float t = abs(sectorAngle) / (angleStep * 0.5);
float starRadius = mix(outerRadius, innerRadius, t);
return distance - starRadius;
}
The star works in polar coordinates. It splits the full circle into one sector per point, works out how far the pixel's angle is from the middle of its sector, and uses that to pick a radius between outerRadius (at a tip) and innerRadius (halfway between tips). The SDF is then distance - starRadius, the same pattern as the circle with a radius that depends on angle.
This isn't an exact distance. It measures along the ray from the center, not to the nearest point on the edge, and the linear mix over angle gives slightly curved sides. The sign is still correct, so it draws cleanly with fwidth anti-aliasing.
Rounded rectangle
float roundedRectSDF(float2 point, float2 center, float2 size, float cornerRadius) {
// Translate to center
float2 p = abs(point - center);
// Shrink rectangle by corner radius
float2 halfSize = size * 0.5;
float2 shrunkSize = halfSize - cornerRadius;
// Distance to the shrunken rectangle's corner
float2 cornerDist = p - shrunkSize;
// Outside the shrunken rectangle: distance to rounded corner
float outsideDist = length(max(cornerDist, 0.0));
// Inside the shrunken rectangle: distance to nearest edge
float insideDist = min(max(cornerDist.x, cornerDist.y), 0.0);
// Subtract corner radius to account for rounding
return outsideDist + insideDist - cornerRadius;
}
This is the box SDF with one extra idea: subtracting a constant from any SDF grows the shape by that amount and rounds its corners. Shrink the box by cornerRadius first, then subtract cornerRadius from the result, and you're back to the original size with corners of exactly that radius.
Two related one-liners work on any SDF d:
d - rgrows the shape byr(and rounds sharp corners).abs(d) - tturns a filled shape into an outline of thickness2 * t, centered on the original edge.
The face scene later in this chapter uses abs(...) - 0.02 to draw its mouth and eyebrows as lines.
Heart
float heartSDF(float2 point, float2 center, float scale) {
// Translate and scale
float2 p = (point - center) / scale;
// Heart equation: (x²+y²-1)³ - x²y³ = 0
// We evaluate this equation instead of solving for the true distance
// Flip Y to make heart right-side up
p.y = -p.y;
// Shift the heart so it sits around the center
float x = p.x;
float y = p.y - 0.5; // Adjust center
// Negative inside the heart, positive outside
float heartEq = pow(x*x + y*y - 1.0, 3.0) - x*x * y*y*y;
// Rough normalization so values grow more like a distance
float distance = heartEq / (3.0 * pow(x*x + y*y, 1.5) + 1.0);
return distance * scale;
}
The heart starts from a classic implicit curve, an equation that's zero on the outline, negative inside, and positive outside. That gets the sign right but the magnitude isn't a distance, so the function divides by a rough normalization term. Treat it as an approximation: it anti-aliases fine with fwidth, but glows or outlines built from its values will be uneven in thickness. The p.y = -p.y flip is there because SwiftUI's y axis points down and the equation assumes y points up.
Transforming SDFs
To move, rotate, or scale a shape, you transform the point you feed into the SDF, not the shape itself:
// Rotation transformation
float2 rotate(float2 point, float angle) {
float s = sin(angle);
float c = cos(angle);
return float2(
point.x * c - point.y * s,
point.x * s + point.y * c
);
}
// Scale transformation
float2 scale(float2 point, float factor) {
return point / factor; // Divide to make the shape bigger; multiply the SDF result by factor
}
This works in reverse. Subtracting center from the point moves the shape to center. Rotating the point by angle makes the shape appear rotated by -angle. Dividing the point by 2 makes the shape twice as big, because a pixel now has to be twice as far from the center to reach the same edge. Scaling also changes the distance units, so multiply the result by the same factor to keep real distances (more on that in the pitfalls below).
The star below spins because the shader rotates the coordinates by time * rotationSpeed before calling starSDF. The Xcode project passes date.timeIntervalSince(startDate) as time, so the value stays small and keeps its float precision. It also uses the interior distance for color: smoothstep(-0.15, -0.05, starDist) is a gradient that runs from deep inside the star to near its edge, which gives the bright center.
The return value half4(starColor * star, star) multiplies the color by the coverage. SwiftUI expects premultiplied alpha, so a pixel that is half covered must have its color scaled by 0.5 as well as its alpha. Returning half4(starColor, star) would make the anti-aliased edge too bright.
Rotating Star with SDF Transformations
Animated star demonstrating SDF coordinate transformations, rotation matrices, and gradient coloring with inner glow effects
[[ stitchable ]] half4 rotatingStarSDF(
float2 position,
half4 color,
float2 size,
float time, // Animation time
float rotationSpeed // How fast it rotates
) {
float2 uv = position / size;
float2 centered = uv - 0.5;
// Rotate the coordinate system
float angle = time * rotationSpeed;
float2 rotatedPoint = rotate(centered, angle);
// Calculate star distance in rotated space
float starDist = starSDF(rotatedPoint, float2(0.0, 0.0), 0.2, 5);
// Render with smooth edges
float pixelWidth = fwidth(starDist);
float star = 1.0 - smoothstep(-pixelWidth, pixelWidth, starDist);
// Add color based on distance for depth effect
float innerGlow = 1.0 - smoothstep(-0.15, -0.05, starDist);
half3 starColor = mix(
half3(1.0, 0.8, 0.2), // Golden edge
half3(1.0, 1.0, 0.9), // Bright center
innerGlow
);
return half4(starColor * star, star);
}Building a scene from SDFs
The face below combines everything in this chapter. Each feature is its own SDF: a rounded box for the head, squashed circles for the eyes, abs(curve) - thickness lines for the mouth and brows. The shader turns each one into a coverage value with smoothstep, then paints it over the previous layer with mix, back to front. That layering is how you build any 2D scene from SDFs: each shape gets its own color, and later layers cover earlier ones.
A few details to look for:
p = (uv - 0.5) * 2.0gives a -1 to 1 range, andp.y = -p.ymakes +y point up so "eyes above mouth" reads naturally in the numbers.leftEyePos.y *= eyeSquishscales one axis to make an oval. Non-uniform scaling means the eye's distance values are no longer exact, which is fine for a small squash.- Setting
mouth = 1000.0outside a range of x is a quick way to clip a shape: a huge distance means "nowhere near this shape". The clipped ends are hard cuts rather than anti-aliased edges. pixelWidth = length(fwidth(p)) * 0.5computes the pixel size once from the coordinates instead of callingfwidthon every SDF. All the distances are in the samepunits, so one width serves them all.
Complex SDF Scene - Animated Face
Advanced SDF composition demonstrating layered facial features, animated expressions, and proper SDF blending techniques for realistic character rendering
[[ stitchable ]] half4 sdfScene(
float2 position,
half4 color,
float2 size,
float time
) {
float2 uv = position / size;
float2 p = (uv - 0.5) * 2.0; // -1 to 1 range
p.y = -p.y; // Flip so +y points up (SwiftUI's y grows downward)
// Head shape - rounded square for a friendlier look
float2 headSize = float2(0.5, 0.55);
float2 d = abs(p) - headSize;
float head = length(max(d, 0.0)) + min(max(d.x, d.y), 0.0) - 0.15;
// Eyes - not holes, but friendly ovals
float eyeSquish = 0.8; // Make eyes slightly oval
float2 leftEyePos = p - float2(-0.18, 0.12);
leftEyePos.y *= eyeSquish;
float leftEye = length(leftEyePos) - 0.06;
float2 rightEyePos = p - float2(0.18, 0.12);
rightEyePos.y *= eyeSquish;
float rightEye = length(rightEyePos) - 0.06;
// Animated pupils that follow a gentle pattern
float lookX = sin(time * 0.8) * 0.02;
float lookY = cos(time * 1.2) * 0.01;
float2 leftPupilPos = p - float2(-0.18 + lookX, 0.12 + lookY);
float leftPupil = length(leftPupilPos) - 0.03;
float2 rightPupilPos = p - float2(0.18 + lookX, 0.12 + lookY);
float rightPupil = length(rightPupilPos) - 0.03;
// Eye sparkles for life
float2 leftSparklePos = p - float2(-0.20, 0.14);
float leftSparkle = length(leftSparklePos) - 0.015;
float2 rightSparklePos = p - float2(0.16, 0.14);
float rightSparkle = length(rightSparklePos) - 0.015;
// Nose - small and cute
float2 nosePos = p - float2(0.0, 0.0);
float nose = length(nosePos * float2(1.5, 1.0)) - 0.04;
// Mouth - proper smile using SDF curve
float2 mouthPos = p - float2(0.0, -0.15);
// Create smile curve using parabola
float mouthCurve = mouthPos.y + mouthPos.x * mouthPos.x * 2.0;
float mouthWidth = 0.15 + sin(time * 2.0) * 0.03; // Gentle animation
float mouth = abs(mouthCurve) - 0.02;
// Limit mouth to center area
if (abs(mouthPos.x) > mouthWidth) {
mouth = 1000.0;
}
// Cheeks - animated blush circles
float blushSize = 0.08 + sin(time * 3.0) * 0.02;
float leftCheek = length(p - float2(-0.28, -0.05)) - blushSize;
float rightCheek = length(p - float2(0.28, -0.05)) - blushSize;
// Eyebrows for expression
float2 leftBrowPos = p - float2(-0.18, 0.25);
float leftBrow = abs(leftBrowPos.y - leftBrowPos.x * 0.3) - 0.015;
if (abs(leftBrowPos.x) > 0.1) leftBrow = 1000.0;
float2 rightBrowPos = p - float2(0.18, 0.25);
float rightBrow = abs(rightBrowPos.y + rightBrowPos.x * 0.3) - 0.015;
if (abs(rightBrowPos.x) > 0.1) rightBrow = 1000.0;
// Build the face using proper layering
float pixelWidth = length(fwidth(p)) * 0.5;
// Start with head
float faceShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, head);
half3 faceColor = half3(1.0, 0.9, 0.8); // Skin tone
// Add eyes (white part)
float eyeWhites = min(leftEye, rightEye);
float eyeShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, eyeWhites);
faceColor = mix(faceColor, half3(1.0, 1.0, 1.0), eyeShape * faceShape);
// Add pupils
float pupils = min(leftPupil, rightPupil);
float pupilShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, pupils);
faceColor = mix(faceColor, half3(0.2, 0.3, 0.4), pupilShape * faceShape);
// Add sparkles
float sparkles = min(leftSparkle, rightSparkle);
float sparkleShape = 1.0 - smoothstep(-pixelWidth * 0.5, pixelWidth * 0.5, sparkles);
faceColor = mix(faceColor, half3(1.0, 1.0, 1.0), sparkleShape * faceShape);
// Add nose
float noseShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, nose);
faceColor = mix(faceColor, half3(0.9, 0.8, 0.7), noseShape * faceShape * 0.3);
// Add mouth
float mouthShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, mouth);
faceColor = mix(faceColor, half3(0.8, 0.4, 0.5), mouthShape * faceShape);
// Add cheeks (blush with transparency)
float cheeks = min(leftCheek, rightCheek);
float cheekShape = 1.0 - smoothstep(-pixelWidth * 2.0, pixelWidth * 2.0, cheeks);
faceColor = mix(faceColor, half3(1.0, 0.7, 0.8), cheekShape * faceShape * 0.4);
// Add eyebrows
float brows = min(leftBrow, rightBrow);
float browShape = 1.0 - smoothstep(-pixelWidth, pixelWidth, brows);
faceColor = mix(faceColor, half3(0.7, 0.6, 0.5), browShape * faceShape);
// Background
half3 bgColor = half3(0.3, 0.5, 0.7); // Soft blue
half3 finalColor = mix(bgColor, faceColor, faceShape);
// Add subtle rim light
float rimLight = 1.0 - smoothstep(-0.02, 0.02, head);
finalColor += half3(0.1, 0.1, 0.2) * rimLight * (1.0 - faceShape);
return half4(finalColor, 1.0);
}Performance
Skipping shapes that can't win
Every pixel evaluates your whole SDF, so the cost grows with each shape you add. The most useful optimization is to skip an expensive shape when a cheap test proves it can't be the closest one:
// Straightforward: every pixel evaluates all three shapes
float complexSDF(float2 p) {
float shape1 = circleSDF(p, float2(0.1, 0.1), 0.2);
float shape2 = rectangleSDF(p, float2(-0.1, -0.1), float2(0.3, 0.3));
float shape3 = starSDF(p, float2(0.0, 0.0), 0.15, 5);
return min(min(shape1, shape2), shape3);
}
// Cheaper: only evaluate the star (atan2, fmod) when it could be the closest shape
float optimizedSDF(float2 p) {
float circle = length(p - float2(0.1, 0.1)) - 0.2;
float2 rectP = abs(p - float2(-0.1, -0.1)) - float2(0.15, 0.15);
float rect = length(max(rectP, 0.0)) + min(max(rectP.x, rectP.y), 0.0);
float result = min(circle, rect);
// The star fits inside a circle of radius 0.15 at the origin, so it is never
// closer than that bounding circle. If the bound is already farther than
// result, the star can't change the min: skip it.
float starBound = length(p) - 0.15;
if (starBound > result) return result;
float star = starSDF(p, float2(0.0, 0.0), 0.15, 5);
return min(result, star);
}
The test has to be conservative. A bounding circle works because the true distance to the star can never be smaller than the distance to a circle that contains it. An early exit like if (result > 0.1) is not safe: a pixel can be far from the circle and rectangle yet right on the star.
Two limits on how much this buys you. The Metal compiler inlines small functions, so writing circleSDF out by hand doesn't make it faster; the saving comes only from work you skip. And GPUs run neighboring pixels in groups that execute together, so if any pixel in a group needs the star, the whole group waits for it. Early exits pay off when large areas of the view are far from the expensive shape.
What makes an SDF expensive
Cost follows the operations involved. A circle is one length and a subtraction. A box adds abs, max, and min, still very cheap. Smooth booleans add a few multiplies on top of min or max. Shapes built from atan2, pow, or fmod (the star and the heart) cost more, and anything with a loop, like a polygon with many sides or many blobs, multiplies its body by the iteration count.
Common pitfalls
Pitfall 1: Scaling coordinates without fixing the distance
// WRONG: Distance doesn't scale properly with transformations
float scaledCircle = circleSDF(p * 2.0, center, radius); // Distance is wrong!
// CORRECT: Account for scaling in distance calculation
float scaledCircle = circleSDF(p * 2.0, center, radius) / 2.0; // Divide by scale factor
circleSDF(p * 2.0, ...) draws the circle at half size, because every point is pushed twice as far out. The distance it returns is measured in the scaled space, so it's twice the real distance. Dividing by the scale factor brings it back. Only uniform scaling can be corrected exactly; squashing one axis (like the eyes in the face scene) gives approximate distances.
Pitfall 2: Anti-aliasing with a fixed width
// WRONG: Fixed anti-aliasing width
float shape = 1.0 - smoothstep(-0.01, 0.01, sdf); // Breaks at different resolutions
// CORRECT: Resolution-independent anti-aliasing
float pixelWidth = fwidth(sdf);
float shape = 1.0 - smoothstep(-pixelWidth, pixelWidth, sdf);
With uv coordinates, a fixed 0.01 on each side means a band 2% of the view wide. On a view 1,000 pixels wide that's a 20-pixel blur; on a 100-pixel view it's 2 pixels. fwidth keeps the band at about two pixels whatever the size.
Pitfall 3: Adding distances
// Common misunderstanding: thinking in terms of "adding" shapes
float wrong = shape1 + shape2; // This doesn't make sense for SDFs
// Correct: Use proper SDF boolean operations
// (union is a reserved word in Metal, so it can't be a variable name)
float unionShape = min(shape1, shape2); // Combine shapes
float intersectionShape = max(shape1, shape2); // Only where both exist
float differenceShape = max(shape1, -shape2); // Subtract shape2 from shape1
The sum of two distances isn't the distance to anything, and its zero line falls somewhere between the two shapes. Combine shapes with min, max, and their smooth versions.
Pitfall 4: Too many shapes per pixel
// WRONG: Computing too many shapes every pixel
float result = 1000.0;
for (int i = 0; i < 100; i++) { // 100 shapes per pixel!
result = min(result, someSDF(p, i));
}
// CORRECT: Use spatial subdivision or early exits
if (roughDistance > 0.5) return roughDistance; // Early exit when far away
// Only compute detailed SDF when close
A hundred shapes means a hundred SDF evaluations for every pixel, every frame. Use a conservative bounding test like the one in the performance section so that most pixels skip most of the shapes.
Challenges
Challenge 1: Gooey button modifier

Create a gooeyBackground shader that draws a button whose shape drips like honey.
What You'll Learn:
- How smooth unions make separate shapes merge organically
- Simple gravity in a shader: position from the formula
y = 0.5 * g * t² - Making drops grow out of the button instead of popping into existence
- Working within
colorEffect's limits: it can only recolor pixels inside the view's frame
Metal Shader Goal:
// Create a viscous dripping effect with:
// - Drops that emerge from within the button shape (not sudden spawning)
// - Gravity-based acceleration using physics formula: y = 0.5 * g * t²
// - Fixed X positions distributed across button width
// - Teardrop shapes that elongate based on fall velocity
// - Smooth merging with button and other drops (smooth union with viscosity)
// - Proper handling of canvas boundaries (skip drops, not fade)
The shader receives the view size, the elapsed time, and the viscosity (in that order after position and color), and draws the button shape itself as a rounded box SDF. colorEffect can't draw outside the view, so the drops can only fall as far as the view is tall. The solution in the Xcode project gives the background room by padding the label 100 points vertically and keeping the button shape small in the middle.
SwiftUI Scaffolding:
struct GooeyButtonView: View {
@State private var animationTime: Float = 0.0
@State private var viscosity: Float = 0.1
@State private var dropColor = Color.blue
let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
var body: some View {
VStack(spacing: 30) {
Text("Gooey Button Demo")
.font(.title2)
.padding()
// The actual gooey button
Button(action: { print("Gooey tap!") }) {
Text("Tap Me")
.font(.title3)
.foregroundColor(.white)
.padding(.horizontal, 40)
.padding(.vertical, 20)
}
.background(
RoundedRectangle(cornerRadius: 15)
.fill(dropColor)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.gooeyBackground(
.float2(proxy.size),
.float(animationTime),
.float(viscosity)
))
}
)
// Controls
VStack(alignment: .leading, spacing: 15) {
HStack {
Text("Viscosity:")
Slider(value: $viscosity, in: 0.05...0.3)
Text("\(viscosity, specifier: "%.2f")")
}
HStack {
Text("Color:")
ColorPicker("", selection: $dropColor)
.labelsHidden()
}
}
.padding()
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
.onReceive(timer) { _ in
animationTime += 1/60.0
}
}
}
Hints:
- Use a smooth union with a large
k(the viscosity slider, 0.05 to 0.3) between the button and each drop. - Give each drop its own time offset (
dropId * 2.3, for example) and loop it withfmod(time + offset, duration), so drops fall one after another. - Grow the drop's radius from zero with
smoothstepat the start of each cycle, and while it's still small, clip it to the button withmax(dropSDF, buttonSDF)so it appears from inside the button. - Divide the drop's local y coordinate by a stretch factor that grows with velocity (
g * t) to make it a falling teardrop. - Return premultiplied color:
half4(finalColor * shape, shape).
Challenge 2: Lava lamp simulator

Create a lavaLamp shader that animates wax blobs rising and falling in a lava lamp.
What You'll Learn: How to combine several animated SDFs with smooth unions to get blobs that merge and split.
Metal Shader Goal: Metal Shader Goal:
// Create a lava lamp effect with:
// - 3-5 blobs that rise and fall at different speeds
// - Blobs that merge when close and split when moving apart
// - Heat distortion effect using sin waves
// - Color gradient based on blob temperature (height)
SwiftUI Scaffolding: SwiftUI Scaffolding:
struct LavaLampView: View {
@State private var animationTime: Float = 0.0
@State private var temperature: Float = 0.5
@State private var blobCount: Float = 3.0
let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("Lava Lamp Simulator")
.font(.title2)
.padding()
// Lava lamp container
ZStack {
// Glass container outline
RoundedRectangle(cornerRadius: 50)
.stroke(Color.gray, lineWidth: 3)
// The lava effect
RoundedRectangle(cornerRadius: 47)
.fill(Color.black)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.lavaLamp(
.float2(proxy.size),
.float(animationTime),
.float(temperature),
.float(blobCount)
))
}
.padding(3)
}
.frame(width: 200, height: 400)
// Controls
VStack(spacing: 15) {
HStack {
Text("Heat: \(temperature, specifier: "%.1f")")
Slider(value: $temperature, in: 0.1...1.0)
}
HStack {
Text("Blobs: \(Int(blobCount))")
Slider(value: $blobCount, in: 2...5, step: 1)
}
}
.padding()
}
.onReceive(timer) { _ in
animationTime += 1/60.0 * temperature
}
}
}
Hints:
- Start the combined distance at a large value (
1000.0) and fold each blob in with a smooth union inside a loop overint(blobCount). - Each blob's vertical position can be
sin(time * speed + phase) * 0.35in centered coordinates, with a different speed and phase per blob. - The lamp is 200 by 400 points, so multiply
centered.xbysize.x / size.yor your round blobs will come out as tall ellipses. - Tie the smooth union's
kto the heat slider so hot wax merges more readily. - Add a slight horizontal wobble with
sin(time * frequency + y), and fake heat distortion by adding a smallsin(centered.y * 20.0 + time)term to the final distance.
Challenge 3: Magnetic blob field

Create a magneticGoo shader that renders up to four draggable blobs that merge smoothly when they get close, like mercury droplets.
What You'll Learn: How the smooth minimum (smin) creates gooey connections between shapes, and how to blend per-shape colors.
Metal Shader Goal:
// Create an effect where:
// - Up to 4 circular blobs can be positioned on screen
// - Blobs merge smoothly as they approach each other
// - Each blob has its own color that blends in merge zones
// - Add subtle animation (breathing/pulsing)
// - Include soft glow effect around blobs
// Use smin() for smooth blending between SDFs
Unlike the earlier shaders, this one doesn't take a size. The node positions come from SwiftUI in points, and position is in points in the same view, so you can compute distances directly in points with no uv conversion. That also means radii and k are in points: the solution uses a 50-point radius and k = 40. Match the argument order in the scaffold: time, then a position and a color for each of the four nodes, then nodeCount. The scaffold sends each color with .float4, so declare those parameters as float4 (the alpha is always 1).
SwiftUI Scaffolding: SwiftUI Scaffolding:
import SwiftUI
struct MagneticGooView: View {
@State private var nodes: [GooNode] = [
GooNode(position: CGPoint(x: 150, y: 300), color: UIColor(red:0.0, green: 0.8, blue: 1.0, alpha: 1.0)), // Cyan
GooNode(position: CGPoint(x: 250, y: 300), color: UIColor(red:0.8, green: 0.0, blue: 1.0, alpha: 1.0)), // Purple
GooNode(position: CGPoint(x: 200, y: 400), color: UIColor(red:1.0, green: 0.5, blue: 0.0, alpha: 1.0)), // Orange
GooNode(position: CGPoint(x: 100, y: 400), color: UIColor.systemPink) // Orange
]
@State private var draggedNode: GooNode.ID?
let startTime = Date()
var body: some View {
TimelineView(.animation) { timeline in
ZStack {
// Background with goo effect
Rectangle()
.fill(.black)
.colorEffect(
ShaderLibrary.magneticGoo(
.float(Float(timeline.date.timeIntervalSince(startTime))),
.float2(nodes[safe: 0]?.position ?? .zero),
.float4(
colorForNode(0).x,
colorForNode(0).y,
colorForNode(0).z,
1.0
),
.float2(nodes[safe: 1]?.position ?? .zero),
.float4(
colorForNode(1).x,
colorForNode(1).y,
colorForNode(1).z,
1.0
),
.float2(nodes[safe: 2]?.position ?? .zero),
.float4(
colorForNode(2).x,
colorForNode(2).y,
colorForNode(2).z,
1.0
),
.float2(nodes[safe: 3]?.position ?? .zero),
.float4(
colorForNode(3).x,
colorForNode(3).y,
colorForNode(3).z,
1.0
),
.float(Float(nodes.count))
)
)
// Invisible drag targets
ForEach(nodes) { node in
Circle()
.fill(.white.opacity(0.01)) // Almost invisible
.frame(width: 100, height: 100)
.position(node.position)
.gesture(
DragGesture()
.onChanged { value in
if draggedNode == nil {
draggedNode = node.id
}
if draggedNode == node.id,
let index = nodes.firstIndex(where: { $0.id == node.id }) {
nodes[index].position = value.location
}
}
.onEnded { _ in
draggedNode = nil
}
)
}
}
.ignoresSafeArea()
}
}
private func colorForNode(_ node: Int) -> SIMD4<Float> {
(nodes[safe: node]?.color ?? .white).toFloat4
}
}
struct GooNode: Identifiable {
let id = UUID()
var position: CGPoint
var color: UIColor
}
// Helper extensions
extension CGPoint {
var simd2: SIMD2<Float> {
SIMD2<Float>(Float(x), Float(y))
}
}
extension UIColor {
var toFloat4: SIMD4<Float> {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
// Get the RGBA components of the UIColor
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
// Convert to SIMD4<Float>
return SIMD4<Float>(Float(red), Float(green), Float(blue), Float(alpha))
}
}
extension Array {
subscript(safe index: Int) -> Element? {
indices.contains(index) ? self[index] : nil
}
}
If you're adding this to the course's Xcode project, Utils.swift already defines CGPoint.simd2 and Array's subscript(safe:). Delete those two extensions from the scaffold or you'll get redeclaration errors.
Hints:
- The solution uses the cubic smooth minimum:
h = max(k - abs(a - b), 0.0) / k, thenmin(a, b) - h * h * h * k / 6.0. It blends a little more softly than the quadratic version earlier in the chapter. - Weight each blob's color by
1.0 / (1.0 + distance * distance * 0.001)and divide the summed color by the summed weights, so the color in a merge zone comes from whichever blobs are nearby. - Add breathing with
radius + sin(time * 2.0 + blobIndex) * 5.0. - Glow outside the blobs:
exp(-field * 0.02)fades over a few dozen points. - Interior shading:
1.0 - smoothstep(-20.0, 0.0, field)ramps from 0 at the edge to 1 at 20 points inside, which gives the blobs some depth.
Want the Challenges Solutions?
Get the full Xcode project with solutions to all challenges, bonus examples, and clean, runnable code.
Get the Full Project →Validation Questions
Before proceeding to Chapter 9, test your understanding:
1. What does it mean for a Signed Distance Function to return negative values?
Answer: The point is inside the shape, and the magnitude is how far inside. If a circle SDF returns -0.1, the point is 0.1 units from the nearest edge, on the inside. Every SDF in this chapter uses this convention, and the boolean operations depend on it: min and max only produce the union and intersection because "negative" always means "inside".
2. Why do we use min(d1, d2) for union and max(d1, d2) for intersection in SDF boolean operations?
Answer: A point is in the union if it's inside at least one shape, meaning at least one distance is negative. min is negative exactly when either input is. A point is in the intersection only if it's inside both shapes, meaning both distances are negative. max is negative only when both inputs are. Outside the shapes, min also gives the distance to the nearer surface, which is the correct distance to the union.
3. How does fwidth() ensure resolution-independent anti-aliasing in SDF rendering?
Answer: fwidth(d) is how much d changes between neighboring pixels, so it's the size of one pixel in distance units. Using it as the half-width of smoothstep(-w, w, d) makes the edge fade over about two pixels whatever the view size or zoom. A fixed width like 0.01 is a fixed fraction of the view instead: blurry on large views and jagged on small ones.
4. Why must distance scaling be handled carefully when transforming SDFs?
Answer: An SDF returns distance in the units of the coordinates you give it. Evaluating sdf(p * s) shrinks the shape by s, and the distance it returns is measured in the scaled space, so it's s times too large. Divide by s: sdf(p * s) / s. The equivalent for growing a shape is sdf(p / s) * s. If you skip this, fwidth anti-aliasing still adapts, but anything that uses the distance values directly (outlines, glows, smooth unions) comes out the wrong thickness.
5. What makes smooth boolean operations "smooth" and when would you use them?
Answer: A hard min switches from one shape's distance to the other's along a sharp crease. The smooth version subtracts a small correction wherever the two distances are within k of each other, largest where they're equal. That pulls the surface outwards in the zone between the shapes and rounds the crease into a fillet; with shapes close enough, it forms a bridge between them. Use it for organic shapes, liquids, and blobs that should merge as they approach, and keep k small when you only want softened joins.
6. How do SDF transformations differ from traditional graphics transformations?
Answer: Traditional graphics moves the shape's vertices. With SDFs you transform the point you query, which means applying the inverse transform. To move a shape to c, evaluate it at p - c. To rotate it by an angle, rotate the point by minus that angle. To scale it up by s, evaluate at p / s and multiply the distance by s. The SDF itself never changes, so one function can draw any number of copies at different positions, angles, and sizes.
Next Chapter Preview: Several shaders in this chapter already took a time argument. Chapter 9 is about time itself: how to drive shaders from SwiftUI with TimelineView, how to keep time values precise, and how to shape motion with sine waves, noise, and easing curves so animation feels organic instead of mechanical.