Skip to main content

linearizeDepth: Depth Buffer Linearization

Perspective Depth Buffer to Linear Space Conversion

The linearizeDepth function converts non-linear depth buffer values to linear depth coordinates. This transformation corrects the perspective projection's non-uniform depth distribution, providing linear interpolation between near and far clipping planes.

Mathematical Foundation

The linearization formula inverts perspective projection depth encoding:

zlinear=2nff+nd(fn)z_{linear} = \frac{2 \cdot n \cdot f}{f + n - d' \cdot (f - n)}

Where:

  • d=2d1d' = 2d - 1 (depth mapped from [0,1] to [-1,1])
  • nn = near clipping plane distance
  • ff = far clipping plane distance
  • zlinearz_{linear} = linear depth value
Live Editor
const fragment = () => {
      const radialDepth = length(uv.sub(0.5)).mul(2)
      const depth = clamp(radialDepth, 0, 1)
      const near = float(1)
      const far = float(50)
      const linear = linearizeDepth(depth, near, far)
      const color = linear.div(far.sub(near))
      return vec4(color, color.mul(0.5), float(1).sub(color), 1)
}