1380 MODELS INDEXED Account
GUIDE · THREE.JS RENDERING

Depth precision in three.js: z-fighting, logarithmicDepthBuffer and reversed-Z

UPDATED
24 MIN READ · BY 3D ASSET

Z-fighting has two different causes. Exactly coplanar faces fight at any precision and are fixed in geometry or with polygonOffset. Faces a few millimetres apart fight because a standard 24-bit depth buffer has a step of about distance² / (near × 16.8 million), and in our tests surfaces needed about twice that: raise camera.near first. logarithmicDepthBuffer fixes range but writes gl_FragDepth; on an Apple M5 it made our test scenes 1.7–7.2× slower and disabled polygonOffset. Reversed-Z with a float depth buffer gives more precision for free.

Three threads, one depth buffer

Saturn with its ring system at real scale, a small probe in the foreground
Saturn at real scale (units: kilometres) with a probe 16 metres from the camera — a near-to-far range of a billion to one. This frame uses reversed-Z with a float depth buffer; the same scene with the default depth setup is further down.

Three questions keep coming back on the three.js forum. “Beware of logarithmic depth buffer — it can degrade scene performance” reports a terrain with instanced foliage dropping from about 65 to 35 FPS when logarithmicDepthBuffer is switched on. “Poor quality of Saturn-like rings and spheres” asks why thin rings look broken. “Depth Prepass — how is it done?” asks how to draw depth first so expensive pixels are shaded only once. None of them ends with numbers anyone else can reuse.

All three are about one piece of hardware: the depth buffer — how many distinct distances it can tell apart, and what it costs when a shader takes over writing it. We measured both on one machine, with three.js r180:

  • Precision. For each depth setup and distance from 1 m to 30 km: the smallest gap between two parallel surfaces that stops them flickering, read back pixel by pixel.
  • Cost. Frame time of the default depth buffer, logarithmicDepthBuffer, reversed-Z and a depth prepass on three scenes: 39,990 instanced low-poly trees, the same forest as alpha-tested cards, and the showcase block of our Brown City pack.
  • Our own data. The geometric z-fight audit we run on every model, check:zfight, and what its first pass over 1,798 models found.

Measured on Apple M5 (MacBook), Chrome 158, ANGLE → Metal, three.js r180. Frame times are synchronised time per frame: batches of frames closed by a 1-pixel readPixels and timed with performance.now(), so they include CPU submission and the sync as well as GPU work; mean of 2 passes on fresh page loads; in 47 of 62 configurations the two passes were within 5% of their mean; the largest gap was 13% (cards with log depth at 1080p, 8.46 and 9.64 ms). Apple GPUs are tile-based; where a result could differ on a desktop GPU we say so.

Quick diagnosis

  • Flickers even close up → first check for coincident or nearly coincident surfaces. Exactly coplanar ones need a geometry fix or polygonOffset; no depth setting helps them.
  • Appears only in the distance → the gap is smaller than the depth step there. Raise camera.near, widen the gap, or change the depth mode.
  • Shimmers on thin, repeated detail (rings, fences, wires) → aliasing, not depth. Move the detail into a mipmapped texture.

The short version

Scroll the table sideways for all columns →

SetupSmallest safe gap at 300 mAt 3 kmFrame cost (forest, 4K)Use it when
Default, near = 0.168 mm11 m2.09 msScenes up to a few hundred metres. Raise near as far as the camera allows.
Default, near = 111 mm1.0 m2.09 msSame buffer, 10× more precision — the cheapest fix there is.
logarithmicDepthBuffer152 µm2.6 mm10.5 msOnly when nothing else is available. Breaks polygonOffset, slows every pixel.
Reversed-Z, float depth23 µm518 µm2.13 msHuge ranges (space, flight, open worlds). Needs EXT_clip_control and care with offsets.

The rest of the article explains where each number comes from, shows what each failure looks like, and gives code for every fix.

How a depth buffer spends its bits

A perspective camera does not store distance. It stores a value proportional to 1 / z, remapped so that near becomes 0 and far becomes 1 (in WebGL it goes through −1…1 first). This is what makes depth interpolate correctly across a triangle, and it is also why precision is spent so unevenly: half of all depth values describe the space between near and 2 × near. With near = 0.1, half the buffer is used on the first 20 centimetres in front of the lens.

The size of one depth step at distance z follows directly from that curve. For the default setup it is close to

// One step of a standard (non-reversed) 24-bit depth buffer at distance z, in metres:
// the distance between two neighbouring stored values. far barely matters.
const depthStep = (z, near, far = Infinity) =>
  (z * z * (1 - near / far)) / (near * (2 ** 24 - 1));

depthStep(10, 0.1);    // 0.06 mm
depthStep(100, 0.1);   // 6 mm
depthStep(1000, 0.1);  // 0.6 m  — a car parked on a road is "inside" the road
depthStep(1000, 1);    // 6 cm

That is the theoretical step. A gap of one step is not yet a safe gap: the projection is computed in 32-bit floats, interpolated depth is rounded, and two surfaces must land at least one step apart in every pixel they share. In the test below the safe gap came out at about twice the step, so as a working rule give detail at least 2 × depthStep, which is z² / (near · 8.4 M).

Two things in that formula decide almost everything. Precision falls with the square of distance, so a scene that is fine at 50 m is 16× worse at 200 m. And it scales linearly with near: moving the near plane from 0.1 to 1 buys exactly 10× everywhere. far hardly appears — pulling it in from 10 km to 1 km changes almost nothing for objects at 100 m. That is the opposite of what most people try first.

Measured, not just computed

To check the formula and to compare setups that do not follow it, we rendered two parallel planes, tilted 45° to the view, the farther one red and drawn second so that a tie in depth goes to it — the worst case. For every distance the page bisects the gap until fewer than 1% of the pixels show red. The planes cover a 256 × 256 render without anti-aliasing; every setup sees exactly the same geometry.

Chart scrolls sideways · full numbers in the table under it →

Smallest gap that does not z-fight (lower is better)

  • Default, near 0.01
  • Default, near 0.1
  • Default, near 1
  • logarithmicDepthBuffer
  • Reversed-Z, float depth
0.1 µm1.0 µm10 µm100 µm1.0 mm10 mm0.10 m1.0 m10 m100 m1000 m1 m3 m10 m30 m100 m300 m1 km3 km10 km30 kmDefault, near 0.01, 1 m: 4.5 µmDefault, near 0.01, 3 m: 112 µmDefault, near 0.01, 10 m: 45 µmDefault, near 0.01, 30 m: 8.0 mmDefault, near 0.01, 100 m: 44 mmDefault, near 0.01, 300 m: 0.64 mDefault, near 0.01, 1 km: 8.3 mDefault, near 0.01, 3 km: 124 mDefault, near 0.01, 10 km: 921 mDefault, near 0.01, 30 km: 1570 mDefault, near 0.1, 1 m: 0.5 µmDefault, near 0.1, 3 m: 7.3 µmDefault, near 0.1, 10 m: 45 µmDefault, near 0.1, 30 m: 598 µmDefault, near 0.1, 100 m: 13 mmDefault, near 0.1, 300 m: 68 mmDefault, near 0.1, 1 km: 0.97 mDefault, near 0.1, 3 km: 11 mDefault, near 0.1, 10 km: 98 mDefault, near 0.1, 30 km: 410 mDefault, near 1, 1 m: 0.1 µmDefault, near 1, 3 m: 1.0 µmDefault, near 1, 10 m: 3.2 µmDefault, near 1, 30 m: 47 µmDefault, near 1, 100 m: 1.0 mmDefault, near 1, 300 m: 11 mmDefault, near 1, 1 km: 7.3 mmDefault, near 1, 3 km: 1.0 mDefault, near 1, 10 km: 9.5 mDefault, near 1, 30 km: 45 mlogarithmicDepthBuffer, 1 m: 0.3 µmlogarithmicDepthBuffer, 3 m: 0.9 µmlogarithmicDepthBuffer, 10 m: 3.3 µmlogarithmicDepthBuffer, 30 m: 9.9 µmlogarithmicDepthBuffer, 100 m: 34 µmlogarithmicDepthBuffer, 300 m: 152 µmlogarithmicDepthBuffer, 1 km: 502 µmlogarithmicDepthBuffer, 3 km: 2.6 mmlogarithmicDepthBuffer, 10 km: 9.0 mmlogarithmicDepthBuffer, 30 km: 25 mmReversed-Z, float depth, 1 m: 0.2 µmReversed-Z, float depth, 3 m: 0.5 µmReversed-Z, float depth, 10 m: 2.0 µmReversed-Z, float depth, 30 m: 4.5 µmReversed-Z, float depth, 100 m: 26 µmReversed-Z, float depth, 300 m: 23 µmReversed-Z, float depth, 1 km: 124 µmReversed-Z, float depth, 3 km: 518 µmReversed-Z, float depth, 10 km: 1.8 mmReversed-Z, float depth, 30 km: 4.1 mmdistance from the camera →
Two planes 45° to the view, far plane drawn second, gap bisected until < 1% of pixels fight; far = 100 km. Apple M5 (MacBook), Chrome 158, ANGLE → Metal, three.js r180. Single points can jump by a few times because of where a surface falls between two depth steps; the slopes are what matters.
All values (smallest gap that does not fight)
Distancenear 0.01near 0.1near 1log depthreversed, float
1 m4.5 µm0.5 µm0.1 µm0.3 µm0.2 µm
3 m112 µm7.3 µm1.0 µm0.9 µm0.5 µm
10 m45 µm45 µm3.2 µm3.3 µm2.0 µm
30 m8.0 mm598 µm47 µm9.9 µm4.5 µm
100 m44 mm13 mm1.0 mm34 µm26 µm
300 m0.64 m68 mm11 mm152 µm23 µm
1 km8.3 m0.97 m7.3 mm502 µm124 µm
3 km124 m11 m1.0 m2.6 mm518 µm
10 km921 m98 m9.5 m9.0 mm1.8 mm
30 km1570 m410 m45 m25 mm4.1 mm

For the default setup the safe gap sits at about twice the theoretical step: at 100 m with near = 0.1 the step is 6 mm and the planes needed 13 mm; at 1 km the step is 0.6 m and we measured 0.97 m. Keep in mind what this number is: a gap measured along the normal of two planes tilted 45°, with fewer than 1% fighting pixels as the threshold. It is a property of this test, not a constant of the hardware; a different angle or threshold moves it by a small factor. The other two lines are almost straight: their step grows only linearly with distance. That is the whole point of both the logarithmic buffer and reversed-Z, and the chart shows how differently they get there — at 1 km reversed-Z resolves 124 µm, the logarithmic buffer 502 µm, the default 0.97 m.

Working rules from these measurements, with any sensible far:

SetupSafe gap at distance z (this test)Measured at z = 300 m
Default projectionz² / (near · 8.4 M) — two steps of z² / (near · 16.8 M)near 0.1: 68 mm · near 1: 11 mm
Reversed-Z, 24-bit fixed-point depthsame theoretical step; about half the default’s safe gap in our emulation, because the projection loses less in float math38 mm (near 0.1, emulated)
logarithmicDepthBufferabout z · ln(far) / 16.8 M: ≈ 7·10⁻⁷ z at far = 100 km152 µm
Reversed-Z, float depthabout z / 8.4 M: ≈ 1.2·10⁻⁷ z, independent of near and far23 µm

Coplanar faces: a precision problem that more precision cannot fix

Before touching the camera, look at what is actually fighting. If two faces lie in the same plane — a poster on a wall, a road marking at road level, the top of a box that sits flush inside another box — their depths are equal up to rounding, and rounding differs between two triangles that cover the same pixel with different vertices. No buffer resolves a gap of zero. Every setup in the chart above fights here, the float buffer included.

A blue BAKERY sign on a brick wall, half of it replaced by bricks along a diagonal line
A sign exactly on the wall face, no offset. Half of it loses to the wall along the triangle diagonal — at 30 metres, with near 0.1.
The same sign drawn cleanly over the wall
The same sign with polygonOffset (factor −2, units −2). Clean at every distance we tested, up to 30 km.

In the precision test the same coplanar “decal” — smaller than the base plane and triangulated differently — showed between 6% and 74% of its pixels without an offset, at random, distance after distance. With polygonOffset it showed 94%–100%. There are three fixes, in order of preference:

  1. Delete the hidden face. If a box sits flush inside another, its buried face is invisible anyway and only costs triangles. In the audit described at the end of this article, identical overlapping triangle pairs turned up 570 thousand times across the catalogue.
  2. Move it. A real gap that the buffer can resolve at the distances the object will be seen from. With the default near = 0.1, 3 mm holds to about 50 m and 5 cm to about 200 m — the numbers behind the rules in our own pipeline, below.
  3. Offset the depth, not the geometry, with polygonOffset, when the detail must stay flush: decals, painted lines, labels.
// Decal material: same look, pulled towards the camera in depth only.
function decalMaterial(base, level = 1) {
  const m = base.clone();
  m.polygonOffset = true;
  m.polygonOffsetFactor = -2 * level;  // scales with the surface's depth slope (grazing views)
  m.polygonOffsetUnits = -2 * level;   // in minimum resolvable depth steps
  return m;                            // share it: one decal material per base, not per mesh
}

That is the helper our Food pack uses for seeds, grill lines and printed labels; a decal laid over another decal uses level = 2, so the two layers never tie. polygonOffset is applied by the rasteriser after interpolation: factor multiplies how fast depth changes across the polygon (large at grazing angles), units adds a fixed number of depth steps. Because it works in depth steps rather than metres, the same values hold close up and far away — as long as the GPU computes the depth itself. The next two sections are about setups where it does not.

The cheapest fix: move the near plane

A near plane of 0.01 or 0.001 is common in examples and viewers (“so the camera can get close”). It costs a factor of 10 or 100 in precision at every distance. Our street test scene has lane markings 4 mm above the asphalt and window panels 1 cm proud of the facades, out to 1.5 km. We drew the base surfaces after the details, so every depth tie goes to the base: three.js orders opaque objects by material and distance, and whether your wall happens to be drawn before or after its windows is not something to rely on.

Distant facades with window panels broken into fragments
near = 0.01: windows 1 cm proud tear apart beyond about 30 m.
The same facades, only the farthest windows slightly broken
near = 0.1: the same view; only the far end breaks.
The same facades with intact windows
near = 1: intact as far as the windows can be seen.
The same facades with intact windows, reversed depth
Reversed-Z with float depth and near = 0.01: intact as well.

So the first question is never “which depth trick?” but “how close does this camera really get?”. A walking character’s camera rarely needs anything under 0.1–0.3 m; a city or terrain overview can use 1–10 m; a product viewer can set near from the bounding sphere. If the camera moves between those regimes, set near per frame from what is actually close:

// Fit near to the closest bounding sphere that reaches in front of the camera.
// spheres: world-space THREE.Sphere for each object or chunk, computed once.
const v = new THREE.Vector3();
function fitNear(camera, spheres, minNear = 0.05, maxNear = 5) {
  camera.updateMatrixWorld();
  let closest = Infinity;
  for (const s of spheres) {
    const depth = -v.copy(s.center).applyMatrix4(camera.matrixWorldInverse).z; // + = in front
    if (depth + s.radius <= 0) continue;               // entirely behind the camera
    closest = Math.min(closest, depth - s.radius);     // < 0 when the camera is inside it
  }
  const near = THREE.MathUtils.clamp(closest * 0.5, minNear, maxNear);
  // Pull near in at once (or something gets clipped); push it out only with hysteresis.
  if (near < camera.near || near > camera.near * 1.25) {
    camera.near = near;
    camera.updateProjectionMatrix();     // uniforms only — no shader recompilation
  }
}

Changing near/far is a uniform update. Anything that reads the depth buffer back (SSAO, depth of field, soft particles) must be told the new values. In r180 the stock SSAOPass copies cameraNear/cameraFar only in its constructor and the projection matrices only in setSize(); with a dynamic near, update all four uniforms after updateProjectionMatrix(), as our viewer does.

logarithmicDepthBuffer: what it does, and what it costs

When the range is genuinely huge, three.js offers new WebGLRenderer({ logarithmicDepthBuffer: true }). It does not change the buffer; it replaces the value written into it. Every built-in material gets two small chunks:

// vertex (logdepthbuf_vertex)
vFragDepth = 1.0 + gl_Position.w;          // w = view-space distance

// fragment (logdepthbuf_fragment), r180
gl_FragDepth = vIsPerspective == 0.0
  ? gl_FragCoord.z
  : log2( vFragDepth ) * logDepthBufFC * 0.5;  // logDepthBufFC = 2 / log2(far + 1)

Depth becomes log(1 + w) / log(1 + far), and the step size becomes proportional to distance — the straight amber line in the chart. The cost is the last line. As soon as a fragment shader writes gl_FragDepth, the GPU cannot know a fragment’s depth until the shader has run, so it cannot reject hidden fragments early. On desktop GPUs this switches off early-Z; on Apple’s tile-based GPUs it switches off hidden-surface removal, which normally shades each pixel of opaque geometry once regardless of draw order. Every covered pixel of every layer is shaded, then thrown away.

Measured

Chart scrolls sideways · full numbers in the table under it →

Frame time with and without logarithmicDepthBuffer (lower is better)

  • Default
  • logarithmicDepthBuffer
  • Reversed-Z
0 ms7 ms14 ms21 ms28 msForest, 1080pDefault, Forest, 1080p: 1.2 ms1.2 mslogarithmicDepthBuffer, Forest, 1080p: 3.7 ms3.7 msReversed-Z, Forest, 1080p: 1.2 ms1.2 msForest, 4KDefault, Forest, 4K: 2.1 ms2.1 mslogarithmicDepthBuffer, Forest, 4K: 11 ms11 msReversed-Z, Forest, 4K: 2.1 ms2.1 msAlpha-tested cards, 1080pDefault, Alpha-tested cards, 1080p: 1.4 ms1.4 mslogarithmicDepthBuffer, Alpha-tested cards, 1080p: 9.1 ms9.1 msReversed-Z, Alpha-tested cards, 1080p: 1.3 ms1.3 msAlpha-tested cards, 4KDefault, Alpha-tested cards, 4K: 3.5 ms3.5 mslogarithmicDepthBuffer, Alpha-tested cards, 4K: 25 ms25 msReversed-Z, Alpha-tested cards, 4K: 3.5 ms3.5 msCity block, 1080pDefault, City block, 1080p: 2.3 ms2.3 mslogarithmicDepthBuffer, City block, 1080p: 3.8 ms3.8 msReversed-Z, City block, 1080p: 2.3 ms2.3 msCity block, 4KDefault, City block, 4K: 3.5 ms3.5 mslogarithmicDepthBuffer, City block, 4K: 9.1 ms9.1 msReversed-Z, City block, 4K: 3.5 ms3.5 ms
Synchronised frame time, mean of 2 passes, Apple M5 (MacBook), Chrome 158, ANGLE → Metal, three.js r180. Forest: 39,990 instanced trees, 1,599,612 triangles. Cards: the same forest with three crossed alpha-tested quads per crown. City: Brown City block-01 merged by material, 420,295 triangles. No shadows, no MSAA, no post-processing; the sky is a tone-mapped mesh.
All values: frame time with and without log depth
SceneDefaultLog depthReversed-ZLog ÷ default
Forest, 1080p1.19 ms3.7 ms1.19 ms3.1×
Forest, 4K2.09 ms10.5 ms2.13 ms5×
Cards, 1080p1.38 ms9.05 ms1.33 ms6.6×
Cards, 4K3.52 ms25.4 ms3.5 ms7.2×
City, 1080p2.27 ms3.79 ms2.25 ms1.7×
City, 4K3.48 ms9.05 ms3.49 ms2.6×

The forum’s 65 → 35 FPS is, if anything, mild. On the instanced forest the logarithmic buffer made the frame 3.1× slower at 1080p and 5× slower at 4K; on the alpha-tested version — the foliage case from the thread — 6.6× and 7.2× (3.52 ms → 25.4 ms). Even the city block, with far less overdraw, went from 3.48 ms to 9.05 ms at 4K. The penalty grows with resolution and with overdraw, because it is paid per hidden fragment. Reversed-Z, which gives more precision than the logarithmic buffer, costs nothing measurable.

As grml points out in the thread, a percentage of FPS is a poor unit: 500 → 400 FPS is 0.5 ms, 60 → 48 FPS is 4.2 ms. The table above is in milliseconds for that reason. In our numbers the extra cost was 8.43 ms per 4K frame on the forest — half a 60 Hz frame budget — and 21.9 ms on the cards, more than a whole one.

Sorting does not save you

With a normal depth buffer, drawing front to back is the classic way to cut overdraw: hidden fragments fail the depth test before shading. We drew the forest’s instances in random order, sorted front to back and sorted back to front:

Instance order (4K)DefaultLog depth
Front to back2.05 ms10.7 ms
Random2.09 ms10.5 ms
Back to front3.79 ms11.5 ms

With the default buffer order matters even on a tile-based GPU (back to front is 1.8× slower). With the logarithmic buffer all three orders cost the same, because the depth test now runs after the shader whatever the order. One InstancedMesh is a single draw, so three.js never sorts its instances in the first place — exactly the foliage case.

It also turns off polygonOffset

This one is rarely mentioned. polygonOffset is applied to the depth the rasteriser computes; a shader that writes gl_FragDepth replaces that value, offset and all. With the logarithmic buffer on, our offset decal behaved exactly like the decal without an offset — between 18% and 58% of it visible at the distances we tested.

The BAKERY sign broken up into noisy fragments of brick and sign
Log depth, same polygonOffset as the clean image above: the offset is ignored and the sign fights the wall.
The sign drawn cleanly
Default depth, same material: clean.

If you have to keep the logarithmic buffer, offset the decal in the shader instead. In log space a constant shift of depth is a constant relative shift of distance, so one value works near and far; with 1e-6 and far = 100 km it moves the decal about 0.001% of its distance towards the camera (1 mm at 100 m), and in our test the decal was 100% visible from 1 m to 30 km:

// Decal under logarithmicDepthBuffer: polygonOffset is ignored, so bias gl_FragDepth.
decal.material.onBeforeCompile = (shader) => {
  shader.fragmentShader = shader.fragmentShader.replace(
    '#include <logdepthbuf_fragment>',
    '#include <logdepthbuf_fragment>\n  gl_FragDepth -= 1e-6;'
  );
};
decal.material.customProgramCacheKey = () => 'log-decal';

Two more side effects. Anything that reads the depth buffer and converts it back to distance assumes the standard curve: in r180 none of the depth-reading passes in examples/jsm/postprocessing (SSAOPass, SAOPass, GTAOPass, SSRPass, BokehPass) decodes logarithmic depth, so ambient occlusion and depth of field go wrong. And the shadow pass uses the same chunks, so shadow maps of directional and spot lights are rendered without early depth rejection too.

Reversed-Z in three.js r180

Reversed-Z gets the same linear behaviour without touching the shader. Map near to 1 and far to 0 instead of the other way round, and store depth as a 32-bit float. A float has the same relative precision everywhere and enormous precision near 0 — exactly where the 1/z curve crowds distant objects. The two non-linearities cancel, and in our test the safe gap became about z / 2²³: 0.12 mm at 1 km, independent of near and far. The depth test flips to “greater”, the clear value to 0. Nothing is written from the shader, so early-Z and hidden-surface removal keep working.

const renderer = new THREE.WebGLRenderer({ antialias: true, reversedDepthBuffer: true });

// The flag is silently ignored without EXT_clip_control — check and fall back.
if (!renderer.capabilities.reversedDepthBuffer) {
  console.warn('No EXT_clip_control: raise camera.near or use logarithmicDepthBuffer');
}

// three.js then builds reversed projection matrices for every camera it renders
// with and swaps depth functions and the clear value; materials need no changes.

Two details decide whether this works as advertised.

It needs a float depth buffer

Reversed-Z with a 24-bit fixed-point buffer gains very little: fixed point has the same step everywhere, so there is no extra precision near 0 to spend. We could not get a real 24-bit buffer on this Mac — Apple GPUs and Chrome’s SwiftShader both store the canvas’s “24-bit” depth as a 32-bit float, which is why rev on the canvas and rev into an explicit float target gave identical numbers. So we emulated one, by rounding the depth to 1/(2²⁴ − 1) steps in the fragment shader. At 1 km, reversed-Z with fixed-point depth resolved 0.42 m against 0.97 m for the default — about twice as good — while reversed-Z with float depth resolved 124 µm.

On Windows (Direct3D through ANGLE) and most Android GPUs the default framebuffer has a real 24-bit depth buffer. If you need reversed-Z there, render into a target with a float depth texture and copy the colour to the screen:

// Explicit 32-bit float depth. With reversedDepthBuffer: true this is the real thing
// on every GPU, not only on those that happen to back the canvas with float depth.
// This is the output path we measured: linear half-float colour, then ACES + sRGB
// applied once, in the copy (three.js tone-maps only when drawing to the canvas).
const target = new THREE.WebGLRenderTarget(w, h, {
  type: THREE.HalfFloatType,                    // linear HDR, like EffectComposer
  samples: 0,   // MSAA: try 4 separately — supported sample counts depend on the depth format
  depthTexture: new THREE.DepthTexture(w, h, THREE.FloatType),  // DEPTH_COMPONENT32F
});

const copy = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({
  uniforms: { map: { value: target.texture } },
  vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }',
  fragmentShader: `uniform sampler2D map; varying vec2 vUv;
    void main() {
      gl_FragColor = texture2D(map, vUv);
      #include <tonemapping_fragment>
      #include <colorspace_fragment>
    }`,
  depthTest: false, depthWrite: false, toneMapped: true
}));
copy.frustumCulled = false;
const copyScene = new THREE.Scene().add(copy);
const copyCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);

renderer.toneMapping = THREE.ACESFilmicToneMapping;
function render() {
  renderer.setRenderTarget(target);
  renderer.render(scene, camera);               // linear, no tone mapping
  renderer.setRenderTarget(null);
  renderer.render(copyScene, copyCamera);       // tone mapping + sRGB, once
}

If you already render through EffectComposer, give its render targets the float depth texture instead of adding another copy. One catch when you compare the two paths: a Color scene.background is a clear colour, written untouched on the canvas but tone-mapped by the copy, so the sky changes colour. Our benchmark draws the sky as a tone-mapped mesh, which both paths treat the same way. With that, the frames matched visually. On the forest at 4K we compared 129,600 sampled points, counting a point as different if any channel differs by more than 24/255. The 24-bit-depth target path differed from the canvas in 6,208 points, all by 1/255 (rounding through the half-float target), and none crossed the threshold. The float-depth reversed-Z target had 2 points over it — the same 2 that reversed-Z on the canvas has, so they come from reversed depth, not from the copy. On time: a half-float target with a 24-bit depth buffer plus the tone-mapping copy took 1.82 ms on the forest at 4K, the same with float depth 1.86 ms, and drawing straight to the canvas 2.09 ms; on the city block 3.37 ms and 3.38 ms against 3.48 ms. In these measurements the whole target path was slightly faster than drawing straight to the canvas, in both passes. We did not time the copy on its own and did not dig into why, so read this as “the target path cost nothing extra here”, not as a speed-up.

polygonOffset has the wrong sign in r180–r182

With reversed depth, “closer” means a larger depth value, so a negative offset pushes a decal away from the camera. three.js r180 passes the material’s offset to WebGL unchanged. Our decal, set up with the usual negative values, disappeared completely: 0% visible at every distance. Flipping the sign brought it back to 100%.

A plain brick wall: the sign is missing entirely
r180, reversedDepthBuffer: true, offset −2/−2: the sign is behind the wall.
The sign drawn cleanly on the wall
The same with +2/+2 — what r183 and later do for you.

From r183 WebGLState.setPolygonOffset negates the factor and units when the depth buffer is reversed, and WebGPURenderer does the same for its depth bias. On r180–r182 flip them yourself, in one place:

// r180–r182 only: three.js does not flip polygonOffset for reversed depth.
const reversed = renderer.capabilities.reversedDepthBuffer;
const OFFSET_SIGN = reversed && Number(THREE.REVISION) < 183 ? 1 : -1;
decal.material.polygonOffsetFactor = 2 * OFFSET_SIGN;
decal.material.polygonOffsetUnits = 2 * OFFSET_SIGN;

What else to check

  • Your own depth code. Shaders that read gl_FragCoord.z or a depth texture and turn it into distance assume 0 = near. With reversed depth, recover view distance directly as near * far / (near + (far - near) * depth). Do not convert with 1.0 - depth first: for distant surfaces depth is tiny, the subtraction rounds to 1.0 in float32 and the precision you switched to reversed-Z for is gone. three.js defines USE_REVERSED_DEPTH_BUFFER in every program so a custom chunk can branch on it.
  • Post-processing. As with the logarithmic buffer, r180’s stock SSAO, SAO, GTAO, SSR and bokeh passes assume standard depth. The three.js issue tracking reversed-depth support (#31998, opened for r180) also lists shadows as partly broken; test shadow bias on your scene before shipping.
  • Browser support. EXT_clip_control is exposed by Chrome and Safari; check current coverage on web3dsurvey and always keep the fallback.
  • WebGPURenderer. It has no reversed depth in r180 (Mugen87 confirms this in the forum); reversedDepthBuffer arrived in r183, and the renderer ignores logarithmicDepthBuffer when both are set.

Saturn’s rings: depth precision, or aliasing?

The Saturn thread is a good example of a symptom that looks like a depth problem and mostly is not. Reading it closely, nobody mentions near, far or z-fighting: the rings are many thin TubeGeometry loops, and the complaint is aliasing on the thinnest ones. We rebuilt the scene at real scale — kilometres, a 58,232 km planet, rings from 74,500 to 136,780 km, the camera 360,000 km out — to separate the two problems.

Problem 1: real-scale depth

Real scale is where precision runs out. A probe 16 m in front of the camera needs near of about a metre (0.001 in kilometre units); Saturn is 360,000 km away. With the default buffer that puts the depth step at Saturn’s distance in the millions of kilometres — larger than the planet. Draw order decides what is in front: the rings show through the planet, and so do the stars.

Saturn with the far half of the rings and stars visible through the planet
Default depth, near = 1 m, far = 10⁶ km: the rings behind the planet and the stars show through it.
Saturn rendered correctly with rings passing behind the planet
Reversed-Z, float depth, same near and far: correct. The logarithmic buffer is also correct here, at its usual cost.

Real-scale space is the textbook case for reversed-Z. Without it, the standard workaround is to give up one shared depth range: draw the far scene (planet, rings, stars) with its own camera and huge near, clear depth, then draw the near scene (probe, cockpit) with a small one — two renderer.render calls with autoClear = false and a clearDepth() between them. That is also what the first-person-weapon case in the prepass thread actually needs: two depth ranges, not a prepass.

Problem 2: thin geometry aliases

The thread’s actual complaint survives every depth fix. A ringlet a few hundred kilometres wide, seen from 360,000 km, is thinner than a pixel. Rasterisation samples it at pixel centres, so it appears in some pixels and not in their neighbours, and dozens of such loops beat against the pixel grid as moiré. MSAA (on in both images below) helps edges, not features smaller than a pixel.

Close-up of rings built from many thin tubes, showing strong moiré patterns
Rings as ~100 thin tube loops (the forum approach): moiré. 3× crop, MSAA on.
Close-up of rings built from one textured ring, smooth bands
One RingGeometry with a radial texture: same ring profile, smooth.

The fix is to move the detail from geometry into a texture, because textures have something geometry does not: mipmaps, which pre-average detail that is too small for the current pixel size. One flat ring, a 1D strip for density and colour, and UVs that run from the inner to the outer radius:

// One ring, all ringlets in a 2048×1 texture (alpha = optical density).
const inner = 74500, outer = 136780;                  // km
const geo = new THREE.RingGeometry(inner, outer, 512, 1);
const pos = geo.attributes.position, uv = geo.attributes.uv;
for (let i = 0; i < pos.count; i++) {
  const r = Math.hypot(pos.getX(i), pos.getY(i));
  uv.setXY(i, (r - inner) / (outer - inner), 0.5);   // u = radius, not planar xy
}
ringTexture.colorSpace = THREE.SRGBColorSpace;
ringTexture.anisotropy = renderer.capabilities.getMaxAnisotropy(); // rings are seen at grazing angles
// mipmaps are generated by default for power-of-two textures

const rings = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
  map: ringTexture, transparent: true, side: THREE.DoubleSide
}));
rings.rotation.x = -Math.PI / 2;

Anisotropic filtering matters more than usual here, because rings are almost always seen at a steep angle and ordinary mipmapping blurs them along the wrong axis. The 16,000 × 16,000 PNG someone in the thread resorted to is unnecessary: the information is one-dimensional, so a 2048-texel strip holds the same ring profile.

Depth prepass: when it pays, and when it does not

A depth prepass draws the opaque scene twice: first depth only, with the cheapest possible shader, then colour with the depth test set so that hidden fragments fail before shading. Expensive shading then runs roughly once per visible pixel instead of once per layer (roughly, because fragments at exactly equal depth also pass LessEqualDepth). With public three.js API it is a few lines — no need for renderer.state, which the code in the forum thread relies on — but there is one trap in r180 that breaks it silently:

const depthOnly = new THREE.MeshBasicMaterial({ colorWrite: false });

// Assumes one material per mesh, FrontSide, no displacement, morphs, skinning or custom
// vertex shaders: anything that changes coverage or depth between the two passes.
const hidden = [];                              // meshes the depth pass must not draw
const wasVisible = new Map();
scene.traverse((o) => {
  if (!o.isMesh) return;
  const m = o.material;
  if (m.transparent || m.alphaTest > 0) { hidden.push(o); return; } // override ignores alpha
  m.depthWrite = false;                         // render state, not shader code: no recompiles
  m.depthFunc = THREE.LessEqualDepth;           // EqualDepth needs bit-exact invariance
});

renderer.autoClear = false;
const sky = scene.background;                   // a THREE.Color
function render() {
  // r180: a Color background makes EVERY render() clear colour and depth, even with
  // autoClear off. Clear once ourselves and keep the background null for both passes.
  scene.background = null;
  renderer.setClearColor(sky, 1);
  renderer.clear();
  for (const o of hidden) { wasVisible.set(o, o.visible); o.visible = false; }
  scene.overrideMaterial = depthOnly;           // pass 1: depth only
  renderer.render(scene, camera);
  scene.overrideMaterial = null;
  for (const o of hidden) o.visible = wasVisible.get(o);   // keep what the app had hidden
  renderer.render(scene, camera);               // pass 2: colour against that depth
  scene.background = sky;
}

The trap is the background. WebGLBackground forces a clear whenever scene.background is a Color, regardless of autoClear, so restoring the sky colour between the passes wipes the prepass depth — and with depthWrite off the colour pass then draws in submission order, last object wins. Our first benchmark run had exactly this bug; we caught it by comparing final images. Every number below is from the corrected version, checked at 4K on a grid of every 8th pixel in both directions (1/64 of the frame, 129,600 samples), with a sample counted as different above 24 of 255 in any channel. Each prepass was compared with the same depth mode without it: on the forest, in random and back-to-front order, default vs prepass and log vs log + prepass matched in every sample; on the city block they differed in 0.18% and 0.16%. Those are the block’s own coincident faces: with LessEqualDepth and depth writes off, equal-depth fragments all pass and the last one drawn wins.

Cutout and transparent meshes are hidden during the first pass because an override material ignores alpha maps: leaves would write solid rectangles into depth. They draw normally in the second pass with their own depthWrite. Multi-material meshes, double-sided materials and anything with a custom vertex stage need their own depth materials (customDepthMaterial-style), or the two passes disagree about what covers a pixel.

Scroll the table sideways for all columns →

SceneDefaultDepth prepassLog depthLog + prepass
Forest, 1080p1.19 ms2.04 ms3.7 ms5.17 ms
Forest, 4K2.09 ms3.08 ms10.5 ms13.2 ms
Forest back-to-front, 4K3.79 ms3.23 ms11.5 ms13.3 ms
City block, 1080p2.27 ms2.52 ms3.79 ms4.42 ms
City block, 4K3.48 ms3.7 ms9.05 ms10.4 ms

On this GPU the result depends on draw order. A working prepass costs about the same whatever the order — 3.2 ms front to back, 3.23 ms back to front on the forest at 4K — because the colour pass shades each pixel about once either way. Without it, a well-sorted forest takes 2.05 ms and the same forest drawn back to front 3.79 ms. So the prepass lost where order was already good (random order, which on a tile-based GPU behaves like sorted: 2.09 ms → 3.08 ms), was slightly slower on the city block at 4K (3.48 ms → 3.7 ms) and won only in the worst order (3.79 ms → 3.23 ms). At 1080p, where shading is cheap, it lost everywhere.

The reason is the hardware. Apple’s tile-based GPUs already remove most hidden opaque fragments per tile before shading — a prepass in silicon, though not a perfect one, as the back-to-front row shows. The software prepass adds a second geometry pass — 1,599,612 triangles transformed twice — and a second set of draw calls, and pays that back only when a lot of shading would otherwise be wasted.

It does not rescue the logarithmic buffer. The colour pass still writes gl_FragDepth, so its fragments are still tested late; log + prepass was the slowest configuration in every row.

Where can a prepass win? On immediate-mode desktop GPUs, with genuinely expensive fragment shaders (many lights, parallax, volumetrics), poorly sorted or self-overlapping geometry, and a vertex load small enough to pay twice. Our forest has a cheap shader (one directional light, a hemisphere light), so the winning case here is modest; with heavier materials the balance moves towards the prepass. We did not have a desktop GPU in this test, so measure it on your target hardware with your shaders, and keep it switchable. The cheaper alternative is to help the sorting three.js already does. It orders opaque objects by material first and by distance only within a material, and it never sorts inside one mesh or one InstancedMesh: splitting a huge mesh into chunks, or sorting instances by distance when the camera moves a lot, gives early-Z something to work with.

Our own data: a geometric z-fight audit of 1,798 models

Everything above is about the camera. In practice most of the z-fighting we have fixed was in the models: two boards sharing a face, a trim strip set 1 mm proud, a window frame flush with its wall. Screenshots are a poor way to find those — whether a fight flickers depends on distance, angle and draw order, and a still frame can hide it. So our pipeline checks geometry instead.

npm run check:zfight builds each model in Node (no renderer), collects its world-space triangles and looks for pairs that could fight from some camera: nearly parallel (within about 1.8°), facing a common side, closer than 3 mm, overlapping by more than 2 cm². It knows enough about materials to rank what it finds: two different materials overlapping is a hard fight; the same material with different UVs or colours is hard or soft depending on how different they look; identical overlapping faces are reported as wasted triangles, not as fights. A pair with different polygonOffset values is exempt — that is the intended decal fix — and a ray test drops overlaps buried inside other geometry, where no camera can see them. What it reports are geometric candidates; whether a given pair visibly flickers still depends on distance, angle and draw order.

The first run over the whole catalogue, on 28.11.2026, built 1,798 models. 749 had at least one candidate pair, and 434 failed the default threshold (more than 0.01 m² of hard fighting). It also found 68,008 overlaps buried inside geometry and 15,730 pairs already handled by an offset. Looking at the worst five fights of every model by gap:

Chart scrolls sideways · full numbers in the table under it →

Fighting area by gap between the faces (worst five fights per model)

  • Area, m²
0 m²400 m²800 m²1200 m²1600 m²2000 m²2400 m²Area, m², 0 (coplanar): 2202 m²0 (coplanar)Area, m², < 0.5 mm: 49 m²< 0.5 mmArea, m², 0.5–1 mm: 54 m²0.5–1 mmArea, m², 1–2 mm: 380 m²1–2 mmArea, m², 2–3 mm: 170 m²2–3 mm
First catalogue-wide check:zfight run, 1,798 models, 2026-11-28. Only the five worst fights per model and test case are kept in the report, so these are the visible problems, not every pair.
All values: fights and area by gap
GapFightsArea
0 (coplanar)7,6642202.4 m²
< 0.5 mm3,26148.5 m²
0.5–1 mm1,49654.3 m²
1–2 mm4,752379.6 m²
2–3 mm2,615170.1 m²

Among those kept fights, 77% of the area came from faces with no gap at all — the case no depth buffer can fix. The rest sat between a fraction of a millimetre and 3 mm: exactly the range that the default buffer stops resolving somewhere between 10 and 50 metres. If we had switched the viewer to a logarithmic buffer or reversed-Z instead of fixing the models, we would have paid for it in frame time and left most of these fights in place. (The share is measured on the largest fights the report keeps per model and test case, not on every pair in the catalogue.)

The rules that came out of fixing them are short, and they all follow from the measurements above:

  • No coplanar overlaps. Inset the hidden face by at least 5 mm, make faces back-to-back, or delete the buried one.
  • Raised detail stands at least 4 mm proud on small props (for the near distances they are seen from), and overlays on buildings 3–5 cm, because buildings are seen from 200 m.
  • Flush detail is a decal: a shared material clone with a distinct polygonOffset; a decal on a decal gets a stronger, distinct level.
  • Small props get stricter thresholds. The default 0.01 m² limit let whole faces of a 20 cm card terminal fight unreported, so the Food pack fails on any fight above 0.2 cm².

The check runs after every geometry change and on whole scenes, between model instances. Our Food pack went from its first wave to 148 models with zero reported fights; the city buildings were the worst offenders in the first run — window reveals and interior cards flush with their facades.

A checklist

  1. Find coplanar faces first. If two faces have no gap, no depth setting helps. Delete, inset or decal them. A geometric check is more reliable than looking at screenshots.
  2. Raise camera.near as far as the camera allows, and fit it per frame if the camera moves between close-up and overview. It is free: ten times the near distance is ten times the precision, everywhere.
  3. Leave far alone unless objects get clipped; it barely affects precision with the default buffer.
  4. Keep details at a distance the buffer can resolve: safe gap ≈ z² / (near · 8.4 M), about two depth steps. With near 0.1: 3 mm holds to ~50 m, 5 cm to ~200 m.
  5. For real ranges, use reversed-Z with a float depth buffer: reversedDepthBuffer: true, a FloatType depth texture where the canvas is not float, flipped polygonOffset on r180–r182, fixed depth-reading shaders.
  6. Or split the range: render far and near scenes with separate cameras and a depth clear between them.
  7. Use logarithmicDepthBuffer last — on WebGPURenderer before r183, or without EXT_clip_control — and budget for it: 5× to 7.2× slower frames on overdraw-heavy scenes in our tests, no polygonOffset, broken depth-reading post-processing.
  8. Measure a depth prepass on your target GPU before adopting it, and compare images, not only timings. On Apple silicon it paid only for badly ordered geometry at 4K.

Frequently asked questions

Why does my model z-fight only from far away?

Because depth precision falls with the square of distance. Two faces 2 mm apart are resolved at 10 m and tie at 100 m with near = 0.1. Raise camera.near first (10× near = 10× precision everywhere), then increase the gap or use polygonOffset. If the faces are exactly coplanar they fight at any distance — that is a modelling problem, not a precision one.

Should I just enable logarithmicDepthBuffer?

Not by default. It writes gl_FragDepth from every material, which disables early depth rejection: on an Apple M5 our test frames were 1.7–5× slower on opaque scenes and 6.6–7.2× slower on alpha-tested foliage. It also makes polygonOffset ineffective and breaks the depth-reading post-processing passes that ship with three.js. Use it when the range is genuinely huge and reversed-Z is unavailable.

Does camera.far matter for z-fighting?

Very little with the default buffer: the depth step at distance z is about z² / (near · 2²⁴), and far only enters through a factor that is close to 1. It does set the scale of the logarithmic buffer, and objects beyond far are clipped. Change near, not far.

Does reversed-Z work with WebGPURenderer?

Not in r180, where WebGPURenderer has no reversed depth and the forum advice was to use the logarithmic buffer. The reversedDepthBuffer option arrived in WebGPURenderer in r183; with both options set, it ignores logarithmicDepthBuffer.

Why did my decals disappear after enabling reversedDepthBuffer?

In three.js r180–r182, polygonOffset is passed to WebGL unchanged, and with reversed depth a negative offset moves a surface away from the camera. Use positive factor and units on those versions; from r183 three.js flips them for you.

Is a depth prepass worth it in three.js?

Measure it. On an Apple M5 a working prepass cost about 3.08 ms per 4K frame on our forest whatever the draw order: slower than the well-sorted scene (2.05 ms), faster than the same scene drawn back to front (3.79 ms), slightly slower on a city block. Tile-based GPUs already remove most hidden opaque fragments before shading, so the gain is smaller than on desktop GPUs with expensive shaders. In r180 make sure a Color scene.background is not set during the passes — it forces a depth clear — and the prepass does not recover the cost of logarithmicDepthBuffer.

Sources

More deep dives

ALL DEEP DIVES →