Reversed-Z + Infinite Far: Planetary-Scale Depth in WebGPU
Why Pinionfall ripped out manual frag_depth logarithmic depth for hardware Reversed-Z + Infinite Far (depth32float) in WebGPU: exact IEEE-754 precision math, Early-Z recovery, every pipeline flip, and five real compromises.
If you have ever built a 3D engine with large view distances (open worlds, flight sims, or seamless multi-planet games like Pinionfall where a single camera sees both a grass blade 15 cm from your boots and an asteroid belt 2,000 kilometers out in orbit), you eventually hit the same brick wall: the depth buffer runs out of precision and distant geometry turns into a flickering Z-fighting soup.
Pinionfall originally solved that with a classic trick: a logarithmic depth buffer written manually via @builtin(frag_depth). It kept planets and settlements Z-fighting-free, so we left it alone while building the rest of the game.
Now that all the pieces of Pinionfall are working together and we are doing our December top-to-bottom WebGPU overhaul (currently landing on our overhaul branch ahead of the next release), Reversed-Z + Infinite Far Plane (depth32float) is one of the very first foundational upgrades we landed.
Here is the complete, practical breakdown of how Reversed-Z actually works, why it feels like an IEEE-754 cheat code, what it improves and what it compromises, and every single flip and trap you need to watch for in WebGPU.
1. The Problem: Perspective Projection Wastes Almost All of Your Depth Buffer
In a standard perspective camera, clip-space depth is divided by view-space distance z. In WebGPU’s [0, 1] clip-space depth convention (the same as Direct3D 12, Metal, and Vulkan):
d_std(z) = f · (z - n) / (z · (f - n))
Plug in near = 0.1 m and far = 100,000 m:
- At 0.1 m (near plane):
d = 0.0 - At 0.2 m (10 centimeters past the near plane):
d = 0.5000 - At 1.0 m:
d = 0.9000 - At 10.0 m:
d = 0.9900 - Everything from 10 m to 100 km is squished into the last 1% of the depth buffer (
0.99to1.0).
Now look at what happens when you store that value in a 32-bit floating-point depth buffer (depth32float).
IEEE-754 floats are not evenly spaced. Every power-of-two band ([0.5, 1], [0.25, 0.5], [0.125, 0.25], and so on) holds the exact same 8,388,608 floats (2^23), so roughly 99.2% of all floats in [0, 1] (~1.06 billion values) sit below 0.5. They get exponentially denser toward 0.0 and are sparsest near 1.0.
In Standard-Z, you pack everything beyond 20 centimeters next to 1.0 (where float32 is sparsest) and hand over a billion (~1.06 billion) tiny float values below 0.5 to the ten centimeters right in front of your camera.
Look at the yellow and red curves above (computed from exact IEEE-754 adjacent-ULP math, near = 0.1 m, far = 100 km):
- Standard-Z
depth32floatis no better thandepth24unormbeyond 20 centimeters, because everything farther away lives inside the single[0.5, 1.0]float exponent bin (only 23 mantissa bits). - By 1 km, adjacent depth steps are already 0.60 meters apart: instant Z-fighting on roads, decals, windows, roofs, and shadows.
2. The Classic Band-Aid (What Pinionfall Used Before): Logarithmic Depth
To survive planetary distances (0.1 m up to 2,000 km), Pinionfall, like Outerra and many space engines before it, originally computed a logarithmic depth curve manually:
// Legacy log-depth: fixes per-vertex chord error, but disables Early-Z & Hi-Z!@fragmentfn fs_main(in: VertOut) -> FragOut { var out: FragOut; let log_z = log(max(in.clip_w * frame.log_depth_fc + 1.0, 1.0)) / log(frame.log_depth_far * frame.log_depth_fc + 1.0); out.frag_depth = clamp(log_z, 0.0, 1.0); // ... shade G-buffer / material ... return out;}On the precision chart, log-depth looks great (purple dotted curve). So why did we rip it out?
Because logarithmic depth traps you in a catch-22 with four real costs:
- Per-vertex log depth causes chord error; fixing it per pixel kills Hardware Early-Z and Hi-Z. Computing log depth in the vertex shader lets hardware linearly interpolate a curved
log(z)function across screen space, bending long triangles away from their true geometric plane (chord error). Movinglog()into the fragment shader via@builtin(frag_depth)eliminates that chord error, at the cost of forcing the GPU into Late-Z: the hardware can no longer know a fragment’s depth before running the fragment shader, so occluded pixels behind buildings, hills, trees, and rocks still shade before getting discarded. In Pinionfall, 22+ mesh and transparent shaders were writing custom@builtin(frag_depth). - We had to build a manual software Early-Z pass just to cope. Because rock meshes wrote
@builtin(frag_depth)and lost hardware Early-Z, roughly 60% of every rock planted in the ground (plus rocks behind trunks and terrain) was shading only to fail the late depth test. We maintained a separate compute pass,ground-depth-pass(a half-resolution conservative depth snapshot costing +8.3 MB VRAM at 4K), solely so the rock shader could hand-cull hidden fragments in software. - Expensive depth reconstruction everywhere. Every depth-reading pass (SSAO, SSR, contact shadows, water refraction, decals, clouds, TAA/TSR) had to decode log depth with
exp()instead of a single division. - No free hardware Hi-Z acceleration across standard opaque geometry until manual
frag_depthis removed.
3. The Cheat Code: Reversed-Z + Infinite Far Plane
Flip the projection matrix so near maps to 1.0 and far maps to 0.0. Then take the limit as far -> ∞:
d_rev(z) = n / z
Look at what happens to the float32 mantissa bands:
[0.1 m to 0.2 m]->[1.0 to 0.5]-> 8,388,608 depth steps[0.2 m to 0.4 m]->[0.5 to 0.25]-> 8,388,608 depth steps[~819 m to 1,638 m]->[2^-13 to 2^-14]-> 8,388,608 depth steps[~1,678 km to 3,355 km]->[2^-24 to 2^-25]-> 8,388,608 depth steps
Every single doubling of distance gets its own dedicated 23-bit mantissa.
Hyperbolic 1/z perspective compression and IEEE-754 floating-point spacing cancel each other out, giving you an almost perfectly flat ~24-bit quasi-logarithmic depth buffer completely in fixed-function hardware, with zero chord error (because clip.z / clip.w = near / z is affine in 1/w, so hardware interpolation is exact) and zero manual @builtin(frag_depth) writes on standard meshes.
Check the exact adjacent-ULP depth steps (near = 0.1 m, depth32float, with band worst-case z · 2^-23 in parentheses):
- At 1 m: 0.00007 mm exact (
<= 0.00012 mmworst-case) - At 1 km: 0.073 mm exact (
<= 0.12 mmworst-case: sub-millimeter across a full kilometer) - At 100 km: 1.14 cm exact (
<= 1.19 cmworst-case) - At 2,000 km (high planetary orbit): 0.14 m exact (
<= 0.24 mworst-case), with no far clip plane and no near-plane compromise.
And because hardware Early-Z and Hi-Z turn back on across our standard opaque and translucent mesh shaders (keeping manual @builtin(frag_depth) strictly on ray-offset impostors and carved snow-contact recesses), fragments behind already-drawn foreground geometry are rejected before the fragment shader runs.
The immediate wins we landed on our overhaul branch:
- Linearizing depth becomes 1 division:
let linear_z = frame.near / d;(replacingexp()in 15+ shaders). - Bend Studio screen-space contact shadows already trace in inverse view depth
1/w: Reversed-Z hands them the exact projective quantity (d / near) straight out of the hardware depth texture. - Deletes our hand-built software Early-Z pass: we deleted
ground-depth-pass.ts(-8.3 MB VRAM at 4K + 1 fewer compute pass every frame). - Zero far-plane popping: distant moons, orbital rings, and secondary planets never slice against an arbitrary far clip plane.
4. How to Implement Reversed-Z + Infinite Far in WebGPU (5-Minute Checklist)
In a right-handed camera looking down -Z with WebGPU’s [0, 1] NDC depth range:
// Right-handed Infinite Reversed-Z projection matrix (column-major for WGSL)export function perspectiveInfiniteReversedZ( out: Float32Array, fovYRad: number, aspect: number, near: number,): Float32Array { const f = 1.0 / Math.tan(fovYRad * 0.5); out.fill(0); out[0] = f / aspect; out[5] = f; out[10] = 0; // P[2][2] = 0 (far -> infinity maps to 0.0!) out[11] = -1; // w_clip = -z_view out[14] = near; // P[3][2] = near (z = -near maps to 1.0!) return out;}Then flip your WebGPU render pipeline and shader conventions everywhere scene depth is touched:
- Depth attachment format:
'depth32float'(neverdepth24plus, see compromises below). - Depth clear value:
depthClearValue: 0.0(sky/background is now0.0). - Depth test comparator:
'greater'or'greater-equal'(closer objects have larger depth values). - Polygon offset /
depthBias: flip the sign (depthBias: -k,depthBiasSlopeScale: -s). - Sky / miss test:
if (d <= 0.0) { /* sky */ }instead ofd >= 0.99999(and if you guard division with a clamp, use a tiny floor likemax(d, 1e-30), never1e-7, which clamps everything past 1,000 km). - Hi-Z pyramid & occlusion culling: in Reversed-Z, the conservative farthest depth in a
2x2block ismin(d00, d10, d01, d11)(notmax), and an object’s bounding box is occluded only when its nearest corner satisfiesbox.maxZ < hizMinZ. - Depth-offset impostors: only keep
@builtin(frag_depth)on genuine ray-offset billboards/impostors (or carved snow-contact recesses), and writeframe.near / max(linear_z, frame.near).
5. Honest Engineering: What Are the Compromises & Gotchas?
Every graphics technique has trade-offs. Reversed-Z is as close to a free lunch as rendering gets, provided you respect five real constraints:
- It requires
depth32float. Do not pair Reversed-Z withdepth24unormordepth24plus. Integer depth formats have uniform precision from0to1, so reversing them gives zero precision gain. Most GPUs already pad 24-bit depth to 32 bits in memory anyway, sodepth32floatusually uses the same 4 bytes/pixel (the real extra cost only shows up if you also require stencil viadepth32float-stencil8, which commonly uses 8 bytes/pixel depending on hardware; skip stencil unless you truly need it). - Orthographic shadow maps do not benefit. Orthographic projections (like directional sun CSM cascades) already distribute depth linearly. Reversing an orthographic map into
depth32floatdoes not improve worst-case precision: it simply piles unused float density at the far edge and shifts the coarser steps toward the light. Keep orthographic CSM cascades in standard[0, 1](and note that perspective spot/point shadow maps are a separate case, where short-range standard[0, 1]ordepth16unormmaps are typically plenty). - It does not fix world-space
float32vertex jitter. Reversed-Z solves depth-buffer quantization, not world-coordinate rounding. If your camera is 800 km from the origin, you still need camera-relative / eye-relative coordinates (subtracting camera position on the CPU infloat64before uploading transforms to the GPU, which Pinionfall already does ineye-relative.ts). - Watch out for division by zero on sky pixels (
d == 0.0). With an infinite far plane, every sky texel stores exact0.0. Every screen-space pass (ambient occlusion, SSR, volumetric effects, decals, temporal velocity dilation) must explicitly early-out ond <= 0.0(or use a tiny floor likemax(d, 1e-30)) before evaluatingnear / dso you never injectInf/NaNinto temporal history buffers. - Replacing finite far-plane assumptions in legacy shaders. If any legacy shader assumed
farwas finite (for example, computing normalized[0, 1]fog distance from raw depth instead of linear view distance, or unprojecting frustum corners atndc.z = 0.0where infinity now lives), it needs to switch tolinear_z = near / dand unproject atndc.z = 1.0instead.
Why We Implemented It Right at the Start of the Overhaul
Every major rendering upgrade we have planned on the roadmap (occlusion culling, ambient occlusion, lighting, atmosphere, reflections, water, and transparency) reads from the scene depth buffer.
Building any of those on top of legacy @builtin(frag_depth) logarithmic depth would mean baking exp() reconstructions, Late-Z stalls, and software Early-Z workarounds into every new shader, only to rewrite them all later. Starting the overhaul with Infinite Reversed-Z gives the entire renderer a clean foundation from Day 1:
- Standard mesh shaders regain hardware Early-Z & Hi-Z right out of the gate, letting us delete our manual
ground-depth-passcompletely. - 1-division depth linearization (
near / d) speeds up every depth-reading pass we already have as well as every new pass we are about to build. - Sub-millimeter to orbital precision with zero far-plane clipping and zero chord-error hacks.
If you are starting a new WebGPU, Vulkan, Metal, or DX12 renderer today, make Reversed-Z + Infinite Far (depth32float) your default from Line 1. You will never miss the far plane.
Primary References & Further Reading
- Nathan Reed (NVIDIA): Visualizing Depth Precision (2015)
- Brano Kemen (Outerra): Maximizing Depth Buffer Range and Precision (2012)
- Emil Persson (Humus, SIGGRAPH 2012): Creating Vast Game Worlds
- Matt Pettineo (MJP): Attack of the Depth Buffer (2010)
- W3C WebGPU Spec: Coordinate Systems
Play Pinionfall free in your browser (WebGPU) at pinionfall.com, follow the overhaul on the roadmap, or inspect the full engine source licence.