WebGPU From Zero · Episode 11

Shadow Maps

Shadow Maps is Episode 11 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 11 · WebGPU From Zero · Season 2

Put three objects on a floor and light them. Without shadows they don't sit on the ground — they float above it, untethered, like stickers pasted onto a backdrop. Add one dark smudge of contact under each one and the whole scene snaps into place: suddenly the cube has weight, the sphere is resting, the torus is hovering on purpose. Shadows are the cheapest, most powerful trick in real-time graphics for making a pile of triangles feel like a place.

The technique is almost suspiciously simple, and it's the same one every game ships: a shadow map. Render the scene once from the light's point of view, but throw away the colors — keep only the depth, "how far is the nearest surface in this direction." Then render normally from the camera, and for each fragment ask one question: is anything closer to the light than I am? If yes, I'm in shadow. That's it. By the end of this page you'll have built it from raw WebGPU — a depth-only render pass into an offscreen texture, a sampler_comparison that does the depth test in hardware, soft PCF edges, and the bias tweak that fixes the notorious shadow acne — and you'll watch the shadows sweep across the floor as the light orbits.

0 fps
scene auto-orbits · drag the sliders
init…
A lit scene with no shadows. The objects float.

What you're looking at

A tiny diorama: a wide ground plane with a cube, a sphere, and a torus sitting on it, plus a single directional light (think "sun") that orbits the scene. The camera slowly auto-rotates so the scene is alive the instant the page paints. The stage selector walks you through building the shadow pipeline one layer at a time; the light angle slider moves the sun; bias tunes the acne fix; and the PCF toggle switches between hard and soft shadow edges. The badge bottom-left shows the backend (WebGPU or a fallback) and the shadow map resolution.

Each stage is the same scene with one more piece of the shadow machinery switched on. Watch the contact darkness appear, harden, soften, then detach-and-reattach as you abuse the bias. Here's the plan:

CAMERA PASS (what you see) LIGHT PASS (what the shadow map sees) ┌───────────────────────────┐ ┌───────────────────────────┐ │ scene → color + depth │ │ scene → depth ONLY │ │ + sample shadow map ◄────┼──────────┤ (from the light's MVP) │ └───────────────────────────┘ compare └───────────────────────────┘ per fragment: my light-space depth vs stored nearest depth behind? → in shadow

Stage 1 — A lit scene with no shadows

We start with ordinary forward rendering: project each mesh with a model-view- projection matrix, shade it with simple Lambert diffuse (max(dot(N, L), 0)) plus a little ambient, write color and depth, done. It looks fine at a glance — until you really look. The cube's bottom edge doesn't meet the floor. The sphere has no anchor. Nothing casts anything. Your eye keeps trying to place the objects in space and failing, because the single strongest depth cue humans have — contact shadow — is missing.

This is the "before." Everything from here on is about computing that one dark region honestly, by asking the light what it can see.

Stage 2 — The light's-eye depth pass

The key idea: render the scene a second time, from the light. For a directional light we use an orthographic projection (the sun's rays are parallel, so there's no perspective foreshortening) and point a "light camera" at the scene from the sun's direction. We don't care about color in this pass — we want the depth buffer, because the depth buffer is exactly "for each direction out of the light, how far away is the nearest surface." That depth buffer is the shadow map.

In WebGPU this is a render pass with no color attachment at all — only a depthStencilAttachment pointing at an offscreen depth24plus texture (created with RENDER_ATTACHMENT | TEXTURE_BINDING so we can sample it later — it's the most universally supported depth format for both jobs). We run the same meshes through a stripped-down vertex shader that uses the light's view-projection matrix, and an empty fragment stage. The GPU fills the depth texture for free.

Stage 2 visualizes that texture: we blit the raw shadow-map depth onto the screen as grayscale. Near the light is dark, far is bright. Move the light angle and watch the light's view of the scene swing around. This is the secret picture every shadowed frame is built on — most engines never show it to you.

// (a) THE SHADOW (DEPTH-ONLY) PASS — render scene depth from the light's MVP.
// One offscreen depth texture, sampleable later as the shadow map.
const SHADOW_SIZE = 1024;
const shadowTex = device.createTexture({
  size: [SHADOW_SIZE, SHADOW_SIZE],
  format: 'depth24plus',
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
});
const shadowView = shadowTex.createView();

// A pipeline with NO fragment target — depth only. We cull back faces (same as
// the camera) so single-sided geometry like the ground still lands in the map,
// and lean on a depth bias for acne. (Front-face culling is a common alternative
// when every caster is a closed solid — see pitfalls.)
const shadowPipeline = device.createRenderPipeline({
  layout: 'auto',
  vertex: { module: shadowModule, entryPoint: 'vs', buffers: [vbLayout] },
  primitive: { topology: 'triangle-list', cullMode: 'back' },
  depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
});

// per frame, BEFORE the camera pass:
const sp = encoder.beginRenderPass({
  colorAttachments: [],                                  // ← nothing! depth only
  depthStencilAttachment: {
    view: shadowView,
    depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store',
  },
});
sp.setPipeline(shadowPipeline);
sp.setBindGroup(0, lightBindGroup);   // holds the light's view-projection matrix
drawAllMeshes(sp);                       // same geometry, light's MVP
sp.end();

Stage 3 — Sample the shadow map (hard shadows)

Now the camera pass gets smart. For every fragment we already know its world position (we pass it from the vertex shader). We transform that world position by the same light view-projection matrix used to build the map — call the result the fragment's position in light clip space. Two things fall out of it: where this point lands in the shadow map (an x,y), and how far it is from the light (a depth). We look up the stored nearest depth at that x,y and compare:

  • If the stored depth is closer to the light than we are → something is between us and the sun → we're in shadow.
  • Otherwise we're the thing the light hits → lit.

One wrinkle that trips up everyone porting from OpenGL: WebGPU's clip-space Z is [0, 1], not GL's [-1, 1]. So when we convert the light-clip XY to a [0,1] texture UV we flip Y and halve-and-offset XY, but the Z (our comparison depth) is already in [0,1] — no remap needed. Get this wrong and your shadows are inverted or shifted by half the scene.

Stage 3 does the comparison with a single textureSampleCompareLevel tap — the hardware does the depth test for us and returns 1.0 (lit) or 0.0 (shadowed). The result is a binary, hard-edged shadow — crisp, a little jaggy at the silhouettes (those are the shadow map's texels showing through), but unmistakably grounding. The objects finally sit down.

// (b) COMPARISON SAMPLER + SAMPLING THE SHADOW MAP in the main fragment shader.
// fragment world pos → light clip → [0,1] uv + a depth to compare.
@group(0) @binding(3) var shadowMap: texture_depth_2d;
@group(0) @binding(4) var shadowSamp: sampler_comparison;   // ← the special one

fn shadowFactor(worldPos: vec3f) -> f32 {
  let lc = u.lightViewProj * vec4f(worldPos, 1.0);   // fragment in LIGHT clip space
  let ndc = lc.xyz / lc.w;                          // perspective divide (ortho: w=1)
  // clip XY [-1,1] → uv [0,1], FLIP Y. Z is already [0,1] in WebGPU — no remap.
  let uv = vec2f(ndc.x * 0.5 + 0.5, ndc.y * -0.5 + 0.5);
  // outside the light frustum? treat as fully lit (don't shadow the world).
  if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || ndc.z > 1.0) {
    return 1.0;
  }
  let zref = ndc.z - u.bias;                        // our depth, minus a bias (NB: 'ref' is a WGSL reserved word)
  // hardware depth compare: returns 1.0 if zref <= stored (lit), else 0.0.
  return textureSampleCompareLevel(shadowMap, shadowSamp, uv, zref);
}

The JavaScript side declares that sampler with compare: 'less' — that's what turns an ordinary sampler into a comparison sampler:

const shadowSamp = device.createSampler({
  compare: 'less',                 // ← makes it a sampler_comparison
  magFilter: 'linear', minFilter: 'linear',  // linear ⇒ the GPU PCFs 2×2 for free
});

Stage 4 — Comparison sampler + PCF (soft edges)

Hard shadows reveal the shadow map's resolution: the edge is a staircase of texels. The fix is PCF — Percentage-Closer Filtering. Instead of one depth comparison, take several taps in a little grid around the UV, do the compare at each, and average the results. A fragment right at the edge might be in shadow for 5 of 9 taps → 0.55 lit → a soft gradient instead of a hard cliff. The edge stops being binary and starts looking like a real penumbra.

There's a beautiful WebGPU detail here: because we used a comparison sampler with linear filtering, every single tap is already a hardware-bilinear 2×2 PCF. Stacking a 3×3 grid of those gives a very smooth result for nine cheap instructions. The PCF toggle flips between a single tap (hard) and the 3×3 kernel (soft) so you can A/B the difference live.

// (c) PCF — average several offset taps for soft edges.
fn shadowPCF(worldPos: vec3f) -> f32 {
  let lc = u.lightViewProj * vec4f(worldPos, 1.0);
  let ndc = lc.xyz / lc.w;
  let uv = vec2f(ndc.x * 0.5 + 0.5, ndc.y * -0.5 + 0.5);
  if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || ndc.z > 1.0) {
    return 1.0;
  }
  let zref = ndc.z - u.bias;
  let texel = 1.0 / f32(u.shadowSize);     // one shadow-map texel in uv units
  var sum = 0.0;
  // 3×3 grid; each tap is ALSO a hardware 2×2 bilinear PCF (linear filter).
  for (var dy = -1; dy <= 1; dy = dy + 1) {
    for (var dx = -1; dx <= 1; dx = dx + 1) {
      let off = vec2f(f32(dx), f32(dy)) * texel;
      sum = sum + textureSampleCompareLevel(shadowMap, shadowSamp, uv + off, zref);
    }
  }
  return sum / 9.0;                       // 0 = fully shadowed, 1 = fully lit
}

Stage 5 — Depth bias (fixing shadow acne)

Turn the bias slider down to zero and the lit surfaces erupt in a moiré of dark stripes — shadow acne. It happens because the shadow map is a finite grid: one stored depth value covers a whole texel-sized patch of the surface, but the real surface slopes across that patch. Half the patch ends up testing as "slightly behind its own stored depth" and shadows itself. The surface is fighting its own shadow map at the sub-texel level.

The classic fix is a depth bias: subtract a small epsilon from the fragment's comparison depth (or, equivalently, push the stored depth slightly farther) so a surface never shadows itself. That's the - u.bias you've already seen in the shaders. Nudge the slider up and the acne vanishes.

// (d) THE DEPTH BIAS — subtract a small epsilon from the compare depth.
// Too little ⇒ acne; too much ⇒ peter-panning (shadow detaches from the caster).
let zref = ndc.z - u.bias;    // u.bias ≈ 0.001–0.003 for this scene

// Better still: scale bias by surface slope so steep faces get more.
//   let cosT  = max(dot(N, L), 0.0);
//   let slope = clamp(tan(acos(cosT)), 0.0, 2.0);
//   let zref  = ndc.z - (u.bias + u.bias * slope);
// WebGPU also offers hardware bias on the SHADOW pipeline's depthStencil:
//   depthStencil: { ..., depthBias: 2, depthBiasSlopeScale: 2.0 }

But keep cranking past the sweet spot and you get the opposite disease: peter-panning. Over-bias pushes the shadow so far that it detaches from the bottom of each object — the cube appears to hover a centimeter above its own shadow, like Peter Pan whose shadow came loose. Stage 5 lets you ride the slider straight from one failure (acne, bias too low) through the good zone into the other failure (peter-panning, bias too high). Seeing both failure modes is the whole point — the right bias is the narrow valley between them.

Stage 6 — A moving light casting real-time soft shadows

Everything together, animated. The light orbits on its own (the angle slider still works, but it also drifts), the shadow pass re-renders every frame from the new light matrix, and PCF + a tuned bias give clean soft contact shadows that sweep across the floor as the sun moves. This is the payoff promised at the top: real-time shadows you watch travel. It's also, structurally, exactly what a shipped game does for its sun — one shadow pass, one comparison sampler, a PCF kernel, a bias. You built it from nothing.

The whole pipeline, in order

Per frame, the renderer does two passes into one command encoder:

  1. Shadow pass: compute the light's view-projection (an ortho frustum aimed down the light direction, fit to the scene's bounds), then render every mesh's depth into shadowTex with no color target.
  2. Camera pass: render every mesh normally to the swap-chain texture (with its own depth buffer), and in the fragment shader call shadowPCF(worldPos) to dim the diffuse term wherever the fragment is occluded from the light.

The two passes share the same vertex buffers and the same lightViewProj uniform — that shared matrix is the entire trick. One matrix, used to write depth in pass one and to read depth in pass two, is what links "what the light sees" to "what's in shadow."

Common pitfalls

  • Shadow acne (self-shadowing stripes). The number-one shadow bug. A finite shadow map can't perfectly represent a sloped surface, so it shadows itself in a moiré pattern. Fix with a depth bias, a slope-scaled bias, and/or a normal offset (push the sample point a hair along the surface normal). Rendering back faces into the shadow map (cullMode: 'front') also helps by hiding the error on faces the camera can't see.
  • Peter-panning (detached shadows). The cure for acne, overdone. Too much bias slides the shadow off the bottom of the caster so objects look like they're floating again. Use the smallest bias that kills the acne, not the largest. The good range is narrow — that's why we gave you a slider.
  • Light frustum not fit to the scene. A directional light wants an orthographic projection, and its near/far/extent must tightly bound the scene. Too loose and you waste shadow-map resolution on empty space (blocky shadows); too tight and objects fall outside the map and stop casting. Compute the bounds from your geometry, don't hard-code a guess.
  • Forgetting the comparison sampler. Shadow maps use a special sampler type: sampler_comparison in WGSL, created with compare: 'less' in JS, and read with textureSampleCompare / textureSampleCompareLevel. A regular sampler + textureSample on a texture_depth_2d won't do the hardware depth test (and many filter combos are invalid on depth textures). The comparison path is also what gives you free 2×2 PCF per tap.
  • The [0,1] vs [-1,1] clip-Z trap. WebGPU clip space is z ∈ [0,1]. When you remap light-clip coordinates to a shadow-map UV, scale and bias X and Y (and flip Y for texture space), but leave Z alone — it's already the depth you compare. GL tutorials remap Z too; copy that here and your shadows break.
  • Sampling depth with a linear-but-non-comparison filter. On some backends you cannot bilinear-filter a depth texture through a normal sampler at all — it must be a comparison sampler (which filters the comparison results, not the raw depths) or a nearest non-comparison sampler. If pipeline creation complains about filterable types, this is usually why.

Exercises

  1. A spot light (perspective shadow). Swap the light's ortho projection for a persp one and place the light at a finite point looking at the scene. Now the shadow map encodes a cone, and distant objects cast smaller shadow footprints. You'll need the perspective divide you already have (ndc = lc.xyz / lc.w) — it was a no-op for ortho (w=1) but does real work now. Bonus: add a circular falloff so it reads as a spotlight cone.
  2. Cascaded shadow maps (note + sketch). One shadow map can't cover a huge outdoor scene at high resolution. The standard fix is cascades: split the camera frustum into a few depth slices (near, mid, far) and render a separate, tighter shadow map for each, choosing the right cascade per fragment by its view depth. You don't have to implement it — but write the per-fragment selection logic (which cascade does this depth fall into?) and reason about where the seams appear.
  3. Colored shadows. Real shadows aren't pure black — they're lit by the sky/ambient, which has a color. Instead of multiplying diffuse by the shadow factor and going to zero, mix() between a tinted ambient color (cool blue, say) and the fully-lit color using the shadow factor. Push it further: store a colored "transparency" in a second light-pass target so a stained-glass quad casts a colored shadow.

What's next

Episode 12 — Textures, Mipmaps & Reflections. We finally put images on our surfaces: uploading texture data, sampling it in WGSL, and the thing WebGPU makes you do by hand — generating mipmaps (there's no generateMipmap; you downsample with a compute or render pass). Then we use a cube map for cheap reflections, so our shapes don't just cast shadows — they mirror the world around them.