Introduction

So far, every triangle has gone through the pipeline on its own. But in a real scene many triangles cover the same pixel, such as a wall in front of a mountain, and only the nearest should show. This post covers:

  • Why simply drawing things in order doesn’t work
  • The depth buffer and the depth test, which solve it
  • What’s actually stored in the depth buffer, and why it’s so uneven
  • Z-fighting: the flickering you get when the depth buffer runs out of precision

Drawing in Order Isn’t Enough

The obvious solution is the one painters use: paint the distant background first, then nearer things over the top. This painter’s algorithm works for simple scenes, but sorting thousands of objects by distance every frame takes time. And sometimes there’s no right order at all: when two objects pass through each other, each is partly in front of the other.

The Depth Buffer

The graphics card’s solution is a second image the size of the framebuffer, the depth buffer (or z-buffer). Each of its pixels stores a depth: how far away the surface drawn there is. Before each frame, it’s cleared to the furthest possible value. Then, for every fragment:

  1. Compare the fragment’s depth with the value already in the depth buffer at that pixel (the depth test)
  2. If the fragment is nearer, write its colour to the framebuffer and its depth to the depth buffer
  3. If not, throw it away

Objects can now be drawn in any order, and each pixel shows the nearest surface. In the demo, the ring passes through the box, which no drawing order can handle. Turn the depth test off and change the order, then switch the view to see inside the depth buffer. Drag to look around.

Drawing order, the depth test, and the depth buffer's contents

With the depth test off, whatever is drawn last wins, which looks wrong as soon as you turn the camera. With it on, order doesn’t matter.

Under the hood

Running a fragment shader only to throw its result away is wasteful, so graphics cards do the depth test before the fragment shader whenever they can: the early depth test (or “early z”). Many also keep a low-resolution summary of the depth buffer, to reject whole hidden tiles of a triangle at once. That’s why games often draw nearby objects first: everything behind them then fails cheaply. Early testing is switched off if the fragment shader writes its own depth, and restricted if it can discard fragments, because then the shader decides what the depth buffer ends up holding.

What’s Stored: Depth Isn’t Spread Evenly

The depth buffer doesn’t store the distance directly. It stores the z that comes out of the projection matrix and the divide by w (part 5), squeezed into 0 (the near plane) to 1 (the far plane). Because of the divide, it changes in step with 1 ÷ distance, not with the distance itself.

Switch the demo’s view to Stored depth values: almost everything is very pale, close to 1, though nothing is near the far plane. Distance from the camera shows an even spread for comparison. Most of the range is used up just in front of the camera.

That’s useful: nearby objects, where small errors would show most, get the most precision. But distant objects get very little.

Z-Fighting

A depth buffer usually stores each depth as a 24-bit number: about 16.8 million values between the near and far planes. That sounds like a lot, but they’re bunched up near the camera, so far away the steps between them get large. When two surfaces are closer together than one step, rounding decides which is in front, differently from pixel to pixel and frame to frame, and they flicker through each other: z-fighting.

The demo below shows six pairs of walls, 5, 10, 20, 40, 80 and 160 units away, sized to look the same on screen. In each pair, an orange wall sits a small gap in front of a blue one, so every wall should look orange. The chart compares the smallest gap the depth buffer can resolve at each distance (blue curve) with the actual gap (orange dashed line): where the curve rises above the line, the walls fight. The camera sways slightly so you can watch them flicker (press Pause to stop it). (The demo rounds each depth to what a 16- or 24-bit buffer could store, because some browsers quietly use a more precise one.)

Pairs of walls a tiny gap apart, and the depth buffer’s precision with distance

(The near plane slider is logarithmic: each step of 1 multiplies the distance by ten, so −2 means 0.01 units, 0 means 1 and 1 means 10.)

The near plane matters enormously: moving it from 0.01 to 1 makes distant depth a hundred times more precise, while the far plane barely matters. Hence the advice in part 6 to push the near plane out as far as possible.

How the demo works out the blue curve

For a surface z units from the camera, with the near plane at n and the far plane at f, the value the depth buffer stores is:

stored depth = f ÷ (f − n) × (1 − n ÷ z)

Check the ends: at z = n, the bracket is 1 − 1 = 0, and at z = f it works out to exactly 1. The n ÷ z part is the “1 ÷ distance” from earlier.

A 24-bit buffer stores 2²⁴ different values, so one step is 1 ÷ 2²⁴ of the range (1 ÷ 2¹⁶ for 16 bits). The blue curve is how far apart two surfaces must be for their stored depths to differ by at least one step, which works out as very nearly:

smallest gap ≈ step × (f − n) × z² ÷ (f × n)

The gap grows with z²: twice as far away needs four times the gap. And it’s divided by n: a near plane ten times further out makes everything ten times more precise. The far plane hardly matters, because (f − n) ÷ f is close to 1 when f is much bigger than n. Setting stored depth to 0.5 and solving for z gives the readout’s “half of all the values” distance, 2 × n × f ÷ (f + n): just 0.02 units when n = 0.01.

Other common fixes:

  • Don’t put surfaces almost on top of each other. Decals (pictures stuck onto surfaces, like posters or bullet holes) are a classic cause, and are usually pulled slightly towards the camera with a setting called depth bias.
  • Reverse-Z: store 1 at the near plane and 0 at the far plane, in a 32-bit floating-point depth buffer. Floating-point numbers are most precise near 0, which cancels out most of the bunching; many modern games use it.

Questions You Might Have

Do 2D games need a depth buffer?

Often not: they usually draw sprites back to front by layer, so the order does the job. A depth buffer still helps if solid sprites are drawn in any order.

What's a stencil buffer?

Another per-pixel buffer, usually stored alongside depth (24 bits of depth plus 8 of stencil is common). It holds small whole numbers that later drawing can test against: handy for masks, outlines and portals.

Summary

  • The depth buffer stores the depth of the nearest surface at each pixel, and the depth test keeps only fragments nearer than that.
  • Objects can then be drawn in any order, even when they intersect.
  • Stored depth follows 1 ÷ distance, so precision is concentrated near the camera.
  • When two surfaces are closer than the precision allows, they z-fight. A larger near plane helps most.

Next, the last part of this series puts everything together to light a 3D object: basic lighting.

Further Reading