Shaders From Zero · Episode 24
A Complete Scene
A Complete Scene is Episode 24 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
This is the episode where Season 3 pays off. Every technique we built — geometry, normals, lighting, shadows, AO, materials, reflection, fog — composes into one image. Not a study, not a fragment of a scene: a finished piece. The kind of demo you can point at and say "that's what I can build."
The structure of this episode mirrors how you actually build a raymarched scene in practice. You lay down geometry first. You light it. You add shadows. You assign materials. You drop fog over the top. Five layers, in order, and at the end you have a portfolio piece running entirely in one fragment shader. Fork it, swap the SDFs, retune the materials — you have a template you can take anywhere.
The scene we're building
A small room set, lit cinematically. Concretely:
- A matte gray floor extending to the horizon.
- A central gold sphere — the hero element, metallic, reflective.
- A glass sphere to the right — fresnel-mixed refraction.
- A blue plastic torus that orbits the center, animated by
uTime. - A single warm key light from the upper-left, slightly desaturated ambient.
- Subtle atmospheric fog matching the sky for a seamless horizon.
This is the kind of scene people ship as portfolio pieces. It's not arbitrary — every element exercises a different technique from Season 3. The floor tests shadow reception. The gold tests reflection. The glass tests fresnel. The torus tests animation in the SDF. The fog ties the whole thing together.
Layer 1 — Geometry only
Before lighting, before materials, the first thing to get right is the SDF. If the shape is wrong, no amount of beautiful lighting will save it. So we start with a flat-shaded debug pass: color every pixel by the material ID it hit.
Callback to Episode 22: the scene SDF returns vec2(distance, materialId)
instead of just a float. Carry the ID through the march so we know which shading
function to call when the ray converges.
vec2 sceneSDF(vec3 p) {
float fl = p.y; // floor at y = 0
float gold = length(p - vec3(-1.2, 1.0, 0.5)) - 0.7;
float glass = length(p - vec3( 1.2, 0.85, -0.3)) - 0.55;
// orbiting torus, rotated around y by uTime
vec3 tp = p - vec3(0.0, 0.6, 0.0);
float ang = uTime * 0.5;
mat2 R = mat2(cos(ang), -sin(ang), sin(ang), cos(ang));
tp.xz = R * tp.xz;
vec2 q = vec2(length(tp.xz) - 1.8, tp.y);
float tor = length(q) - 0.18;
vec2 res = vec2(fl, 0.0); // floor = matId 0
if (gold < res.x) res = vec2(gold, 1.0); // gold = matId 1
if (glass < res.x) res = vec2(glass, 2.0); // glass = matId 2
if (tor < res.x) res = vec2(tor, 3.0); // torus = matId 3
return res;
}
Note the manual if (d < res.x) chain instead of min.
min on a vec2 takes the componentwise minimum, which
silently throws away the material ID. The conditional is the only way to carry
the ID through correctly. This will save you hours of debugging the first time
you forget.
The march loop returns the (t, matId) pair, and we color flatly:
vec3 matCol = vec3(0.5);
if (matId < 0.5) matCol = vec3(0.35); // floor — gray
else if (matId < 1.5) matCol = vec3(0.95, 0.7, 0.2); // gold
else if (matId < 2.5) matCol = vec3(0.7, 0.85, 1.0); // glass
else matCol = vec3(0.2, 0.4, 0.9); // torus
The result looks like a flat sticker book — every surface is a single color with no shading. That's the point: at this stage you're verifying the SDF, the positions, and the material IDs. Once that's solid, light the scene.
Layer 2 — Lighting
Callback to Episode 19. Compute the normal at the hit point with the gradient of the SDF, then do Lambert plus ambient. One warm key light from the upper-left.
vec3 calcNormal(vec3 p) {
vec2 e = vec2(0.001, 0.0);
return normalize(vec3(
sceneSDF(p + e.xyy).x - sceneSDF(p - e.xyy).x,
sceneSDF(p + e.yxy).x - sceneSDF(p - e.yxy).x,
sceneSDF(p + e.yyx).x - sceneSDF(p - e.yyx).x
));
}
vec3 lightDir = normalize(vec3(0.5, 0.8, 0.3));
vec3 lightCol = vec3(1.0, 0.95, 0.85); // warm key
float NdotL = max(dot(N, lightDir), 0.0);
vec3 lit = matCol * (lightCol * NdotL + vec3(0.18, 0.20, 0.25));
Notice the ambient is slightly blue-shifted. Warm key + cool fill is a cinematography trick that makes scenes feel three-dimensional even before shadows. Cheap, instant payoff.
Layer 3 — Shadows + AO
Callback to Episode 20. Soft shadows by Quilez's penumbra method — march a ray from the hit point toward the light and track the closest approach. AO by sampling the SDF at a few small offsets along the normal.
float softShadow(vec3 ro, vec3 rd, float mint, float maxt, float k) {
float res = 1.0;
float t = mint;
for (int i = 0; i < 32; i++) {
if (t > maxt) break;
float h = sceneSDF(ro + rd * t).x;
if (h < 0.001) return 0.0;
res = min(res, k * h / t);
t += h;
}
return clamp(res, 0.0, 1.0);
}
float calcAO(vec3 p, vec3 n) {
float occ = 0.0, sca = 1.0;
for (int i = 0; i < 5; i++) {
float h = 0.01 + 0.12 * float(i) / 4.0;
float d = sceneSDF(p + n * h).x;
occ += (h - d) * sca;
sca *= 0.95;
}
return clamp(1.0 - 3.0 * occ, 0.0, 1.0);
}
And the critical detail: when you launch the shadow ray, start it a tiny bit off the surface along the normal, not exactly on it:
float sh = softShadow(N * 0.01 + hitPos, lightDir, 0.02, 12.0, 16.0);
float ao = calcAO(hitPos, N);
vec3 lit = matCol * (lightCol * NdotL * sh + vec3(0.18, 0.20, 0.25)) * ao;
Without the N * 0.01 offset, the shadow ray starts inside the
surface it's leaving — sceneSDF returns a near-zero distance on
iteration zero, and the function thinks the point is occluded. Everything goes
black. This is the single most common bug in compositing raymarched scenes.
The scene now has gravity. Objects ground to the floor through their contact shadows; corners and crevices darken via AO. The image is starting to look real.
Layer 4 — Materials
Callback to Episode 22. Switch on material ID and run a different shading function per surface. The floor stays diffuse. The torus is a saturated diffuse plastic. The gold is metallic with a real reflection. The glass is a fresnel mix.
if (matId < 0.5) {
// floor — pure diffuse gray
vec3 base = vec3(0.32);
col = base * (lightCol * NdotL * sh + vec3(0.18, 0.20, 0.25)) * ao;
} else if (matId < 1.5) {
// gold — metallic, single-bounce reflection (Ep 21)
vec3 base = vec3(0.95, 0.72, 0.28);
vec3 diff = base * (lightCol * NdotL * sh + vec3(0.10, 0.10, 0.12));
vec3 R = reflect(rd, N);
vec3 refl = trace(hitPos + N * 0.01, R); // march again from the surface
col = mix(diff, refl * base, 0.65) * ao;
} else if (matId < 2.5) {
// glass — fresnel between sky-tinted refraction and reflection
float F = pow(1.0 - max(dot(N, -rd), 0.0), 5.0);
vec3 R = reflect(rd, N);
vec3 refl = trace(hitPos + N * 0.01, R);
vec3 refr = sky(refract(rd, N, 1.0 / 1.5)); // fake: sample sky in refracted dir
col = mix(refr * vec3(0.85, 0.95, 1.0), refl, 0.04 + 0.96 * F);
} else {
// torus — diffuse plastic with a small specular highlight
vec3 base = vec3(0.18, 0.42, 0.95);
float spec = pow(max(dot(reflect(-lightDir, N), -rd), 0.0), 32.0);
col = base * (lightCol * NdotL * sh + vec3(0.20, 0.22, 0.30)) * ao
+ vec3(1.0) * spec * sh * 0.5;
}
The glass uses a Schlick approximation for fresnel — at grazing angles the surface acts more like a mirror; head-on it shows what's behind. We cheat the refraction by sampling the sky directly instead of marching the bent ray through the surface. For a portfolio piece you'd do real refraction; here it saves a marching loop and looks ninety percent as good.
The gold sphere will now reflect the torus and the floor. The reflection isn't a hack — it's a second full raymarch from the hit point along the reflected direction. This is why the reflection includes shadows, the floor, and the torus's current orbit position. It's an honest mirror.
Layer 5 — Atmosphere (final)
Callback to Episode 23. Mix the shaded color with the fog color using Beer-Lambert falloff. The fog color matches the lower band of the sky, so distant surfaces dissolve into the horizon instead of clipping against it.
vec3 fogCol = vec3(0.55, 0.62, 0.72); // matches lower sky
float fogAmt = 1.0 - exp(-0.04 * t); // Beer-Lambert
col = mix(col, fogCol, fogAmt);
Two observations to internalize:
- Fog is applied after shadows, not before. Shadow rays don't get foggy, but the shaded color you produce does — so the shadow on the floor near the horizon fades into the fog naturally. If you fogged the shadow ray itself, distant shadows would brighten incorrectly.
- Fog is applied after reflection. The reflected scene inside the gold sphere is already fully shaded — including its own fog if the bounce hits something far. Then we apply fog one more time at the camera-to-gold distance. Both work in the correct direction.
That's the finished piece. Open the demo, set the stage selector to 5, and sit with it for a moment. Every line of code in the fragment shader is something you wrote across Episodes 17-23. Nothing is imported. Nothing is hidden. This is a complete 3D scene rendered from one function.
The full Stage-5 fragment shader (annotated)
uniform vec2 uResolution;
uniform float uTime;
varying vec2 vUv;
vec2 sceneSDF(vec3 p) {
float fl = p.y;
float gold = length(p - vec3(-1.2, 1.0, 0.5)) - 0.7;
float glass = length(p - vec3( 1.2, 0.85, -0.3)) - 0.55;
vec3 tp = p - vec3(0.0, 0.6, 0.0);
float ang = uTime * 0.5;
mat2 R = mat2(cos(ang), -sin(ang), sin(ang), cos(ang));
tp.xz = R * tp.xz;
vec2 q = vec2(length(tp.xz) - 1.8, tp.y);
float tor = length(q) - 0.18;
vec2 res = vec2(fl, 0.0);
if (gold < res.x) res = vec2(gold, 1.0);
if (glass < res.x) res = vec2(glass, 2.0);
if (tor < res.x) res = vec2(tor, 3.0);
return res;
}
vec3 calcNormal(vec3 p) {
vec2 e = vec2(0.001, 0.0);
return normalize(vec3(
sceneSDF(p + e.xyy).x - sceneSDF(p - e.xyy).x,
sceneSDF(p + e.yxy).x - sceneSDF(p - e.yxy).x,
sceneSDF(p + e.yyx).x - sceneSDF(p - e.yyx).x
));
}
// raymarch — returns (t, matId), or (-1, -1) on miss
vec2 march(vec3 ro, vec3 rd) {
float t = 0.0;
for (int i = 0; i < 128; i++) {
vec3 p = ro + rd * t;
vec2 r = sceneSDF(p);
if (r.x < 0.001) return vec2(t, r.y);
if (t > 40.0) break;
t += r.x;
}
return vec2(-1.0);
}
float softShadow(vec3 ro, vec3 rd, float mint, float maxt, float k) {
float res = 1.0, t = mint;
for (int i = 0; i < 32; i++) {
if (t > maxt) break;
float h = sceneSDF(ro + rd * t).x;
if (h < 0.001) return 0.0;
res = min(res, k * h / t);
t += h;
}
return clamp(res, 0.0, 1.0);
}
float calcAO(vec3 p, vec3 n) {
float occ = 0.0, sca = 1.0;
for (int i = 0; i < 5; i++) {
float h = 0.01 + 0.12 * float(i) / 4.0;
float d = sceneSDF(p + n * h).x;
occ += (h - d) * sca;
sca *= 0.95;
}
return clamp(1.0 - 3.0 * occ, 0.0, 1.0);
}
vec3 sky(vec3 rd) {
return mix(vec3(0.55, 0.62, 0.72), vec3(0.25, 0.35, 0.55), max(rd.y, 0.0));
}
// Reflection is a SECOND march from the hit point. No recursion in GLSL,
// so we shade the reflected hit with a cheap diffuse-only pass.
vec3 traceReflection(vec3 ro, vec3 rd, vec3 lightDir, vec3 lightCol) {
vec2 h = march(ro, rd);
if (h.x < 0.0) return sky(rd);
vec3 p = ro + rd * h.x;
vec3 N = calcNormal(p);
float NdotL = max(dot(N, lightDir), 0.0);
float sh = softShadow(p + N * 0.01, lightDir, 0.02, 12.0, 16.0);
vec3 base = vec3(0.32); // floor default
if (h.y > 0.5 && h.y < 1.5) base = vec3(0.95, 0.72, 0.28);
else if (h.y < 2.5) base = vec3(0.7, 0.85, 1.0);
else if (h.y > 2.5) base = vec3(0.18, 0.42, 0.95);
vec3 col = base * (lightCol * NdotL * sh + vec3(0.18, 0.20, 0.25));
float fogAmt = 1.0 - exp(-0.04 * h.x);
return mix(col, vec3(0.55, 0.62, 0.72), fogAmt);
}
void main() {
vec2 ndc = vUv * 2.0 - 1.0;
ndc.x *= uResolution.x / uResolution.y;
vec3 ro = vec3(0.0, 2.0, -5.0);
vec3 rd = normalize(vec3(ndc, 1.5));
vec3 lightDir = normalize(vec3(0.5, 0.8, 0.3));
vec3 lightCol = vec3(1.0, 0.95, 0.85);
vec2 hit = march(ro, rd);
vec3 col;
if (hit.x < 0.0) {
col = sky(rd);
} else {
vec3 p = ro + rd * hit.x;
vec3 N = calcNormal(p);
float matId = hit.y;
float NdotL = max(dot(N, lightDir), 0.0);
float sh = softShadow(p + N * 0.01, lightDir, 0.02, 12.0, 16.0);
float ao = calcAO(p, N);
if (matId < 0.5) {
vec3 base = vec3(0.32);
col = base * (lightCol * NdotL * sh + vec3(0.18, 0.20, 0.25)) * ao;
} else if (matId < 1.5) {
vec3 base = vec3(0.95, 0.72, 0.28);
vec3 diff = base * (lightCol * NdotL * sh + vec3(0.10, 0.10, 0.12));
vec3 refl = traceReflection(p + N * 0.01, reflect(rd, N), lightDir, lightCol);
col = mix(diff, refl * base, 0.65) * ao;
} else if (matId < 2.5) {
float F = pow(1.0 - max(dot(N, -rd), 0.0), 5.0);
vec3 refl = traceReflection(p + N * 0.01, reflect(rd, N), lightDir, lightCol);
vec3 refr = sky(refract(rd, N, 1.0 / 1.5)) * vec3(0.85, 0.95, 1.0);
col = mix(refr, refl, 0.04 + 0.96 * F);
} else {
vec3 base = vec3(0.18, 0.42, 0.95);
float spec = pow(max(dot(reflect(-lightDir, N), -rd), 0.0), 32.0);
col = base * (lightCol * NdotL * sh + vec3(0.20, 0.22, 0.30)) * ao
+ vec3(1.0) * spec * sh * 0.5;
}
float fogAmt = 1.0 - exp(-0.04 * hit.x);
col = mix(col, vec3(0.55, 0.62, 0.72), fogAmt);
}
col = pow(col, vec3(0.9)); // gentle gamma lift
gl_FragColor = vec4(col, 1.0);
}
Common pitfalls in compositing
- Material IDs lost in
minchains. Useif (d < res.x) res = vec2(d, id), nevermin(res, vec2(d, id)). The latter takes the componentwise min and silently swaps your IDs. - Reflection ray hitting the same surface. If you launch
reflect(rd, N)frompexactly, the first iteration seesd ≈ 0and returns the same surface. Always offset byp + N * 0.01. - Shadow ray starts inside the surface. Same bug, same fix. Without the offset every lit pixel reads as occluded and your whole scene goes black.
- Order matters: shadows before fog. Compute lighting, including shadow, and then fog the final shaded color. If you fog the shadow ray itself, distant shadows brighten and the horizon line breaks.
- Reflection happens before fog. The reflected scene is shaded and fogged at its own depth (the bounce distance), then the camera ray fogs the surface at the original hit depth. Two correct fog passes, one nested.
- SDF must compile fast. Every helper (normal, shadow, AO,
reflection) calls
sceneSDFdozens of times. Keep it tight. Asin/cosin the SDF is fine; aforloop inside it will tank your frame rate.
What's next — the end of the canonical 24
This is the end of the canonical curriculum. Look back at what you've built:
- Season 1 — shader literacy. You can read any GLSL on the web. You know what UVs are, what normals are, what a fragment shader does.
- Season 2 — eight portfolio-grade effects on real meshes: hologram, dissolve, water, glass, galaxy, portal, toon, post-processing. Each one is something you'd ship in a real product.
- Season 3 — full raymarched scenes from one fragment shader. SDFs, normals, lighting, shadows, AO, reflections, materials, volumetrics — and this episode, composing all of them into a finished piece.
Where to go from here:
- Shadertoy. Open it. Browse. You can now read any demo there — and most of them aren't more sophisticated than what you just wrote. The site that used to be hieroglyphics is now reference material. Fork anything that catches your eye; the language is yours.
onBeforeCompilein Three.js. The bridge between this season and the wider Three.js ecosystem. Splice your shaders intoMeshStandardMaterialto get raymarching effects on top of PBR-lit meshes. Hybrid scenes — Three.js for the cinematography, raymarching for the impossible objects.- WebGPU + TSL. The future of GPU programming for the web. Compute shaders unlock simulations the fragment shader can't reach: 100,000+ particle systems, FFT ocean models, real-time fluid. Three.js's TSL is the smoothest on-ramp.
- Production work. Spline. Bruno Simon-style portfolios. Product configurators. Game engine post-processing. You have the toolkit. The only thing left is to build.
You've completed the canonical 24. Now go build something.