Shaders From Zero · Episode 20
Shadows
Shadows is Episode 20 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
A scene with lighting but no shadows looks fake. Surfaces seem to glow on their own; objects float without weight; the sphere and the floor in Episode 19 felt like two unrelated images stacked on top of each other. Shadows are what tie objects to each other and to the ground — they're the visual proof that light came from somewhere and was blocked on the way.
The good news: in a raymarcher, a shadow is just another small raymarch. From the point you hit, you cast a new ray toward the light. If anything is in the way, the point is in shadow. That's it. Same loop, same SDF, different start and direction.
Hard shadow rays
From the hit point, cast a new ray toward the light. March it the same way you march the camera ray. If you hit anything before reaching the light's distance, the original hit point is in shadow.
float hardShadow(vec3 ro, vec3 rd, float minT, float maxT) {
float t = minT;
for (int i = 0; i < 64; i++) {
float d = sceneSDF(ro + rd * t);
if (d < 0.001) return 0.0; // in shadow
if (t > maxT) break;
t += d;
}
return 1.0; // lit
}
Two parameters matter:
minT = 0.02— a small offset to avoid self-shadowing. Without it, the surface shadows itself: the hit point is technically on the surface, so the first SDF sample is essentially zero, and every pixel comes back as "in shadow." The fix is to start the shadow ray a hair off the surface — either by bumpingtforward to0.02, or by offsetting the origin along the normal (we'll do both in the demo).maxT = 20.0— how far away the light is. For a directional light (parallel rays from the sun), set this large; the ray needs to keep marching until it escapes the scene. For a point light, set it to the actual distance to the light.
The result is a binary 0 or 1, which you multiply into the diffuse term:
diff = max(dot(N, L), 0.0) * shadow. Lit pixels stay lit; shadowed
pixels get their direct light killed.
Soft shadows — Quilez's penumbra trick
Hard shadows have crisp boundaries — every pixel is either fully lit or fully dark. Real shadows soften with distance from the caster. The shadow directly under a coin is sharp; the shadow of a tree branch on the grass below has a fuzzy edge. The softness depends on the angular size of the light and the distance between caster and receiver.
Inigo Quilez published a clever cheat in 2010: track the minimum ratio
of d / t along the shadow ray. That ratio measures the closest
the ray ever came to a surface, scaled by how far it traveled to get there — which is
a good approximation of the penumbra angle.
float softShadow(vec3 ro, vec3 rd, float minT, float maxT, float k) {
float res = 1.0;
float t = minT;
for (int i = 0; i < 64; i++) {
float d = sceneSDF(ro + rd * t);
if (d < 0.001) return 0.0;
res = min(res, k * d / t);
if (t > maxT) break;
t += d;
}
return clamp(res, 0.0, 1.0);
}
The new ingredient is the line res = min(res, k * d / t). Every step
we shrink res toward whatever was the worst (smallest) ratio along the
way. If the ray cleanly misses every surface, res stays at 1.0 (fully
lit). If the ray grazes a surface — passes near it without hitting — d
gets small relative to t, res drops below 1.0, and we get
partial shadow.
k is the softness knob. Larger k sharpens the penumbra;
smaller k blurs it. Try k = 16.0 for a tight, slightly soft
edge; k = 4.0 for diffuse, big-area-light softness; k = 64.0
to push it back toward a hard shadow.
"We can take advantage of the fact that during the marching, we know how close the ray got to objects in the scene. We can use this distance to estimate how much the surface is occluded by other geometry." — Inigo Quilez, Soft Shadows in Raymarching
Same loop budget as the primary ray (64 iterations is plenty for shadows), same
SDF, one extra min per step. It's almost free.
Ambient occlusion (cheap version)
Shadows handle direct light — the rays coming straight from the light source. But scenes are also lit by ambient light, the soft glow that seems to come from everywhere (skylight, bounces, the general scattering of light around a room). Ambient light doesn't have a direction, so you can't shadow it with a single shadow ray. But surfaces in crevices receive less of it than surfaces out in the open, because the surrounding geometry blocks the ambient hemisphere.
The cheap raymarched approach: sample the SDF a few times along the surface normal, check whether the geometry is closer than expected. If it is, the local neighborhood is full of stuff — that point is occluded.
float ao(vec3 p, vec3 n) {
float occ = 0.0;
float sca = 1.0;
for (int i = 0; i < 5; i++) {
float h = 0.01 + 0.12 * float(i);
float d = sceneSDF(p + n * h);
occ += (h - d) * sca;
sca *= 0.95;
}
return clamp(1.0 - 3.0 * occ, 0.0, 1.0);
}
Five samples stepping outward along the normal at increasing distances. At each
sample, (h - d) measures the shortfall: if the SDF
reports a distance smaller than h, there's geometry closer than expected
and we accumulate occlusion. The sca factor weights nearer samples more
heavily.
The function returns a value in [0, 1]: 1.0 means no
occlusion (a wide-open surface), 0.0 means totally occluded (deep inside
a crevice). Multiply it into the ambient term.
Composing
The final shading equation, putting all three pieces together:
vec3 N = calcNormal(p);
float shadow = softShadow(p + N * 0.01, L, 0.0, 20.0, 16.0);
float aoTerm = ao(p, N);
float diff = max(dot(N, L), 0.0) * shadow;
vec3 col = uBaseColor * (ambient * aoTerm + diff);
Two multiplications, two roles:
shadowmodulates the direct light. If the shadow ray was blocked, no direct contribution survives.aoTermmodulates the ambient light. Ambient is "from everywhere," and occlusion blocks "everywhere" most strongly in tight corners.
Notice the p + N * 0.01 offset on the shadow ray's origin. Same idea
as minT: nudge off the surface so the shadow ray doesn't immediately
register the surface itself as a blocker.
The normal helper
You can't shade without a normal, and you can't AO without one either. The central-differences trick from Episode 19, repeated here because every shader this season needs it:
vec3 calcNormal(vec3 p) {
const float h = 0.0001;
vec2 k = vec2(1.0, -1.0);
return normalize(
k.xyy * sceneSDF(p + k.xyy * h) +
k.yyx * sceneSDF(p + k.yyx * h) +
k.yxy * sceneSDF(p + k.yxy * h) +
k.xxx * sceneSDF(p + k.xxx * h)
);
}
Four SDF samples at tetrahedron offsets, combined into a gradient direction.
That's the surface normal at p.
Common pitfalls
minTtoo small. The surface shadows itself — every pixel comes out dark. BumpminTto0.02or offset the shadow origin along the normal.minTtoo large. A visible gap appears between the object and its shadow on the ground, like the object is hovering.- Soft shadow
ktoo high. The penumbra collapses and you're back to hard shadows. Anything above 64 is barely distinguishable from hard. - Soft shadow
ktoo low. The shadow vanishes entirely into the ambient — try not to drop below 2.0. - AO sample range too large. The
hvalues reach past the local geometry into the scene at large, and you get false occlusion all over open surfaces. Keep the maxhmodest — about the scale of a surface bump. - Forgot to offset the shadow origin along the normal. Same
class of bug as
minTtoo small — the shadow ray starts on the surface, registers itself as a hit, and everything reads as shadowed.
Exercises
- Two lights. Compute two shadow values, two diffuse terms, and sum the contributions. Give the lights different colors and watch the shadows tint each other.
- Animate the light position around the scene with
uTime— orbit it on a circle in the XZ plane, or have it swing on a pendulum in Y. The shadow will sweep across the floor in real time. - Crank the soft-shadow
kto 64 and back down to 2. Watch the penumbra width respond. At what value does it start looking like a real shadow?
What's next
Episode 21 — Reflections. We bounce rays off shiny surfaces. Same machinery as a shadow ray, but pointed in the reflection direction and feeding its result back into the shading equation. The scene starts looking like polished chrome.