10. Shadow Mapping

Rendering shadows in real time by seeing the scene through the light's eyes

Ray tracing gives you perfect shadows for free — just cast a ray toward the light and see if anything blocks it. But ray tracing is expensive. Rasterization-based engines need a different trick. Shadow mapping is that trick: render the scene from the light's point of view, record what it sees, then use that information to decide what's in shadow.

It's the most widely used real-time shadow technique in games and has been since id Tech 3 popularized it in the early 2000s.

The Core Idea

Shadow mapping works in two passes:

Pass 1 — Render from the light. Place a virtual camera at the light's position, pointing in the light's direction. Render the scene, but only store depth values — no color. The result is a shadow map: a depth texture that records how far the closest surface is from the light at every pixel.

Pass 2 — Render from the camera. For each fragment, transform its position into the light's clip space. Compare the fragment's depth (its distance from the light) to the value stored in the shadow map at that position. If the fragment is farther away, something closer is blocking the light — the fragment is in shadow.

Pass 1 (light's view):
  for each triangle:
    rasterize → store depth in shadow map

Pass 2 (camera's view):
  for each fragment:
    p_light = light_MVP * fragment_world_pos
    stored_depth = shadow_map[p_light.xy]
    if p_light.z > stored_depth:
      fragment is in shadow
    else:
      fragment is lit

Two-Pass Rendering

Shadow mapping reuses the depth buffer concept from rasterization. The shadow map is a depth buffer — just rendered from the light instead of the camera.

Interactive

Camera view vs. shadow map depth

Left: the scene as the camera sees it, with shadows applied. Right: the same scene from the light's perspective, showing only depth (brighter = closer to the light).

Building the Light's View Matrix

For a directional light (like the sun), use an orthographic projection. The light has no position — only a direction. Place the virtual camera somewhere along that direction, looking at the scene:

light_view = lookAt(light_dir * distance, scene_center, up)
light_proj = ortho(left, right, bottom, top, near, far)
light_MVP  = light_proj * light_view * model

For a spot light, use a perspective projection with the spot's cone angle as the field of view:

light_view = lookAt(light_pos, light_pos + light_dir, up)
light_proj = perspective(cone_angle, 1.0, near, far)

For a point light, you need shadows in all directions — one shadow map won't cover it. The standard approach is a cube shadow map: six square shadow maps, one per face of a cube. We'll cover this later.

Coordinate Transformation

After Pass 1, we have the shadow map. In Pass 2, for each camera-visible fragment, we need to look up its depth in the shadow map. That means transforming the fragment's world position into the light's texture space.

The light's MVP matrix maps world coordinates to clip space [-1, 1]. Texture coordinates are [0, 1]. So we apply a scale-and-bias:

// After multiplying by light_MVP and perspective divide:
tex_x = p_light.x * 0.5 + 0.5
tex_y = p_light.y * 0.5 + 0.5
depth = p_light.z * 0.5 + 0.5   // OpenGL; in Direct3D, z is already [0,1]

Now (tex_x, tex_y) is where to sample the shadow map, and depth is what to compare against.

Shadow Acne

The most notorious shadow mapping artifact. The shadow map has finite resolution — each texel covers a patch of the scene. When the surface isn't perfectly aligned with the shadow map grid, a fragment's depth can alternate between barely-in-front and barely-behind the stored value, creating a Moire-like striping pattern across lit surfaces.

The fix is a depth bias — offset the stored depth slightly toward the light so that small precision differences don't cause false self-shadowing:

// During the comparison:
if fragment_depth > shadow_map_depth + bias:
    in shadow

A constant bias works for surfaces facing the light head-on, but surfaces at grazing angles need a larger bias. The slope-scaled bias handles this:

bias = constant_bias + slope_scale * max(abs(dz/dx), abs(dz/dy))

Most APIs expose this directly (glPolygonOffset in OpenGL, DepthBias / SlopeScaledDepthBias in Direct3D).

Interactive

Shadow acne & bias

No bias — notice the stripy shadow acne on lit surfaces.

The Bias Dilemma

  • Too little bias → shadow acne (false self-shadowing)
  • Too much bias → Peter Panning — shadows detach from objects and float, because the surface is biased so far forward that it no longer occludes itself

Finding the right balance is an art. A slope-scaled bias of 1.0–2.0 combined with a small constant offset is a good starting point.

Aliased Edges

Shadow map resolution is finite. When the camera is close to a shadow boundary, the shadow edge appears as a staircase of blocky texels. This is shadow aliasing, and it's the second-biggest problem in shadow mapping.

Percentage-Closer Filtering (PCF)

Instead of a single binary lookup (lit or shadowed), sample the shadow map multiple times in a small neighborhood and average the results:

shadow = 0
for each sample in kernel:
    offset = sample.xy * texel_size
    stored = shadow_map(tex_xy + offset)
    shadow += (fragment_depth > stored + bias) ? 1.0 : 0.0
shadow /= num_samples

This produces a soft penumbra — the shadow gradually fades from fully shadowed to fully lit over several pixels. A 3x3 or 5x5 kernel is common. Larger kernels are softer but more expensive.

PCF Is Not a Blur

PCF does not blur the shadow map. It performs multiple depth comparisons and averages the binary results. Blurring the depth values first would produce incorrect shadows. The comparison must happen before the averaging.

Interactive

Hard shadows vs. PCF

The same scene with a low-resolution shadow map. PCF averages multiple depth comparisons to soften the staircase edges.

Variance Shadow Maps (VSM)

An alternative that plays nicely with hardware texture filtering. Instead of storing just depth, store both the depth and depth-squared. These two moments let you estimate the probability that a fragment is in shadow using Chebyshev's inequality:

E(z)  = mean depth      (first moment)
E(z²) = mean depth²     (second moment)
variance = E(z²) - E(z)²

// Chebyshev upper bound on the probability of being in shadow:
p_max = variance / (variance + (fragment_depth - E(z))²)
shadow = 1.0 - p_max

The advantage: since we're storing moments, we can blur the shadow map with a Gaussian filter (or use mipmaps) and the math still works. This gives very smooth, variable-width soft shadows. The downside is light bleeding — thin occluders can produce artifacts where light leaks through.

Cascaded Shadow Maps (CSM)

One shadow map can't cover an entire outdoor scene with good quality everywhere. Nearby shadows need high resolution, but distant shadows can be coarser. Cascaded shadow maps solve this by splitting the camera's view frustum into slices (cascades) and rendering a separate shadow map for each.

Cascade 0:  near plane → 10m     (high detail, covers a small area)
Cascade 1:  10m → 40m            (medium detail)
Cascade 2:  40m → 150m           (coarser)
Cascade 3:  150m → far plane     (coarsest, covers the most area)

Each cascade has its own light projection matrix, tightly fit to its slice of the frustum. During the camera pass, the shader picks the tightest cascade that contains the fragment.

This is the standard technique for sun shadows in open-world games. Typically 3–4 cascades, each using 1024x1024 or 2048x2048 shadow maps.

Cascade Blending

Hard transitions between cascades are visible as sudden changes in shadow resolution. Blend between adjacent cascades in a narrow overlap band to hide the seam:

if fragment is in overlap zone between cascade i and i+1:
    shadow = mix(shadow_i, shadow_{i+1}, blend_factor)

Omnidirectional Shadows (Point Lights)

A point light casts shadows in every direction. One planar shadow map can't cover a full sphere of directions. The solution is a cube shadow map — six square depth maps, one for each face of a cube (±X, ±Y, ±Z).

Render the scene six times from the light's position, each with a 90° FOV perspective projection aimed at one cube face. During the camera pass, compute the direction from the light to the fragment and use it to sample the appropriate cube face:

light_to_frag = fragment_world_pos - light_pos
stored_depth = texture(shadow_cubemap, light_to_frag)
frag_depth = length(light_to_frag)

if frag_depth > stored_depth + bias:
    in shadow

Six render passes per light is expensive. For scenes with many point lights, only the most important lights get shadow maps — the rest are unshadowed.

Normal Offset Bias

An improvement over simple depth bias. Instead of pushing the depth value, offset the fragment's world position along its surface normal before projecting into light space:

sample_pos = fragment_pos + normal * offset_scale
p_light = light_MVP * sample_pos

This pushes the lookup point away from the surface in the direction it faces, which naturally scales with the surface angle. Combined with a small depth bias, normal offset bias virtually eliminates both shadow acne and Peter Panning.

Resolution and Memory

Shadow map resolution directly impacts quality. Common sizes:

Size Texels Use Case
512x512 262K Small indoor lights
1024x1024 1M General purpose
2048x2048 4M High-quality directional
4096x4096 16M Film / cinematic

Each texel is typically 16 or 32 bits of depth. A 2048x2048 map at 32 bits is 16 MB. With CSM (4 cascades) plus several point lights with cube maps, shadow memory adds up fast.

Putting It All Together

A modern shadow mapping pipeline:

1. For the sun (directional light):
   - Split frustum into 4 cascades
   - For each cascade:
     - Fit orthographic projection
     - Render scene depth to shadow map

2. For each shadow-casting point/spot light:
   - Render depth to shadow map (cube or 2D)

3. Camera pass:
   - For each fragment:
     - Select cascade / shadow map
     - Transform to light space
     - Sample shadow map with PCF
     - Apply normal offset + depth bias
     - Multiply lighting by shadow factor

What's Next

Shadow mapping gives us crisp, directional shadows. But real-time rendering also needs post-processing effects to sell the illusion of a camera capturing a scene. One of the most recognizable is bloom — the bright glow that makes light sources bleed into surrounding pixels.