A sun shadow in Taos Explorer has to work for a person standing on a sidewalk, where a parking meter's shadow is a few centimeters wide, and for a pilot at 3,000 m, whose shadows are whole ridgelines kilometers long. The world arrives as streamed photogrammetry tiles that exist only where the camera looks, the camera's far plane is hundreds of kilometers away, and the sun crosses the sky in real time. One shadow map cannot cover that range. Explorer combines four shadow terms, each built for a different scale, and multiplies them together.
The main term is a shadow clipmap: up to eight concentric, camera-centered, texel-snapped orthographic levels, each twice the width of the one inside it. Explorer resizes the whole set every frame from the camera's altitude and the distance to the nearest drawn geometry. It is filtered with contact-hardening PCSS. Below the clipmap's finest texels, a short screen-space march toward the sun adds contact detail. Beyond the clipmap's outer edge, where the streamed tiles are too coarse and are not drawn behind the camera anyway, a heightfield march over an elevation model shades valleys behind mountains. That result is merged into the same top-down lookup that carries the volumetric clouds' shadow onto the ground. This page covers each term: its data, its shader, its constants and the constraints that set them.
Four shadow terms, one multiply
src/shaders/deferred_lighting.wgsl · src/shaders/modules/directional_shadow.wgsl · src/shaders/modules/contact_shadow.wgsl · src/shaders/modules/cloud_shadow.wgsl · explorer/main.ts
All of Explorer's sun shadowing happens in the deferred lighting pass (see Lighting for the rest of that shader), and it comes down to a few lines. Each term is a visibility in [0, 1], and each one only darkens the result:
// Cloud transmittance over this point (1 = clear). Also scales the direct
// term below; here it widens the shadow penumbra as the sky clouds over.
let cloud_t = cloud_shadow_lookup(world_pos, cloud_shadow_lut, cloud_shadow_samp, cloud_shadow_params);
let shadow_soft = 1.0 + OVERCAST_PENUMBRA_SCALE * (1.0 - cloud_t);
var shad = shadow_factor(world_pos, N, NdotL, view_depth, in.clip_pos.xy, shadow_soft);
…
if (shad > 0.001 && NdotL > 0.0 && !under_glass) {
shad = shad * contact_shadow_march(
depthTex, camera.viewProj, camera.invViewProj, camera.position,
world_pos, normalize(-light.direction), light.contactShadow, shadow_noise_px(in.clip_pos.xy));
}
…
lit_direct = lit_direct * sun_cookie(world_pos)
* cloud_t
* sun_tint
* sun_water_caustics(world_pos);
shad scales the direct sun lobes when they are computed; cloud_t scales them
again at the end. Explorer's terrain shadow is merged into cloud_t before the lighting pass runs,
so the lighting shader doesn't know it exists. Sky ambient (the IBL) is not touched by any of these terms:
the sky is still there when a cloud covers the sun, and so is the light it gives. Ambient occlusion handles
sky occlusion separately.
Each term has a range where it works and a mechanism for handing over to the next:
| Term | Scale it resolves | Occluder source | Hand-off |
|---|---|---|---|
| Contact march | centimeters to 3 m | G-buffer depth (on screen only) | multiplies the clipmap term; only darkens |
| Shadow clipmap | 6 cm texels up to the coarsest level's reach | drawn tiles, aircraft, vehicles, the walker, trees, grass | outermost level dissolves to lit over its last 10% |
| Terrain shadow | km-scale ridges, out to ~30 km | an elevation model, including terrain behind the camera | fades in from 60% of the clipmap's reach |
| Cloud shadow | cloud-sized, across a 60 km square | the HQ clouds' Beer Shadow Map | its lookup fades to clear over the square's outer 10% |
The shadow clipmap
src/engine/components/directional_light.ts · src/renderer/features/shadow_feature.ts · src/shaders/modules/directional_shadow.wgsl · explorer/main.ts
Classic cascaded shadow maps divide the view frustum into depth slices and fit an orthographic box to each one. In a flight app that makes every cascade depend on where the camera points. Pitch from looking at the ground to looking at the horizon and the visible depth grows by orders of magnitude, the cascades stretch to match, and the shadow texel size, the depth bias and the penumbra all change with it. On screen, the shadows grow and shrink as the view tilts.
A clipmap ignores the frustum. DirectionalLight.computeClipmapMatrices builds
clipmapLevels square orthographic boxes in light space, all centered on the camera's
position, with level i covering
- E₀full width of level 0 (
clipmapLevel0Extent); Explorer starts it at 128 m and resizes it per frame - N
DIRECTIONAL_SHADOW_MAP_SIZE: 2048 on desktop, 1024 on phones and tablets - tᵢworld size of one shadow texel in level i
Turning the camera doesn't change any level: same size, same texel density, bit-identical matrices.
Resolution falls off with distance because the far ground is covered only by the outer, coarser levels.
The engine's ShadowFeature returns the levels as the same CascadeData[] the cascade
path uses (matrix, splitFar, depthRange, texelWorldSize), so the
shadow render and sampling code is shared by both modes.
SHADOW_STAGGER_INTERVALS), covered below.Choosing a level per pixel
In the shader a receiver uses the finest level whose box contains it. Because the boxes are
concentric and double in size, the level can be computed directly instead of found by testing each level
in turn. Project the receiver into level 0, take its max-norm distance from the center in units of level-0
half-extents, and the containing level is roughly ceil(log2(m)):
var sc = cascade_coords(0u, world_pos);
var lvl = 0u;
if (!in_cascade(sc)) {
let m = max(max(abs(sc.x * 2.0 - 1.0), abs(sc.y * 2.0 - 1.0)), abs(sc.z * 2.0 - 1.0));
let guess = min(u32(max(ceil(log2(m * 0.95)), 1.0)), count - 1u);
lvl = count - 1u;
for (var i = guess; i < count; i++) {
sc = cascade_coords(i, world_pos);
if (in_cascade(sc)) { lvl = i; break; }
}
}
sel.level = lvl;
let edge = max(abs(sc.x * 2.0 - 1.0), abs(sc.y * 2.0 - 1.0));
if (lvl + 1u < count) {
sel.next = lvl + 1u;
sel.blend = smoothstep(0.85, 1.0, edge);
} else {
sel.next = lvl;
sel.blend = 0.0;
sel.fade = smoothstep(0.9, 1.0, edge); // dissolve, don't cut
}
The 0.95 matters because the boxes are not exactly concentric. Each is snapped to its own texel grid, and a level held back by staggered updates (below) is centered on where the camera was a few frames ago. The shader comment works out the tolerance: scaling by 0.95 keeps the starting guess at or below the true level for any such offset up to about 4%, and the loop then checks containment with the level's real matrix. For a distant receiver this takes one or two projections instead of one per level.
Across the outer 15% of each box, the receiver blends toward the next coarser level, so the change in resolution has no visible edge. The coarsest level has nothing coarser to blend into, and a receiver past its edge would otherwise switch to fully lit along a hard rectangle on the ground. Over that box's last 10%, the shadow dissolves to lit instead. Past that point the terrain and cloud lookup takes over (see Terrain shadows).
One more fallback runs in directional_shadow(): after the normal offset is applied, the
receiver can land just outside the level it was assigned. The function then steps outward to the first
coarser level that contains it, and returns fully lit only if no level does.
Holding still: snapping, latching, pancaking
src/engine/components/directional_light.ts · src/renderer/render_graph/passes/shadow_pass.ts · explorer/main.ts
Texel snapping
A shadow map that moves with the camera by fractions of a texel rasterizes each edge into slightly
different texels every frame, and the edges shimmer. So each level stays on a
world-fixed texel grid: the box may move only in whole-texel steps. The light's lateral axes
(right, up) depend only on the light direction, so the camera position projected
onto them can be rounded to a texel multiple:
const extent = this.clipmapLevel0Extent * Math.pow(2, i);
// radius is half the box width; an exact mapSize/2 texels so the texel snap
// moves the box only in whole-texel steps (radius = mapSize/2 · texelSize).
const texelWorldSize = extent / mapSize;
const radius = extent * 0.5;
let left: number;
let bottom: number;
if (lightStatic) {
const offX = right.dot(camPos);
const offY = up.dot(camPos);
left = Math.round((offX - radius) / texelWorldSize) * texelWorldSize - offX;
bottom = Math.round((offY - radius) / texelWorldSize) * texelWorldSize - offY;
} else {
left = -radius;
bottom = -radius;
}
The lightStatic condition is needed because the snapping grid is anchored to the light's
axes: when the light rotates, the rounding would flip back and forth and the whole map would jump
by whole texels every frame, worst with a crisp edge at coarse planet-scale texels. The engine therefore
snaps only when the light direction is exactly unchanged from the previous frame. The test is
exact equality rather than a velocity threshold, so there is no point where it switches back and forth: a
moving light never snaps, and a still light always does.
The light-direction latch, and why Explorer turns it off
The engine also has a latch: shadowDirectionStep (0.5° by default) re-aims the
shadow only when the sun has moved that far, scaled by sin²(elevation) so the step on the ground stays
roughly constant as the sun gets low. This keeps the matrices bit-identical for long stretches, so a slowly
rotating sun doesn't re-rasterize the map every frame and make the soft penumbra boil. Explorer sets
sun.shadowDirectionStep = 0. Its sun is animated and can be scrubbed, and with the latch
each re-aim would show up as the shadows' shape and length visibly jumping. With the latch off, shadows sweep
smoothly with the sun, and a paused sun still produces identical matrices.
Snapping, the stagger reuse test
(sameLevelShape, which compares the rotation and scale parts of the level matrices) both
depend on the light direction being bit-identical between frames. Explorer runs a
real-time clock (timeScale: 1) and calls applySun every frame, so whenever the
sun direction actually changes between frames, the levels ride the camera unsnapped and are all
re-rendered. Snapping and staggering only take effect while the light is exactly still.
Pancaking: casters in front of the box
Each level's depth slab extends only half the level's width toward the light. A tall or distant occluder
standing between the light and a receiver inside the box, such as a mountain 5 km sunward of a 4 km
level, would be cut off at the near plane, and the part of its shadow from the clipped portion would
disappear: a band of missing shadow that comes and goes as the camera moves. Explorer avoids it with
unclippedDepth (the depth-clip-control feature): those fragments are clamped to
depth 0 instead of discarded. That is the correct answer, since anything in front of the near plane is
nearer the light than every receiver in the box. The caster cull matches it: each level culls against only
five planes of its box and skips the near plane, so it never drops a caster that clamping would still have
drawn.
Sizing the clipmap by altitude
explorer/main.ts (frame loop, "Clipmap scale") · src/renderer/features/shadow_feature.ts · setClipmap
The levels are cubes centered on the camera. A level whose corner doesn't reach the nearest drawn geometry contains nothing. With a fixed 128 m level 0, from 700 m up four of the six levels would shadow nothing and the coarsest would stop 2 km out, and each of those empty levels would still cost a render pass and a full set of texels.
Explorer therefore resizes the clipmap every frame. Level 0 starts at the smallest power-of-two half-extent whose corner could reach the nearest geometry. The nearest distance is the minimum of the previous frame's tile-bounds minimum, the altitude and, in flight, half the chase-camera distance. The corner distance of a cube is h·√3, so the fit uses h ≥ 0.55·d:
const fit = (d: number): number => {
let h = CLIPMAP_MIN_HALF_EXTENT; // 64 m
while (h < d * 0.55 && h < CLIPMAP_MAX_HALF_EXTENT * 2) {
h *= 2;
}
return h;
};
// Grow as soon as the finest level is provably empty; shrink only once the
// geometry is 30% inside the next size down.
const grow = fit(nearest);
const shrink = fit(nearest * 1.3);
if (grow > clipmapHalfExtent0) { clipmapHalfExtent0 = grow; }
else if (shrink < clipmapHalfExtent0) { clipmapHalfExtent0 = shrink; }
if (clipmapHalfExtent0 > CLIPMAP_MAX_HALF_EXTENT) { // 32768 m
shadowFeature.setClipmap(1, CLIPMAP_MIN_HALF_EXTENT * 2);
terrainShadowFade = 0;
} else {
const reach = Math.max(2048, altitude * 8);
const levels = 1 + Math.ceil(Math.log2(Math.max(1, reach / clipmapHalfExtent0)));
const maxLevels = Math.min(planeMode ? CLIPMAP_PLANE_LEVELS : CLIPMAP_MAX_LEVELS,
effects.shadowLevels + (planeMode ? 2 : 0));
const used = Math.max(CLIPMAP_MIN_LEVELS, Math.min(maxLevels, levels));
shadowFeature.setClipmap(used, clipmapHalfExtent0 * 2);
terrainShadowFade = clipmapHalfExtent0 * 2 ** (used - 1);
}
The levels freed at the inner end are spent on reach: about eight altitudes, which is
roughly the ground a pitched-down camera sees, and never less than 2 km. The level count is clamped to
3 at minimum and to the quality preset's shadowLevels at maximum (4 on Low, 5 on Medium, 6 on
High and Ultra). In flight the budget gets two extra levels, up to the engine's limit of 8, because the
finest levels stay on the aircraft beside the camera and the ground below still needs its reach. Shrinking
uses 30% hysteresis, so a camera hovering at a threshold doesn't re-rasterize every level back and forth;
setClipmap's documentation notes that every change of E₀ re-renders all levels at a new
texel size. When the camera is more than about 60 km from anything (h would exceed 32,768 m), the
clipmap drops to a single empty 128 m level, which is cheaper than six empty ones.
Working through the code at a few heights (nearest geometry = altitude, the High preset, not flying, 2048² levels):
| Camera | Level-0 half-extent | Level-0 texel | Levels | Coarsest half-extent (= terrain fade distance) |
|---|---|---|---|---|
| on foot, 2 m | 64 m | 6.25 cm | 6 | 2,048 m |
| 700 m up | 512 m | 50 cm | 5 | 8,192 m |
| 3,000 m up | 2,048 m | 2 m | 5 | 32,768 m |
| 20 km up | 16,384 m | 16 m | 5 | 262,144 m |
| > ~60 km | one empty 128 m level; terrain shadow off | |||
fit, hysteresis, reach and budget logic as the frame loop, with the
nearest geometry assumed to be the ground directly below. Raise the altitude and lower it again: the level-0
size goes up as soon as it can and comes back down only 30% later. The dashed circle is the reach (8
altitudes, at least 2 km); the shaded ring is where the terrain shadow fades in.Rendering the levels
src/renderer/render_graph/passes/shadow_pass.ts · src/renderer/shadow_constants.ts · src/renderer/shadow_stagger.ts · explorer/lib/ground/ground_trees.ts · ground_trees.wgsl · ground_grass.ts
What casts
ShadowFeature gets its casters from four callbacks that Explorer fills each frame:
- drawItems
liveShadowCasters: every streamed tile mesh drawn this frame, plus aircraft, cars, boats, parked vehicles, street props and wrecks, each added through a pooledacquireShadow()beside its G-buffer draw. Several have distance cut-offs (STREET_SHADOW_REACH,PARKED_SHADOW_REACH, 600 m for others). The pools only grow, so a steady draw count allocates nothing per frame. - skinnedCastersthe walker (the fox, and others), drawn with GPU skinning so its current pose casts, not the bind pose.
- customCasterstrees and grass, which draw themselves into each level from their own GPU-generated instance buffers through
drawIndirect. - (tiles only in view)tiles stream only inside the view frustum, so a mountain behind the camera is not drawn and cannot cast into the clipmap. The terrain shadow covers that case.
The trees are impostors (one camera-facing quad per tree, sampling a view atlas). For the shadow, the quad is turned to face the sun and samples the atlas view closest to the sun's direction. Only trees in the nearest ring within 1.3 × 900 m cast. The fragment alpha-tests the atlas and then writes a depth pushed back over a spherical profile, so the crown has volume as seen from the light, not a flat card:
fn fs_shadow(in: ShadowOut) -> @builtin(frag_depth) f32 {
if (textureSampleLevel(atlas_color, atlas_samp, in.uv, i32(in.kind + 0.5), 0.0).a < 0.3 + 0.32 * in.leafless) {
discard;
}
let back = sqrt(max(RADIUS * RADIUS - dot(in.local, in.local), 0.0)) + 0.04;
return clamp(in.clip.z + in.dz * back, 0.0, 1.0);
}
The alpha cut-off rises for leafless (winter) trees, so a bare crown casts a sparser shadow. Grass blades go
through the same blade_vertex() as the G-buffer draw, so the wind sway in the shadow matches the
blades on screen.
Per-level culling
Each level culls the caster list against its box, without the near plane as described above. It also
applies a small-caster cull: if a caster's bounding sphere projects to fewer than
minCasterShadowTexels = 2 texels in that level, its shadow there would be sub-pixel, so it is
skipped. Near levels have tiny texels and keep everything. The coarse outer levels drop the clutter, which
the code comment calls "the main lever for the far-cascade draw count in large streamed scenes."
Casters near a ground cut (a tunnel's mouth) draw with a pipeline that cuts them like the ground, and that pipeline discards. A caster takes it only when its sphere reaches one cut box's own sphere: on Apple and phone GPUs a depth pass whose shader can discard loses its hidden-surface removal, and the sphere about all the boxes covered several kilometers of a city's tiles (levels 1-3 together 1.6 → 0.8 ms on an M1 at Medium). And only in a level whose box holds a cut box: elsewhere the cut cannot remove anything, so a kilometer-wide ground tile that reaches a tunnel's mouth still draws plain in the small level about the camera.
Format: depth16unorm
The shadow layers are
SHADOW_DEPTH_FORMAT = 'depth16unorm', and every pipeline that draws into them (tiles, trees,
grass, terrain, clusters, block casters) imports the constant, because a pipeline must match its depth
attachment's format exactly. The reasoning comes from the clipmap's geometry. Each level's depth slab is as
deep as the level is wide, so
- Δzone unorm16 depth step, in meters, in any level
- tᵢthat level's texel size: the step is always 1/32 texel, much finer than the filter
Half the bytes of depth32float means half the memory and bandwidth: a 2048² layer is 8 MB
rather than 16, and an 8-level clipmap 64 MB rather than 128. On phones Explorer goes further and calls
setDirectionalShadowMapSize(1024) before the first frame. iOS Safari closes a tab that uses
too much GPU memory, without any error. The clipmap texture array keeps the highest level count it has
needed (at least two layers), so moving between 5 and 6 levels doesn't reallocate it.
Hardware bias
The caster pipelines use a modest rasterizer bias, depthBias: 2 and
depthBiasSlopeScale: 2.5 with no clamp, and cull back faces unless the material is
double-sided. Material-aware casters alpha-test against getShadowCoverage(), so a cut-out
surface casts the shape of what is visible. Most of the bias is applied at the receiver, per level (see
Filtering).
Render bundles, and the black iPhone frame
A streamed city can have about 500 caster draws per level, and recording them on the CPU every frame would
be most of the CPU frame. ShadowPass records each level's plain casters (solid, single-sided)
into a GPURenderBundle and replays it with executeBundles. The bundle is
re-recorded only when the set of casters that survived culling changes: which items, in what order, their
vertex and index buffers, or the model bind group. Matrices are not baked in; they are read from a model
buffer uploaded once per frame and shared by all levels. The outer clipmap levels change slowly, so their
bundles stay valid for many frames.
Shadow bundles use fragment-less (depth-only)
pipelines. WebKit rejects those inside render bundles at setPipeline (WebKit bug 319980),
iOS Safari 27.2 included. One invalid bundle invalidates the frame's whole render-graph command
buffer, so an iPhone would show a black canvas. Bundles only save CPU time, so
supportsShadowBundles() turns them off for every WebKit user agent that isn't Chromium (all iOS
browsers and macOS Safari), and those record the draws directly. Separately, the bundle code skips empty
meshes, because WebKit also rejects drawIndexed with a zero-size index buffer inside a bundle.
Staggered updates
With SHADOW_STAGGER_INTERVALS = [1, 1, 2, 2, 4, 4], the two finest levels re-render every frame,
the next two every other frame, and the two coarsest every fourth frame. Each level has its own phase,
(frame + i) % interval, so the refreshes land on different frames. The coarse levels are the
widest and hold the most tiles, so they account for most of the shadow draw calls. A level that isn't
re-rendered keeps its depth and the matrix it was rendered with. That matrix is published through
frame.extras('shadow:cascades'), so lighting, fog, god rays and every extra caster pass sample
the stale depth consistently, and its shadows stay fixed in the world while the camera moves.
A held level is refreshed early if its shape changes (light direction, box size, level count) or if the
camera has moved more than 2% of the level's half-extent since it was rendered. The cost is that shadows
of moving casters in a held level update at the lower rate. Passes that draw into the shared map
must skip held levels, which are published as shadow:renderLevels: those layers aren't
cleared, so moving geometry drawn into them again would accumulate. In flight, levels 7 and 8 have no
interval entry and render every frame. ?stagger=0 turns staggering off for A/B comparisons.
Filtering: PCSS and its bias
src/shaders/modules/directional_shadow.wgsl · src/shaders/deferred_lighting.wgsl · explorer/lib/studio/studio_doc.ts · explorer/assets/studio/look.json
One WGSL module, directional_shadow.wgsl, implements level selection, receiver bias and the
filters for the deferred pass and every forward+ variant. Each importing shader supplies a set of one-line
adapter functions (dsh_matrix, dsh_texel, dsh_compare, …) over its
own bindings. The same filter code therefore runs on the layered shadow map or, through a page table, on
the virtualized page pool (below).
Receiver bias, per level
Both bias terms scale with the level's texel size, so neither is a constant:
let texel_world = dsh_texel(level);
let ndl = max(NdotL, 0.15);
let slope = sqrt(max(0.0, 1.0 - ndl * ndl)) / ndl; // tan(theta)
let world_bias = texel_world * clamp(1.0 + 2.0 * slope, 1.0, 8.0);
let L = normalize(-dsh_light_dir());
let t_angle = clamp(1.0 - max(0.0, NdotL), 0.0, 1.0);
var nb = N * (texel_world * 3.0 * t_angle);
nb -= L * dot(L, nb); // no light-parallel part: that would fake depth bias
out.sc = cascade_coords(level, world_pos + nb);
out.bias = world_bias / max(dsh_depth_range(level), 1e-3) + 0.0002;
The bias is a slope term rather than a constant NDC offset. Because each level's depth range spans the whole box, NDC depth is heavily compressed, and a fixed NDC offset becomes a tiny world offset while the texel footprint is large. Surfaces sloped relative to the light would then show shadow acne as a moiré whose diagonal follows the light's lateral axes. The slope term uses the worst-case depth change across one texel, t·tanθ, converts it to NDC through the level's depth range, and caps it at 8 texels so that at grazing angles the shadow doesn't detach from its caster. The normal offset is three texels at grazing angles and zero on surfaces facing the sun.
Percentage-closer soft shadows
PCSS (Fernando 2005) estimates penumbra width from the average depth of the blockers around the receiver, so a shadow is sharp where the caster touches the ground and widens with distance from it. Explorer works out the penumbra in world units and converts it to texels of the level being sampled. That keeps the softness the same on both sides of a level boundary, so the cross-blend doesn't show a change in appearance.
let SEARCH_WORLD : f32 = 0.3; // meters — blocker search radius
let KERNEL_MAX_WORLD : f32 = 1.0 * softness; // meters — caps very soft shadows
let MIN_KERNEL : f32 = min(2.6 * softness, 16.0); // texels — floor that hides the grid
let texel_world = dsh_texel(level);
let depth_world = dsh_depth_range(level);
let search_tex = clamp(SEARCH_WORLD / texel_world, 2.0, 8.0);
var kernel = MIN_KERNEL;
let avg_blocker = pcss_blocker_search(level, ls.sc, search_tex, screen_pos);
if (avg_blocker >= 0.0) {
let occluder_dist = max((ls.sc.z - avg_blocker) * depth_world, 0.0);
let penumbra_world = min(dsh_light_size() * softness * occluder_dist, KERNEL_MAX_WORLD);
kernel = clamp(penumbra_world / texel_world, MIN_KERNEL, 16.0);
}
return pcf_shadow(level, ls.sc, ls.bias, kernel, screen_pos);
- λ
shadowSoftness, the light-size factor: 0.02 (Studio look,look.json); 2 cm of penumbra per meter between caster and receiver. For comparison, the real Sun's 0.53° disc gives about 0.93 cm per meter - sovercast softness, 1 + 4·(1 − cloud_t): up to 5× softer under full cloud
- d_occreceiver depth minus mean blocker depth, times the level's depth range (meters)
- tᵢthe level's texel size
The minimum kernel controls how the penumbra scales with texel size. In level 0 on foot (6.25 cm texels), 2.6 texels is a 16 cm blur, so a curb's shadow is nearly sharp. In a 2 m level it is a 5 m blur. That is deliberate. With a one-texel minimum, the hardest shadows follow the shadow-map grid and look chunky. A blur of a few texels stays stable and hides the staircase. The 1 m cap bounds the other end: however tall the caster, the penumbra never exceeds 1 m on a clear day (5 m under full overcast). At λ = 0.02 that cap is reached at 50 m between caster and receiver.
The blocker test is
d < sc.z, without the receiver bias. On a surface sloped toward the light, the
receiver's own light-side neighbors then count as blockers at nearly zero distance and pull the average
toward the receiver, which narrows the penumbra. That narrowing is part of the tuned look: biasing the
search widens every penumbra and makes the 16-tap noise visibly stripier. It also rules out an obvious
optimization. "No blockers found, skip the PCF" is almost never true on sloped ground, and where it is
true, 16 point samples over the search disc can't prove the bilinear PCF footprint is clear, so the shader
has no such early-out. The only skip that is exact is NdotL ≤ 0, which
shadow_factor returns before any taps.
Noise that TAA can average
Both 16-tap kernels are rotated per pixel by interleaved gradient noise, which turns banding into fine
dither. The TAA resolve reads history at the de-jittered position, so it does not blur as it resamples,
and a fixed dither would show through as visibly stripy penumbrae. So while a long-history TAA resolve is
running, Camera.temporalNoiseIndex (1 to 64) shifts the
noise seed every frame, so TAA averages successive patterns into a smooth gradient. With the temporal
upscaler or SMAA T2x the index is 0, and the pattern stays fixed in screen space so it doesn't flicker:
fn shadow_noise_px(screen_pos: vec2<f32>) -> vec2<f32> {
return screen_pos + vec2<f32>(5.588238 * dsh_noise_frame());
}
The contact-shadow march uses the same seed for its start offset. Antialiasing and the TAA resolve are covered in Motion, antialiasing and the lens.
The alternative filter: EVSM2
The engine also has an exponential variance shadow map path (shadowFilter: 'vsm'). After the
depth levels are rendered, DirectionalVsmPass converts each layer to warped moments
(E[w], E[w²]) with w = exp(c·d), blurs them with a separable Gaussian
(radius capped at 1.5, because beyond that the linear-sampling kernel skips texels), and the lighting pass
evaluates the one-tailed Chebyshev bound from a single filtered fetch, with 0.2 light-bleed reduction. The
cost is constant however soft the edge is.
Precision depends on the warp. With shadowVsmPrecision: 'auto' the moments are
rg32float with c = 40 when the device has float32-filterable
(exp(80) ≈ 5.5·10³⁴ fits fp32). Otherwise they are rg16float with c = 5.5, the
largest exponent whose second moment exp(11) ≈ 59,874 fits under fp16's 65,504, and that weak warp behaves
much like plain VSM. Under overcast, the EVSM path widens by averaging a ring of 8 extra taps whose radius
is 0.1 m per unit of softness above 1, since moments filter linearly. The path works in the engine, but Explorer pins
effects.vsm = false and its settings do not offer it, so the shipped look is PCSS. Unlike
the clipmap and page-pool switches, there is no URL override for it.
Contact shadows
src/shaders/modules/contact_shadow.wgsl · explorer/main.ts (CONTACT_SHADOWS)
Even 6 cm texels can't resolve a shadow narrower than a few texels plus the PCSS minimum kernel, and the receiver bias that prevents acne also lifts the shadow off the base of whatever casts it. Photoreal buildings, ledges, cars and street furniture need the shadow line where they meet the ground. The contact march adds it: twelve steps toward the sun, in world space, from each lit pixel, checking the G-buffer depth for a surface that crosses in front of the ray.
/** Screen-space contact shadows for the sun (DeferredLightingFeature.contactShadows): a
* short toward-sun depth march that adds the fine contact occlusion — building bases,
* ledges, street furniture — the clipmap's meter-scale texels can't resolve. Distance /
* thickness are in meters, so they're sized for photoreal city detail. */
const CONTACT_SHADOWS: ContactShadowParams = { distance: 3, thickness: 0.6, steps: 12, intensity: 0.7 };
var t = step_len * (1.0 + jitter); // start a (jittered) step out — skip self
for (var i = 0u; i < steps; i++) {
let p = world_pos + sun_dir * t;
…project p, read the depth at that pixel, reconstruct scene_world…
let diff = length(p - cam_pos) - length(scene_world - cam_pos);
if (diff > 0.02 && diff < thickness) {
let fade = clamp(1.0 - t / max_dist, 0.0, 1.0);
return 1.0 - intensity * fade;
}
t += step_len;
}
return 1.0;
The steps are 25 cm long. A hit counts only if the depth-buffer surface is between 2 cm and 60 cm closer
to the camera than the ray sample. The 60 cm upper limit is the assumed occluder thickness: without it, a
foreground object would cast onto everything behind it on screen. The darkening fades with distance along
the ray and is at most 70%. A hard binary hit combined with the per-pixel start jitter looks like a
dithered blob with hard edges, while the ramp gives TAA a gradient to resolve. The march runs only where
the clipmap term is still above 0.001 and the surface faces the sun, so its cost (a dozen depth reads,
per the effects comment) is paid only on lit pixels.
The term is on by default on High and Ultra and off on Low and Medium. It is also turned off in the
cockpit view: from the pilot's seat the propeller is a thin, fast object directly in the
march's path, and it would cast a strobing shadow across the instrument panel. It is skipped under stained glass
too, since glass writes G-buffer depth and the march would treat the pane as opaque. The engine has a
longer sibling, far_shadow_march, which takes 16 geometrically spaced steps for mountain
shadows past the cascades. Explorer leaves it off. A depth-buffer march can only see what is on screen,
and a mountain behind the camera is not, so Explorer uses the elevation model instead.
The other paths: cascades, SDSM, virtual pages
src/engine/components/directional_light.ts · src/renderer/features/sdsm_feature.ts · src/renderer/sdsm_reducer.ts · src/renderer/features/shadow_feature.ts · src/shaders/vsm_page_mark.wgsl · src/renderer/vsm_pages.ts
Explorer pins its shadow configuration in code: "the altitude-aware shadow clipmap with PCSS and
staggered updates, no SDSM, no page virtualization", whatever a saved settings blob says. The other paths
are still in the engine and are wired into Explorer's ShadowFeature, so URL flags can switch
to them for A/B captures (?clipmap=0, ?vsmpages=1). How each one works, and why
it isn't the default, explains the clipmap design.
Cascades
With mode: 'cascade' the sun uses four cascades (numCascades = 4) split with a
practical-split blend of λ = 0.9, which is nearly logarithmic:
- n, fcamera near plane and
shadowFar - λ0.9 in Explorer: cascade 0 ends a hundred-odd meters out even when the range reaches kilometers
The engine's cascades are already more stable than frustum-fit boxes. Each cascade is a sphere centered on the camera position, with a radius that reaches the farthest corner of its depth slice, enlarged by 2/N so sampling at the edge never wraps, and texel-snapped like the clipmap. Rotating the camera leaves the boxes unchanged, and casters beside or behind the camera stay inside them. The view dependence that remains is the slice depths themselves.
Explorer's shadowFar depends only on altitude. Computing it from how far the camera looks
before hitting the ground would make the cascade size swing wildly as the camera pitched, because a nearly
horizontal ray meets the ground very far away, and since the penumbra and the bias scale with texel size,
shadows would grow and shrink with tilt. Altitude doesn't change with view direction:
shadowFarAdaptive = Math.min(120000, Math.max(4000, altitude * 6 + 4000));
…
if (issRide) {
// the only shadow-casting geometry is the station, a few hundred m away
shadowFarAdaptive = Math.max(800, issViewDist() * 4);
}
SDSM, near-only
Sample-distribution shadow maps (Lauritzen et al. 2011) fit the cascades to the depth range actually
visible on screen. SdsmReducer runs a compute pass that reduces the G-buffer depth, skipping
sky, to min and max view-linear depth, stored in an 8-byte buffer as IEEE-ordered u32 atomics.
It copies the previous frame's result into a free buffer of a three-buffer readback ring and maps it
asynchronously, so the bounds are about one frame old. To cover that latency they are padded by 15% and
quantized to steps of 2k/4, four per octave, so they hold still instead of re-fitting every
frame.
Explorer's hook into it is near-only: it tightens the cascade near to the closest
visible geometry but keeps the far at the tilt-invariant shadowFarAdaptive:
// NEAR-ONLY SDSM. … The visible far swings ~hundreds-fold as the camera pitches
// (shallow looking down → out to the horizon looking forward); since the shadow
// bias and penumbra scale with the cascade's texel size, feeding it in makes
// shadows visibly stretch/shrink with tilt. The near barely moves (the nearest
// ground is always ~one altitude away), so near-only keeps most of the density
// win while holding the shadow appearance steady as the view pitches.
depthBounds: () => (effects.sdsm && sdsm.bounds
? { near: sdsm.bounds.near, far: shadowFarAdaptive }
: null),
Even near-only, the cascade size still depends on the view, so the shadows shift slightly as the camera
tilts. The effects comment calls that "visually distracting", and it is why SDSM is off. The
clipmap removes the problem: it has no near or far to fit, so the clipmap path ignores both
depthBounds and shadowFar.
Virtualized pages
With virtualize on, each 2048² level is split into 16 × 16 pages of 128² texels, and only the
pages the scene actually samples are kept, in a shared pool atlas that Explorer sizes at 8192 × 4096
(64 × 32 = 2,048 slots). Everything runs on the GPU, in the same frame, with no readback:
- Mark. One compute thread per subsampled G-buffer pixel reconstructs the
world position, finds its level and page with the same containment rule as the lighting shader, and sets
a bit with
atomicOr. It checks with a plain load first, which reduces contention from every pixel in a page to about one. A pixel within 25% of a page's edge (32 texels) also marks the neighboring page, because the filter reaches up to 16 (PCSS cap) + bias + 1 texels across. - Allocate. The marked bits become a page table, virtual page → pool slot. The coarsest level always gets all 256 of its pages, and the rest are allocated finest level first.
- Render and scatter. Each level is still rendered in full into a single reused scratch level, and its resident pages are then copied into the pool, together with a quarter-resolution proxy that fog and god rays read in place of the layered map.
- Sample. The PCSS taps go through the page table one by one, so a tap that crosses a page boundary resolves to the correct slot. Bilinear footprints are clamped half a texel inside the page, since the neighboring atlas slot holds an unrelated page. A non-resident page moves the receiver out to the next coarser resident level: lower resolution, but the shadow is never missing.
So virtualization saves memory, not render time. The ShadowFeature documentation says so, and
adds that the per-page path is heavy for large casters. In depth16unorm the
layered six-level clipmap costs 48 MB at 2048², while the pool is depth32float, 8192 × 4096 ×
4 bytes = 128 MB. Explorer's pool is twice the engine's 4096² default (1,024 slots), following the
engine's own advice to size it up for high-altitude, many-level scenes: more levels and more altitude
both grow the set of sampled pages. A pool too small for them overflows and drops pages, leaving what
the source calls "the sliding unshadowed wedge". The path supports PCSS only.
Terrain shadows past the maps
explorer/lib/ground/terrain_shadow.ts · explorer/main.ts (cloudShadow provider, frame loop)
At a low sun, valleys should be shaded by mountains far beyond the clipmap's outer level. Those
mountains might be behind the camera, where no tile is drawn. TerrainShadow handles that case
without the scene's geometry, using an elevation model instead:
- Heightmap. A 1024²
r32floatsquare covering 73,728 m around the camera (72 m per texel), in world axes (X east, Z south). It is resampled on the CPU from zoom-11 Terrarium elevation tiles (about 76 m per pixel at the equator) plus the geoid, with the heights including the Earth's curvature away from the origin. The build is time-sliced at 2.5 ms of CPU per frame, a few rows at a time, and redone once the camera is 5 km from the map's center. The 60 km lookup it merges into reaches 30 km from the camera, so 30 km + 5 km stays inside half of 73.7 km. - Bake. A full-screen pass marches every texel toward the sun through the
heightmap (
rg16floatout). It is redone at most every 0.25 s, and only after the sun has turned about 0.1° (0.002 rad). - Merge. Every frame a small pass multiplies the result into the cloud-shadow lookup the lighting pass already reads, faded in by distance from the camera.
const PENUMBRA : f32 = 0.018; // ~1°: the sun's disc, widened for the coarse heights
…
let ground = height(p);
let h0 = ground + 4.0;
var res = 1.0;
var shade = ground;
var t = texel;
for (var i = 0; i < 200; i++) {
let q = p + L.xz * (t / texel);
if (/* off the map */) { break; }
// Nothing farther on can lift the shadow, nor shade the ground, once the ray is
// above the highest terrain.
if (u.misc.y - L.y * t < shade && h0 + L.y * t > u.misc.y) { break; }
let hq = height(q);
shade = max(shade, hq - L.y * t);
let ry = h0 + L.y * t;
if (res > 0.0) {
res = min(res, 0.5 + (ry - hq) / (t * PENUMBRA));
}
t += max(texel, t * 0.03); // a texel at a time near by, 3% beyond
}
return vec4<f32>(smoothstep(0.0, 1.0, clamp(res, 0.0, 1.0)), shade, 0.0, 1.0);
The second channel is used by the volumetric clouds: the height below which the air over a point is in the terrain's shadow. The clouds use it to darken cloud bases in a mountain's shadow at dusk. The receiver starts 4 m above the heightfield so the coarse 72 m data doesn't shadow itself.
Where it fades in
Inside the clipmap's reach, the real geometry already casts, and adding the terrain term there would darken the same area twice. The merge therefore fades the terrain term in with distance:
// Past the shadow maps' reach, and from a few kilometers out in any case: the far
// clipmap levels have only the tiles in view to cast (a mountain behind the camera
// is not drawn) and are no finer than this. Never near the camera: the lookup is
// the ground's shadow, and would darken an aircraft flying in the sun above it.
lut = terrainShadow.addToGraph(graph, lut, params, res, c.x, c.z,
Math.min(terrainShadowFade * 0.6, 1500), Math.min(terrainShadowFade * 0.95, 4000));
terrainShadowFade is the coarsest level's half-extent, computed by the clipmap fit. On foot
(2,048 m) the terrain shadow fades in from 1.2 to 1.9 km. From 700 m up it is capped at 1.5 to 4 km. The
caps exist because the far clipmap levels have only the visible tiles to cast and are no sharper than
72 m elevation data. The merge itself is one line:
cloud * mix(1.0, terrain, smoothstep(start, end, distance(xz, cam.xz))). The term is limited to
Earth (the elevation model is Earth's), to altitudes below 30 km, and to outside the ISS ride, and it is off
on the Low preset. Its 8 MB of textures are allocated on first use, so a phone on Low never allocates them.
At a low sun,
blocky stair-steps on the ground can look like shadow-map texels. On the coarse, stepped photoreal mesh they
are flat per-triangle normals, and crease-angle normals smooth them away
(TILE_CREASE_DEG = 50, applied as the tileset's smoothNormals). Before tuning a
shadow filter, check whether the artifact is in the shadow at all.
Cloud shadows, and shadows at night
src/renderer/render_graph/passes/hq_cloud_pass.ts · src/shaders/clouds_hq.wgsl (fs_ground_lut) · src/renderer/render_graph/passes/cloud_shadow_lut_pass.ts · src/shaders/modules/cloud_shadow.wgsl · explorer/main.ts
The ground lookup
The engine's CloudShadowLutPass defines a shared contract: an r8unorm square of
vertical cloud transmittance, re-centered on the camera every frame, plus a small params uniform
(origin, extent, cloud top). Every consumer (the deferred sun term, the god-ray march, the froxel fog)
takes one bilinear fetch from it, so cloud shadows on the ground, in the light shafts and in the fog come
from the same data. Explorer sizes it at 60 km and 1024², about 59 m per texel.
Explorer doesn't fill it from the pass's own procedural density. HQCloudPass.addGroundShadowLutToGraph
bakes it from the HQ clouds' Beer Shadow Map, the sun-view optical-depth map the
volumetric clouds use for their own self-shadowing, and adds that stage to the graph early so the lighting
pass can read it. Each LUT texel is a point on the receiving plane: the ground, not the camera's
altitude. The BSM gives the optical depth of the cloud column along the sun ray through that point:
fn fs_ground_lut(in: VertexOutput) -> @location(0) vec4<f32> {
let world_xz = ground_lut.origin + in.uv * ground_lut.extent;
let p = vec3<f32>(world_xz.x - ground_lut_cam.position.x, ground_lut_cam.planeY, world_xz.y - ground_lut_cam.position.z);
return vec4<f32>(exp(-beer_shadow_col(p)), 0.0, 0.0, 1.0);
}
Because the column follows the sun ray, a cloud's shadow lands offset toward the side away from the sun, as it should at a low sun, not directly below the cloud. The receiver plane is set at the ground because the column through a point depends on that point's height whenever the sun isn't overhead. Baking at the camera's altitude would put the shadows under the wrong clouds when flying high.
Two details keep the lookup clean. The origin snaps to the LUT's own texel grid
(cloudShadowLutOrigin), so a stationary point doesn't flicker between bilinear errors as the
camera moves. And a lookup outside the square fades to clear over the outer 10% instead of clamping to the
edge texel: under heavy cover the edge texel is dark, and clamping would make the square's axis-aligned
border a visible seam, plainest with god rays at full coverage. Points above the cloud top return 1, so an aircraft above the deck isn't shaded by the clouds
below it.
Direct light only, and softer under overcast
cloud_t multiplies only the direct sun lobes. A cloud covers the sun's disc, not the sky, so
the IBL ambient stays. It also feeds back into PCSS: softness = 1 + 4·(1 − cloud_t), so a sun
behind thick cloud casts shadows up to five times softer, which is how overcast light looks. The cloud
pipeline itself (the BSM, the march, the god rays through the clouds) is covered in
Volumetric clouds, and the atmospheric god rays that also read the
shadow clipmap are in Atmosphere. The terrain term is merged into
this LUT even when the cloud ground shadows are off; the merge then starts from a white texture.
Night: shadows follow the Moon
Explorer has two directional lights. realSun is kept out of the scene and carries the real
sun's direction for the sky, the atmosphere, aerial perspective and the sky probe. sun is the
scene's key light, the one ShadowFeature finds with findSunLight(). By
day the key light is the sun. When the sun is down, applySun points the key light along the
Moon's actual light direction (Moon to camera, from where the Moon is drawn that frame, or from the
ephemeris), colors it a cool MOON_COLOR, and scales its intensity by the Moon's phase (the
illuminated fraction to the power 2.5, so a quarter moon is about a tenth of a full one) and by how high it
is (full brightness by about 8.6° up).
So yes, every shadow term follows the Moon. The clipmap is built from the key light, PCSS and the contact
march use light.direction, and TerrainShadow.update is also given
sun.worldDirection(), the key light, so mountains cast moon shadows across valleys. The shadows
are dim, because the light is. When the Moon sets, the key light's intensity falls to zero and the shadows
have nothing to darken. The night ambient is lifted by an airglow floor in the sky probe instead (see
Lighting), and the lighting feature is built with
disableHorizonFade so a set Moon doesn't also switch off all sky light.
Aerial scattering is
passed aerialSunDirection from realSun, not the key light. Otherwise, at night the
haze would be lit from the Moon's direction at sunlight's color balance. Shadows want the key light;
the sky wants the real sun. Keeping the two lights separate avoids special cases elsewhere.
Where the shadows stop
Above about 60 km the clipmap is a single empty level, and above 30 km the terrain term is off; how the planet looks from orbit is covered in Space, stars and other worlds. The ISS ride is the exception: the camera rides with the station, the nearest geometry is the station itself, and the clipmap fit (nearest = half the view distance) puts the levels around its truss and modules so the station shadows itself.
References
- R. Fernando, “Percentage-Closer Soft Shadows”, SIGGRAPH Sketches, 2005. The blocker search and penumbra estimate behind
pcss_visibility. - W. Reeves, D. Salesin, R. Cook, “Rendering Antialiased Shadows with Depth Maps”, SIGGRAPH 1987. Percentage-closer filtering, the final step of PCSS.
- F. Zhang, H. Sun, L. Xu, L. K. Lun, “Parallel-Split Shadow Maps for Large-scale Virtual Environments”, VRCIA 2006. The practical split blend used by the cascade path (λ = 0.9 in Explorer).
- A. Lauritzen, M. Salvi, A. Lefohn, “Sample Distribution Shadow Maps”, I3D 2011. The depth-reduction fit behind
SdsmReducerand the near-only variant. - W. Donnelly, A. Lauritzen, “Variance Shadow Maps”, I3D 2006; A. Lauritzen, M. McCool, “Layered Variance Shadow Maps”, GI 2008. Chebyshev-bound filtering and the exponential warp of the EVSM2 path.
- C. Tanner, C. Migdal, M. Jones, “The Clipmap: A Virtual Mipmap”, SIGGRAPH 1998. The nested, camera-centered level structure the shadow clipmap borrows its name and layout from.
- J. Jimenez, “Next Generation Post Processing”, SIGGRAPH Advances in Real-Time Rendering course, 2014. Interleaved gradient noise, the per-pixel kernel rotation.
- S. Hillaire, “Physically Based Sky, Atmosphere and Cloud Rendering”, SIGGRAPH Physically Based Shading course, 2016. Beer shadow maps for volumetric cloud shadows.