Drawing

Shadow mapping

A point is in shadow when something stands between it and the light. Shadow mapping answers that question with two passes: first draw the scene's depth as the light sees it, then, for each pixel the camera sees, compare its depth from the light with that stored depth. This page explains the idea, the math, the artifacts and their fixes. The last part shows how RASM does it.

In short

  • Pass 1 draws the scene from the light into a depth-only texture, the shadow map. Each texel keeps the depth of the surface nearest the light.
  • Pass 2 draws from the camera. For each pixel, it moves the surface point into the light's view and compares: farther than the stored depth means something is in front of it, so it is in shadow.
  • A directional light (the sun) uses an orthographic light camera; a spot light a perspective one; a point light six of them (a cube).
  • The map has a finite number of texels, so a surface can shadow itself: shadow acne. A small depth bias and a normal offset fix it.
  • One comparison per pixel gives hard, jagged edges. PCF averages several comparisons for a soft edge.

1The question: can the light see this point?

Lighting math uses the direction to the light and the surface normal. That lights every point that faces the light, even one behind a wall. A shadow is a different question: is the path from the point to the light free?

light in shadow
Lighting only: P is lit (wrong) P wall the ray goes through the wall With a visibility test: P is in shadow P wall shadow
Ray tracing answers this with one ray per pixel and light. Rasterization has no rays, but it has a fast answer to "what is the nearest surface along each line of sight": the depth buffer. Shadow mapping uses a depth buffer drawn from the light.

2The idea: depth from the light

Draw the scene from the light and keep only depth. Each texel of that image, the shadow map, now holds the distance to the first surface the light hits in that direction. A point farther away than that number has something in front of it.

the shadow map light rays lit in shadow
shadow map: one depth per texel 214 214 214 214 84 84 214 214 box ground A B C 0 84 214 depth A: depth 214 map: 214 → equal → lit B: depth 214 map: 84 → farther → shadow C: depth 214 map: 214 → equal → lit
Points are compared, not rays traced. One texture read per pixel answers "is anything nearer the light than me?".

So shadow mapping is two passes over the same scene:

1 Shadow pass near far scene from the light camera depth only: no material, no lighting writes shadow map a depth texture sampled 2 Main pass scene from the camera, shaded each fragment: in shadow or not? Between the passes the texture changes role: depth attachment → sampled texture.
The shadow pass is cheap per pixel, often with no fragment shader at all. Its cost is the geometry, drawn a second time. On Vulkan and D3D12 the change of role is a barrier and a layout change (GPU synchronization).

3The light's camera

The shadow pass needs a view and a projection, like any camera. The kind of light decides them.

orthographic box

Directional (sun)

Parallel rays from far away. An orthographic camera looking along the light. Its box must hold every object that can cast a shadow into the view.

1 map, or several cascades (section 7)

near far

Spot

Rays from one point, inside a cone. A perspective camera at the light, with a field of view equal to the cone's angle.

1 map

90° each

Point

Rays from one point, in all directions. Six perspective cameras of 90° each, one per face of a cube around the light.

6 maps (a cube map)

For the orthographic camera, the size of the box is a design choice. The map has a fixed number of texels, and the box stretches them over the ground:

1 texel

Too large

Each texel covers a lot of ground. Shadows are blocky and blurry.

outside: no shadow

Too small

Sharp shadows, but an object outside the box is not in the map, so it casts none.

Fitted

Just large enough for every caster and every receiver that the view can see.

The near plane counts too

The light camera's near plane must sit behind every caster. A caster between the light and the near plane is clipped away, and its shadow vanishes.

4The test, step by step

The light camera's projection times its view is one matrix, S. In pass 2, a fragment at world position p takes this path:

  1. pworld position of the fragment
  2. S · pinto the light's clip space
  3. ÷ wto NDC (w = 1 for orthographic)
  4. uv, dwhere to read the map; depth as the light sees it
  5. storedread the map at uv
  6. compared against stored
c      = S · (p, 1)            light clip space
ndc    = c.xyz / c.w           divide (w = 1 for orthographic)
uv     = (ndc.x · 0.5 + 0.5,   texture coordinates,
          0.5 − ndc.y · 0.5)   v = 0 at the top
d      = ndc.z                 the fragment's depth as the light sees it
stored = shadowMap(uv)         the nearest depth along that texel's ray

lit    = d is not behind stored
         standard depth: d ≤ stored      reversed-Z: d ≥ stored
depth along the light's ray stored d = stored: the fragment is the first surface → lit stored d d is behind stored: another surface is in front → in shadow
The whole test is one comparison of two numbers on the same ray.
DetailWhat to know
The uv lineIt assumes a Y-up clip space and textures with row 0 at the top. Other conventions flip v differently; the shadow pass and the lookup just have to agree.
Reversed-ZWith near = 1 and far = 0 (Projection and reversed-Z depth), a nearer surface has the larger depth, so the comparison flips.
Outside the mapA point with uv outside 0..1, or d outside the depth range, has no information. It is usually treated as lit.

5Shadow acne, and the fixes

The map stores one depth per texel: the depth at the texel's center. A surface tilted toward the light changes depth inside one texel. Half of the surface under each texel is then "behind" the stored value and shadows itself, in stripes. That is shadow acne.

the real surface stored depth, one step per texel wrongly in shadow
Without bias: acne With bias: clean light from above, depth grows downward 5 texels: each stores the depth at its center bias the comparison moved past half a step: all lit
The steeper the surface as the light sees it, the larger the depth change inside one texel, so the more bias it needs. Acne disappears once the bias is larger than half a texel's depth change.

Try it. The picture below runs the real test for every point of the ground, against a small shadow map. Start with no bias, then raise it slowly.

lit (right) in shadow (right) acne: wrongly in shadow wrongly lit; stored depth + bias (dashed)
Set the sun low (a large angle) and the map small: the steps get taller and need more bias. Then push the bias far past the needed value and watch the shadow leave the ball.

Four fixes, often combined:

same everywhere

Constant depth bias

Compare against the stored depth moved by a small fixed amount toward the fragment.

Too much: peter-panning (below)

flat: small steep: large

Slope-scaled bias

A bias that grows with the surface's slope as the light sees it. The rasterizer can add it while drawing the map.

Too much: the same, on steep surfaces only

p p + n · k

Normal offset

Look up the map from a point pushed off the surface along its normal: about one texel, more where the light grazes.

Too much: shadows shift sideways; thin objects leak light

skipped stored

Draw back faces only

The shadow pass culls front faces, so the map holds the far side of closed objects, away from the lit surface.

Fails for: open meshes and thin walls

Bias is a balance. Too little leaves acne; too much moves the shadow away from the object that casts it:

Too little: acne

Stripes on surfaces that should be lit.

Right

No stripes, and the shadow starts at the object's foot.

gap

Too much: peter-panning

The shadow detaches, and the object seems to float.

Measure offsets in texels

Both offsets are best set in texels, not in fixed world units. Then they stay right when the map's size or the light camera's box changes.

6Soft edges: percentage-closer filtering

One comparison gives 0 or 1, so each shadow-map texel becomes a hard square on screen, and the shadow's edge is a staircase. Blurring the depths does not help: the average of two depths is a depth no surface has. Percentage-closer filtering (PCF) blurs the results instead: compare against several texels around the point, and average the 0s and 1s.

One comparison

Each pixel is 0 or 1. The edge is a staircase of map texels.

PCF: average of several

A pixel near the edge gets a value between 0 and 1: the share of its neighbours that are lit.

How the average is built decides how smooth the edge is. A common kernel reads a 4x4 block and weights it so that it acts as a 3x3 filter that slides with the point:

comparison says lit (1) comparison says shadow (0) the lookup point
3x3 PCF with bilinear weights: 4x4 texels 1 − f.x 1 1 f.x 1 − f.y 1 1 f.y 0011 0011 0111 0111 p How it adds up texel = uv · size − 0.5, base = floor(texel), f = texel − base texels base − 1 … base + 2 in x and y: 16 reads weight = wx · wy, from the labels on the left and top lit = Σ weight · (1 if lit else 0) / 9 The weights add up to 3 · 3 = 9: a 3x3 box filter that slides smoothly as p moves, instead of jumping a whole texel at a time.
A plain 3x3 average of 9 texels gives soft edges, but they still step texel by texel. Weighting the outer row and column by the point's position inside its texel makes the edge move smoothly. GPUs can do the 2x2 bilinear part in hardware with a comparison sampler.

A wider kernel gives a softer edge at more reads per pixel. Real penumbrae grow with the distance between the caster and the receiver; techniques like PCSS (percentage-closer soft shadows) estimate that distance first and widen the kernel to match.

7Resolution, coverage and cascades

A shadow-map texel covers box width / map size world units. Near the camera, one texel can cover many screen pixels: blocky shadows (perspective aliasing). Far away, many texels fall into one pixel and are wasted. Cascades fix this with several maps of the same size over boxes of different sizes.

what the camera sees (from above) a shadow map's box, with its texel grid
One map near the camera: texels too big the same texel size everywhere Cascades: 3 maps 1 2 3 small texels near the camera, large ones far away
Each cascade has the same number of texels. The shader picks the cascade by the fragment's distance from the camera. Cascaded shadow maps explains where to split, how to fit each box and how to keep it still.
VariantIdeaWhen
One map, fixed boxThe box covers a known area (a level, a room, a small scene).Small, bounded scenes; the simplest.
Box fitted to the viewEvery frame, fit the box around the part of the camera's frustum that can receive shadows. Snap it to whole texels so edges do not crawl as the camera moves.Medium scenes.
Cascaded shadow maps (CSM)Split the camera's frustum by distance into 3 or 4 slices, each with its own map. The shader picks the cascade by the fragment's depth.Large outdoor scenes; the standard for a sun.
Virtual shadow mapsOne huge sparse map; only the pages that pixels need are drawn.High-end engines.

8Worked example

A sun shadow over a 28 × 28 unit area: an orthographic box from −14 to 14, near 0.1, far 60, and a 2048 × 2048 map.

0.0137world units per texel (1.4 cm if a unit is a meter)28 / 2048
0.0167depth per world unit (orthographic: linear)1 / (60 − 0.1)
0.00023one texel of depth: a good constant bias0.0137 · 0.0167
1 texelnormal offset, surface facing the light≈ 0.0137 units
2.6 texelsnormal offset at a grazing angle (n · l = 0.2)(1 + 2 · 0.8) ≈ 0.036 units
16 MiBmap memory, 32-bit depth2048 · 2048 · 4 bytes
16texture reads per pixel, 3x3 bilinear PCF4 · 4 texels

9Pitfalls

Stripes or moiré on lit surfaces
Shadow acne: no bias, or a bias smaller than half a texel's depth change.
Objects float; shadows start away from their feet
Too much bias (peter-panning).
A shadow is missing near the light
The caster is in front of the light camera's near plane, or outside its box.
Everything is in shadow, or nothing is
The comparison has the wrong direction (reversed-Z flips it), or v is flipped between the passes.
Shadow edges crawl when the camera moves
A box fitted to the view but not snapped to whole texels.
Blocky shadows close to the camera
One map stretched over too large an area: shrink the box, raise the resolution, or use cascades.
Reading the map gives garbage or validation errors
The depth texture was not moved from attachment to sampled between the passes, or was not created sampleable.

10In RASM

RASM shadows a directional light with cascaded shadow maps: up to four maps, each fitted every frame to a slice of the camera's view. Spot and point lights have shadows too (Spot and point light shadows), and a shaded view reads up to MAX_VIEW_SHADOWS (4). This section shows a directional light's. addShadowPasses adds a depth-only scene view per cascade, and addScenePasses adds the shaded view that reads them. All are ordinary render graph passes, so the graph orders them and adds every barrier. examples/06_shadows shows it, followed by a post pass, with no barrier in the example. Without a graph of your own, list the shadows in the View: View::shadows and View::shadowCount make Renderer::render(views, count) add the same passes for each view, from its own camera (Multiple views).

the application graph passes textures shader steps
application · once, when building the graph shadow = addShadowPasses(graph, scene, camera, {sun, 4 cascades, ...}) makes the cascades' depth-only targets addScenePasses(graph, scene, camera, target, &shadow, 1) the shaded view, with the SceneShadow GPU · every frame, in graph order Cascade 0 … 3: Cull, draw (shadow.slang) one view per cascade shadow_cascade_0 … shadow_cascade_3 readDepth Cull, Scene (rasm.slang) SceneData::shadowMaps: matrix, texture, split per cascade fragMain → sampleShadow → sampleShadowMap (shaders/lib/shadow.slang) view depth → first split beyond p + n · texel · (1 + 2 (1 − n·l)) + l · texel × its matrix → uv, depth 4 gathers = 16 texels, PCF lit 0..1 → shadePBR Lit when its depth ≥ the map's (reversed-Z). Off a cascade's edge: the next cascade. Past the last split: lit, faded in. Both offsets use the texel size 2 · w / (|row 0 of the matrix| · size); w is 1 in a cascade's orthographic box. The graph stores each cascade's depth after its passes and moves it to SAMPLED before the Scene passes.
Each cascade is a normal scene view, culled on the GPU with the cascade's box, with occlusion culling too when it is on. Pass names start with Cascade and the cascade's number, so the GPU timers and the graph dump tell the views apart. A cascade's view picks each caster's LOD from the shaded view's camera and size, so a surface is shadowed by the same triangles it is drawn with (LOD selection).

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Lightsdirectional, spot, pointEach light can have a shadow: a view reads up to MAX_VIEW_SHADOWS (4), each named by its ShadowDesc::light. prepareSceneView puts each shadowed light's first map in gfx::Light::shadowMap. A directional light has cascades (this page and Cascaded shadow maps); a spot light one perspective map and a point light a cube (Spot and point light shadows). The ambient term is not shadowed.
Light cameraderived from the light, often fitted to the viewDerived: no light camera exists. fitShadowCascade builds each cascade's orthographic box along the light, around a slice of the camera's view, snapped to whole texels, every frame (Cascaded shadow maps).
Shadow mapa depth textureOne depth-only render target per cascade, made by addShadowPasses: ShadowDesc::size squared, D32_SFLOAT and no colorFormats. Its depth is always SAMPLED_DEPTH_ATTACHMENT and in the bindless set (NEAREST_CLAMP), even without occlusion culling.
Shadow passdepth onlyA scene view per cascade: the same culling, and the draws with depthPipeline (shaders/passes/shadow.slang: the vertex pulling of rasm.slang, through getVertex and getWorldMatrix, so animated, skinned and morphed meshes cast the shadow of their pose this frame, and an empty fragMain); cut-out and see-through draws use depthMaskPipeline (vertMask, fragMask), which keeps the cutoff or uses hashed alpha (transparency).
Depth conventionstandard or reversed-ZReversed-Z: cleared to 0, compare GREATER_OR_EQUAL, so lit means depth ≥ stored.
Acne fixesconstant, slope-scaled, normal offsetThe lookup moves 1 to 3 texels along the normal (more where the light grazes) and 1 texel toward the light, in the map's texels at that point (offsetLookup). No rasterizer depth bias; the shadow pass culls like the main pass.
FilteringPCF, comparison samplers, PCSS3x3 PCF with bilinear weights over 4x4 texels, read as four 2x2 Gathers, in the shader; no comparison sampler.
Caster detailthe same mesh in both passesMeshes have LODs. A cascade's view takes them from the camera and size of the view that reads it (lodPixelsPerUnit, lodDepthPlane), so all views draw a mesh at the same LOD.
Coveragefixed, fitted, cascadesCascades: 1 to MAX_SHADOW_CASCADES (4), out to ShadowDesc::distance from the camera.
Synchronizationa barrier between the passesThe render graph's: the scene passes declare readDepth on every cascade, so they run after the cascade passes and the graph records the layout changes.

Where it lives in code

WhatWhere
The APIShadowDesc, SceneShadow, MAX_SHADOW_CASCADES, MAX_VIEW_SHADOWS in include/rasm/scene.h; Renderer::addShadowPasses, Renderer::addScenePasses in src/renderer/gpuScene.cpp
Splits and boxesgetShadowSplits, fitShadowCascade in src/renderer/shadowCascades.cpp; getShadowMaps in src/renderer/gpuScene.cpp
Depth-only views, the cascades' matricesRenderer::prepareSceneView, Renderer::drawSceneView in src/renderer/gpuScene.cpp; SceneView in src/renderer/gpuScene.h
GPU fieldsshadowMaps (gfx::ShadowMap: matrix, texture, split), the shadowed lights' shadowedLights (gfx::ShadowedLight: light, firstMap, mapCount), and the LOD camera's lodPixelsPerUnit, lodDepthPlane in SceneData: src/renderer/uberMaterialTypes.h and shaders/lib/core.slang
The shadow pass shadershaders/passes/shadow.slang
The lookup and PCFsampleShadow, sampleShadowMap, offsetLookup, getPcfWeights in shaders/lib/shadow.slang; called from shadePBR in shaders/lib/pbr.slang
Applying itshadePBR in shaders/lib/pbr.slang: the shadowed lights' loop, which reads a shadow only where its light reaches the surface
Depth-only targetscheckRenderTargetDesc and the depth texture's usage in src/rhi/renderContext.cpp; VulkanCommandBuffer::beginRendering (render area from the depth); canReadDepth in src/renderer/renderGraph.cpp
An exampleexamples/06_shadows/main.cpp
Keep these true
  • sampleShadow finds a light's maps only through its gfx::ShadowedLight (firstMap, mapCount); shadePBR multiplies only that light by it. A shadowed light is left out of the global and clustered loops, so it is shaded once.
  • The offsets take the texel size from the point's clip w, which is 1 in a cascade's orthographic box and the depth from the light in a perspective map, so one formula serves both.
  • The cascades' views and the shaded view must fit the cascades with the same inputs (camera, the shaded view's aspect ratio, light, SceneShadow), or the maps are read with other matrices than they were drawn with. addScenePasses only takes a shadow that addShadowPasses made for the same scene and camera in the same graph, read by one view of that camera.
  • The test direction follows reversed-Z. Changing the depth convention changes it too (Projection and reversed-Z depth).
  • The scene passes must declare readDepth on every cascade, or they get no barrier and read one while it is still an attachment.
  • Each gfx::ShadowMap::texture holds the bindless index of this frame slot's depth texture of the map: prepareSceneView looks them up every frame.

Further reading