Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 50 ยท Hidden Surfaces and Drawing 3D Objects

The Z-Buffer Algorithm

Learn how the z-buffer solves hidden surfaces per pixel: the depth buffer, the depth test, depth interpolation, precision and z-fighting, with live demos.

The painter's algorithm decides visibility for whole polygons and breaks when polygons overlap in a cycle or pierce each other. The z-buffer (also called the depth buffer) takes a completely different view: it decides visibility one pixel at a time. For every pixel it remembers how far away the nearest surface drawn so far is. A new surface only gets to color that pixel if it is nearer. No sorting, no splitting, no special cases, and triangles can be drawn in any order.

This idea, from the 1970s, is the visibility method of essentially every GPU today. In this lesson you will build the algorithm, learn how depth is interpolated across a triangle, and see why a 24-bit buffer still produces flickering artifacts called z-fighting.

The algorithm

Keep two arrays of the same size as the screen:

  • the frame buffer (colors), cleared to the background color;
  • the depth buffer (one number per pixel), cleared to the farthest possible value.

Then, for every triangle in the scene, in any order:

TEXT
for each pixel (x, y) covered by the triangle:
    z = depth of the triangle at that pixel
    if z < depth[x, y]:          // nearer than what is stored?
        depth[x, y] = z
        color[x, y] = triangle color at that pixel

That is the whole algorithm. The decision z < depth[x, y] is the depth test. Convention: smaller z means nearer (as in NDC with depth in the range 0 to 1, or -1 to +1 for OpenGL's default). Different APIs may reverse the comparison.

flowchart TD
  A["Clear: color = background,<br/>depth = far (1.0)"] --> B["Next triangle"]
  B --> C["Next covered pixel"]
  C --> D{"z less than<br/>depth stored?"}
  D -->|yes| E["Write depth and color"]
  D -->|no| F["Discard the fragment"]
  E --> G{"More pixels?"}
  F --> G
  G -->|yes| C
  G -->|no| H{"More triangles?"}
  H -->|yes| B
  H -->|no| I["Show the frame"]

Each triangle is rasterized independently; the depth test makes order irrelevant for opaque surfaces.

The cost is memory (a 1920 by 1080 buffer with 32-bit depth takes about 8 MB) and one compare per covered pixel. Both are cheap compared with sorting, and the work parallelizes perfectly, which is why GPUs love it. The cost of drawing grows with the number of pixels covered, including pixels later overwritten by nearer surfaces. That overdraw is the price of the method.

Interpolating depth across a triangle

To compare depths per pixel, we need the triangle's depth at every pixel it covers. We know it only at the three vertices, so we interpolate with the barycentric coordinates of the pixel, as in the triangle rasterization lesson:

TEXT
z = w0 * z0 + w1 * z1 + w2 * z2

Here (w0, w1, w2) are the pixel's weights with respect to the three projected vertices. There is a subtle point. A plane in 3D stays a plane after the perspective divide only if we use the right quantity. Interpolating the view-space z linearly across the screen is wrong, because perspective is not linear in screen space. But the NDC z (after dividing by w) is an affine function of screen position, so linear interpolation of NDC z between the projected vertices gives exactly the right depth at each pixel. (Equivalently, 1/w varies linearly across the screen, which is also the key to perspective-correct texture mapping, covered later.)

That is convenient: the same screen-space barycentric weights you use for color also work for depth.

A z-buffered renderer

The first demo is a complete little renderer written in plain JavaScript, filling a pixel array. The scene has a cube that pokes through a sphere, standing on a ground plane. Cube and sphere intersect, which would defeat the painter's algorithm, yet the intersection curve comes out exactly right. Toggle the depth test off to see the picture drawn in plain triangle order, and switch to the depth view to see the depth buffer itself, with brighter meaning nearer.

A software z-buffer renderer

With the depth test on, the cube and sphere interlock correctly at any angle. With it off, whichever triangle is drawn last wins, and parts of the ground appear on top of the objects.

Precision and z-fighting

A depth buffer has a limited number of bits per pixel, typically 24 or 32. Two surfaces whose true depths differ by less than the buffer's resolution at that distance get the same stored value. The depth test then cannot tell them apart, and which one wins depends on tiny rounding differences that vary from pixel to pixel and from frame to frame. This is z-fighting: a flickering, stripy, noisy mix of the two surfaces. It appears for coplanar polygons (a decal on a wall, a road marking on the road) or for surfaces that are very close.

The root cause, as the projection lesson showed, is that perspective depth is nonlinear: most of the numeric range is spent close to the near plane, and the farther away you look, the coarser the buffer becomes. The smallest distinguishable depth change at distance d is roughly:

TEXT
delta_d  =  d^2 * (f - n) / (f * n * (2^bits - 1))

It grows with the square of the distance. The practical remedies:

  • Move the near plane out as far as the scene allows. Doubling n halves delta_d.
  • Pull the far plane in, though that helps less.
  • Use more bits, or a floating-point depth buffer with reversed-Z (mapping near to 1 and far to 0), which makes the precision far more even.
  • Never place two surfaces in exactly the same plane. Offset a decal slightly, or use the API's polygon offset (depth bias) setting.

The second demo lets you reproduce the problem. A thin gray layer lies a tiny distance gap above a blue road that stretches into the distance, and the depth is quantized to the chosen number of bits at every pixel. The gray layer should win everywhere. Wherever the buffer cannot resolve the gap, the blue shows through. Reduce the bits, lower the near plane, or shrink the gap to see the fighting grow with distance.

Z-fighting with a limited-precision depth buffer

Gray should cover the whole road. Near the bottom, where the road is close to the camera, it does; toward the horizon, blue bands and speckles appear. Raising the near plane to 5 pushes the problem much farther away.

Beyond the basics

A few facts that matter in real engines:

  • Early depth test. GPUs test depth before running the expensive pixel (fragment) program when they can, so hidden pixels cost almost nothing. Drawing opaque objects roughly front to back increases that saving.
  • Transparency. The z-buffer works for opaque surfaces. Blending needs a back-to-front order, so engines draw opaque things first with depth writes, then sort the transparent ones and draw them with depth testing but no depth writing, a mild return to the painter's algorithm.
  • Clearing. The depth buffer must be reset every frame, or last frame's surfaces will hide the new ones.
  • Shadow maps reuse the idea: render the scene's depth from the light's point of view and compare.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the z-buffer store?

    It holds one depth value per pixel; a new fragment is kept only if its depth is nearer than the stored one.
  2. 2. In which order must opaque triangles be drawn for the z-buffer to give a correct image?

    The depth test is evaluated per pixel, so the final result is independent of the drawing order (ties aside).
  3. 3. Which quantity can be interpolated linearly in screen space to obtain the correct depth at each pixel?

    After the perspective divide, z_ndc is an affine function of the screen position, so barycentric interpolation of it is exact. View-space z is not linear in screen space.
  4. 4. What causes z-fighting?

    When both fragments quantize to nearly the same stored depth, the winner varies from pixel to pixel, creating flickering patterns.
  5. 5. Which change most reduces z-fighting in the distance without adding bits?

    Depth resolution at distance d scales with the near value, so increasing near improves precision everywhere, and strongly in the distance.

Summary

  • The z-buffer keeps a depth per pixel and writes a fragment only when it is nearer; no sorting or polygon splitting is needed.
  • Depth is interpolated across a triangle with barycentric weights of the screen-space NDC z, which is exact under perspective.
  • Costs: extra memory, one compare per covered pixel and overdraw; benefits: simplicity, order independence and perfect parallelism.
  • Perspective depth is nonlinear and bits are finite, so surfaces that are close together fight; raise the near plane, add precision (reversed-Z) or offset surfaces.
  • Transparency still needs back-to-front ordering and no depth writes.

You can now draw solid, correctly overlapping 3D objects. The next chapter makes them look real with light: Light and Reflection Models.