Drawing

Projection and reversed-Z depth

The projection matrix turns the 3D view into a flat image, and it decides the depth value of every pixel. This page derives the perspective and orthographic matrices, explains why the usual depth mapping loses precision far away, and shows how reversed-Z fixes it. The last part shows how RASM does it.

In short

  • Perspective divides by the distance. A matrix cannot divide, so it copies the distance into w, and the GPU divides by w after the vertex shader.
  • The depth after the divide is a + b / distance: linear in 1/distance, not in distance. Most of the depth range goes to the first few meters.
  • With the usual mapping (near → 0, far → 1), far objects get values close to 1, where floats are coarse. Surfaces far away z-fight.
  • Reversed-Z maps near → 1 and far → 0. Floats are dense near 0, which balances the 1/distance crowding. With a 32-bit float depth buffer, precision becomes about equal at every distance.
  • Reversed-Z needs three changes together: the projection, a depth clear of 0, and a greater depth test.
  • An infinite far plane costs almost nothing with reversed-Z: depth = near / distance.

1Perspective: divide by the distance

A pinhole camera sees a point at height y and distance D in front of it at the image height y / D (similar triangles). Twice as far means half as big. In view space the camera looks down −Z, so D = −z.

−Z A B y y fovY/2 eye near plane at distance 1 distance D = −z distance 2D far A, at distance D: image height y / D B, twice as far: image height y / 2D, half as big
The vertical field of view fovY fixes how much of the scene fits on screen from top to bottom. The width follows from the aspect ratio.

y_image = y / D

focal = 1 / tan(fovY / 2)

y_ndc = focal · y / D

x_ndc = focal / aspect · x / D

y / D
similar triangles
focal
The view reaches tan(fovY/2) on the plane at distance 1. focal scales that to 1 for NDC.
aspect
width / height. Dividing x by it keeps square things square on a wide screen.

x not divided by aspect

NDC is a square stretched over a wide screen, so a square object looks wide.

x divided by aspect

Square things stay square.

2Why the 4th coordinate: w

A matrix can only multiply and add. It cannot divide by D. So the projection matrix puts D into a fourth coordinate, w, and the GPU divides x, y and z by it later. This is the perspective divide.

  1. (x, y, z, 1)view space
  2. × projectionin the vertex shader; copies D into w
  3. clip spacethe point before the divide
  4. ÷ wthe perspective divide, done by the GPU
  5. NDCthe point after the divide

See Coordinate spaces for the spaces themselves.

| x_c |   | focal/aspect   0     0   0 |   | x |
| y_c | = |      0       focal   0   0 | · | y |
| z_c |   |      0         0     A   B |   | z |
| w_c |   |      0         0    −1   0 |   | 1 |

w_c = −z = D        then   NDC = (x_c, y_c, z_c) / w_c

Keeping w until after the vertex shader has two more uses:

screen behind the camera: w < 0 flips here

Clipping

It happens before the divide, against −w ≤ x, y ≤ w. A point behind the camera has w < 0; after a divide it would flip to the other side of the screen.

linear on screen with ÷ w

Perspective-correct interpolation

Texture coordinates and colors are not linear across a triangle on screen. The GPU interpolates value/w and 1/w, which are linear on screen, and divides.

3The depth row

The third row, (0, 0, A, B), makes the depth. After the divide:

depth = z_c / w_c = (A · z + B) / D = −A + B / D        (z = −D)

So depth is a straight line in 1/D, not in D. That is on purpose: 1/D is linear across a triangle on screen, so the GPU can interpolate depth with no divide per pixel, and compress depth tiles well. Two conditions fix A and B: the depth at the near plane n and at the far plane f.

Conventionnear → , far →ABdepth at distance D
OpenGL−1, +1−(f + n) / (f − n)−2fn / (f − n)(f + n − 2fn/D) / (f − n)
Standard 0..1 (Direct3D, Vulkan, Metal)0, 1−f / (f − n)−fn / (f − n)f (D − n) / (D (f − n))
Reversed 0..11, 0n / (f − n)fn / (f − n)n (f − D) / (D (f − n))
Reversed, infinite far1, 0 (never reached)0nn / D

The reversed row is the standard row with n and f swapped. So any library that builds a standard 0..1 matrix builds a reversed one when you pass the far distance as "near" and the near distance as "far".

1 0.5 0 0.1 1 10 100 1000 distance D (log scale), near 0.1, far 1000 depth standard: 1 → 0.900 10 → 0.990, then 0.999, 1.0 reversed: 1 → 0.100 10 → 0.010, then 0.001, 0
On paper the two curves are mirror images and carry the same information. The difference appears only when the numbers are stored in a float (next section).

Read the standard curve as a bar, and the problem shows: most of the depth range goes to the first few meters.

standard depth, near 0.1, far 1000: the distances that each part of the range 0..1 holds D = 0.1 to 0.2 half of the range D = 0.2 to 1 40% 1 to 10 0 0.5 0.9 0.99 1 D = 10 to 1000: the last 1% of the range depth →
Everything farther than 100 times the near plane shares one hundredth of the range.

Try other planes. The bars below use the formulas of the table, cut at the depth of one distance D.

the part of the depth range for near to D the part for D to far the distance D
Move the far plane: almost nothing changes. Then move the near plane from 0.1 out to 1: the part for everything past D grows ten times.

4Orthographic projection

An orthographic camera has no perspective: parallel lines stay parallel and size does not change with distance. The view volume is a box (left, right, bottom, top, near, far), and the matrix only scales and moves it onto the NDC box. w stays 1, so depth is linear in distance.

Perspective: a frustum on screen far things are smaller w = distance Orthographic: a box on screen same size at any distance w = 1
Orthographic views are used for CAD and map views, 2D and UI, and shadow maps of directional lights.
x_ndc = (2x − (r + l)) / (r − l)
y_ndc = (2y − (t + b)) / (t − b)
depth = (D − n) / (f − n)       standard 0..1
depth = (f − D) / (f − n)       reversed: again, swap n and f

5Why depth precision is poor far away

A 32-bit float stores a number as 1.m × 2e, with 23 bits for m. So there are 223 floats between 0.5 and 1, another 223 between 0.25 and 0.5, another between 0.125 and 0.25, and so on. Floats are dense near 0 and coarse near 1: the gap between neighbors just below 1 is 2−24 ≈ 6 × 10−8, while near 0.001 it is about 10−10.

Now put the standard depth curve on this number line. Every distance past a few times the near plane maps into the last band, [0.5, 1), and most of them into its very top end:

Floats between 2⁻¹⁴ and 1, one band per power of two (log scale) 2⁻¹⁴ 2⁻⁸ 2⁻² 0.5 1 each band holds 2²³ = 8,388,608 floats standard D = 1, 10, 100, 1000 all here: 0.9 … 1.0 reversed D = 1: 0.1 D = 10: 0.01 D = 100: 0.001 D = 1000: 0.0001 Near 0.1. Reversed uses the infinite form, depth = 0.1 / D: each 10× in distance moves 3.3 bands.
Standard depth packs the whole scene into one band of floats. Reversed depth spreads it over many bands, each with 8 million values.

Two surfaces whose depths round to the same float cannot be ordered: the depth test picks one at random per pixel, and the picture flickers in stripes. This is z-fighting. The smallest distance step the buffer can tell apart is the float gap divided by how fast depth changes with distance:

step(D) ≈ gap(depth(D)) / |d depth / dD|        with  |d depth / dD| ≈ n / D²  (both forms)
Distance DStandard depthSmallest step, standard, 32-bit floatSmallest step, standard, 24-bit integerReversed depthSmallest step, reversed, 32-bit float
10.9000906.0 × 10−76.0 × 10−70.0999107.5 × 10−8
100.9900996.0 × 10−56.0 × 10−50.0099019.3 × 10−7
1000.9991000.0060.0060.0009005.8 × 10−6
9000.9999890.480.480.0000117.4 × 10−6

Near 0.1, far 1000, in scene units (say meters).

Standard depth

A wall at 900 m cannot be told apart from a poster 30 cm in front of it.

Reversed-Z

The step stays below 0.01 mm everywhere.

Try it with real floats. The picture computes both depths of two close surfaces, rounds them to 32 bits, and counts the floats between them. The far plane is at 1000.

a float that holds one surface a float that holds both: z-fighting standard depth reversed depth
Bring the surfaces closer to the camera until standard depth can tell them apart. Go back to 900, and move the near plane out instead. Then try to make reversed depth fail.
32-bit float 24-bit integer 0 0.5 1 the same gaps: 2⁻²⁴

A float buffer alone does not help

Standard depth in a 32-bit float buffer is no better than a 24-bit integer buffer: near 1, floats have the same 2−24 spacing as the integers. The gain comes only from reversed depth and a float buffer together.

step size at one distance, standard depth near plane at 0.01 near plane at 0.1 10 times smaller

The near plane matters most

With standard depth, the step size is about D² / n × 6 × 10−8. Moving the near plane from 0.01 to 0.1 makes every step 10 times smaller. With reversed-Z, the near plane hardly matters.

6Reversed-Z

Reversed-Z maps the near plane to depth 1 and the far plane to 0. The 1/D curve crowds far distances toward 0, and floats are densest near 0. The two effects roughly cancel: the step size becomes about D × 10−7, a constant relative precision, at every distance.

It is not one change but three, and all three must change together:

near → 1 far → 0

Projection

Standard: near → 0, far → 1.

Reversed: near → 1, far → 0 (swap n and f).

000000000000

Depth clear value

Standard: 1 (the far plane).

Reversed: 0 (the far plane).

0.4 0.1 0.4 > 0.1: the nearer one wins

Depth test

Standard: LESS: nearer is smaller.

Reversed: GREATER: nearer is larger.

Two more conditions, or there is no gain
  • Depth format. For standard depth a 24-bit integer is enough. Reversed needs a 32-bit float.
  • Clip depth range. Standard works with 0..1 or −1..1. Reversed needs 0..1. With OpenGL's −1..1, far values sit near −1, where floats are coarse, and the gain is lost; OpenGL needs glClipControl.
near far 1.0 the near plane 0.4 new fragment 0.1 stored, a farther surface 0.0 clear value, far plane, empty sky 0.4 > 0.1 passes: the fragment is drawn and writes 0.4 0.1 > 0.4 fails: hidden behind, discarded Nearer means larger. An empty pixel holds 0, so any visible fragment passes over it.
Everything that reads or writes depth by hand follows the same flip: "the farthest depth" in a tile is now the minimum, a sky written at the far plane uses depth 0, and a depth bias pushes the other way.

7The infinite far plane

With reversed-Z there is little reason to have a far plane. Let f go to infinity in the reversed row: A → 0 and B → n.

| focal/aspect   0     0   0 |
|      0       focal   0   0 |          depth = n / D
|      0         0     0   n |
|      0         0    −1   0 |
clipped far

A far plane

It clips away distant geometry, and choosing its value is a trade-off with standard depth.

drawn

No far plane

The depth falls toward 0 but never reaches it, so nothing is ever clipped by distance.

n / Dthe depth at distance D
D × 7 × 10−8the step size, about, at every distance
0.07 mmstep at 1 kmn = 0.1
0.9 mmstep at 10 kmn = 0.1

For frustum culling, the "far plane" of this matrix comes out as (0, 0, 0, n), which every point passes (Frustum culling).

Only with reversed-Z

The same limit with standard depth gives depth = 1 − n / D: the whole scene squeezed against 1, the worst case of section 5.

8Worked example

Near 0.1, far 1000, a 32-bit float depth buffer. Follow a surface at distance 10, then ask whether a second surface right behind it can be told apart.

1. The depth rows

00AB the projection matrix standard 0..1 A = −f / (f − n) = −1.0001 B = −fn / (f − n) = −0.10001 reversed 0..1 A = n / (f − n) = 0.00010001 B = fn / (f − n) = 0.10001 Reversed: the same formulas as standard with n and f swapped, and the signs follow.

Only the third row of the matrix differs. The x, y and w rows are the same.

2. A point at distance 10

z = −10 → w_c = 10 standard: z_c = −1.0001 · (−10) − 0.10001 = 9.901 depth = 9.901 / 10 = 0.9901 reversed: z_c = 0.00010001 · (−10) + 0.10001 = 0.0990 depth = 0.0099 0 1 depth reversed: 0.0099 standard: 0.9901

Same distance, mirror-image depths: 0.9901 = 1 − 0.0099.

3. How finely each value is stored

0.9901: float gap 6.0e−8 → distance step 6.0e−5 (0.06 mm) 0.0099: float gap 9.3e−10 → distance step 9.3e−7 (0.001 mm) floats near 0.99 one gap: 6.0e−8 floats near 0.0099 64 gaps of 9.3e−10 in each gap above Distance step = float gap / (n / D²) = gap · 1000. Both are fine at distance 10.

At short range both work. The difference grows with distance, as the table in section 5 shows.

4. Two surfaces 30 cm apart, 900 away

standard: 900 → 0.99998891 900.3 → 0.99998891 same float: z-fighting reversed: 900 → 1.1112e−5 900.3 → 1.1075e−5 different: the nearer wins standard 900 and 900.3: one float reversed 900.3 900 about 40,000 float steps apart Rounded to 32-bit floats.

With standard depth, the farther surface shows through in stripes that move with the camera.

9Pitfalls

Nothing is drawn
Reversed projection with the old clear (1) or the old test (LESS). The three settings must change together.
Everything is drawn in the wrong order
Reversed clear and test, but a standard projection.
Far surfaces flicker in stripes
Standard depth with a small near plane. Move the near plane out, or use reversed-Z with a float buffer.
No gain from reversed-Z
A 24-bit integer buffer, or OpenGL's −1..1 clip range.
Objects stretched on a wide window
The aspect ratio is not updated when the window or the render target changes size.
Linear depth from the buffer is wrong
The inverse formula of the other convention. For reversed infinite: D = n / depth.
Shadows get acne or peter-panning after the switch
Depth bias still pushes toward larger depth.

10In RASM

RASM uses reversed-Z everywhere, with a 32-bit float depth buffer, a 0..1 clip range, and by default an infinite far plane. The three settings of section 6 are fixed for every pass and every pipeline.

CameraProjection fovY in degrees toProjectionMatrix one of three matrices ORTHOGRAPHIC glm::ortho far, near swapped · linear PERSPECTIVE, finite farZ glm::perspective far, near swapped · 1 → 0 farZ = 0 or infinity written by hand depth = nearZ / D SceneData projection vertMain D32_SFLOAT clear 0 ≥ passes
glm builds standard 0..1 matrices because GLM_FORCE_DEPTH_ZERO_TO_ONE is set in CMake (B2). Passing far as glm's near and near as glm's far reverses them, as in section 3.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Depth conventionstandard or reversedReversed for every camera kind: toProjectionMatrix in camera.cpp.
Far planefinite or infiniteInfinite when farZ is 0 or infinity (hasInfiniteFar). A designated initializer that leaves out farZ gives 0, so the examples get an infinite far plane. Orthographic cameras have no infinite form.
Infinite matrixthird row = (0, 0, 0, n)The same, written by hand because glm has no reversed infinite matrix: m[2][3] = -1, m[3][2] = nearZ (glm indexes column first).
Field of viewan anglefovY is in degrees; toProjectionMatrix converts it.
Depth format32-bit floatD32_SFLOAT (DEPTH_FORMAT), no stencil. Render targets that Renderer::addScenePasses draws into must use it too.
Clear value00.0 in VulkanCommandBuffer::beginRendering, for every pass that clears.
Depth testGREATERVK_COMPARE_OP_GREATER_OR_EQUAL in createGraphicsPipeline, for every graphics pipeline with a depth format. Equal depths pass. PipelineDesc::depthTest and depthWrite are on by default; the see-through draws write no depth, and the culling debug view's boxes test none (debug views).
Validation—isValidProjection refuses a perspective nearZ that is not finite and > 0, a finite farZ not > nearZ, and an orthographic camera without finite nearZ < farZ. NaN fails every check. createCamera then returns an invalid handle; setCameraProjection keeps the old projection.
Jitter—With TAA, writeViewMotion adds a sub-pixel offset to the view's projection, a translation of clip x and y. Depth does not change.
Aspect ratioupdate on resizeupdateCameraAspectRatio runs after the swapchain is (re)created. Renderer::prepareSceneView also fits a copy to each scene view's target size with getProjectionMatrix(camera, aspect). An orthographic camera keeps its center and width; its height becomes width / aspect.
Depth bias, depth clamp—Neither is used. The shadow pass biases in the shader instead (Shadow mapping).

Where it lives in code

WhatWhere
Projection settingsCameraProjection in include/rasm/camera.h
The matricestoProjectionMatrix, hasInfiniteFar, setProjectionAspect in src/scene/camera.cpp
ChecksisValidProjection in src/scene/camera.cpp
Per-pass aspectRenderer::getProjectionMatrix (with an aspect), called by Renderer::prepareSceneView in src/renderer/gpuScene.cpp
Depth texturesDEPTH_FORMAT in include/rasm/renderer.h; created with each render target in src/rhi/renderContext.cpp (the swapchain has none)
Clear to 0VulkanCommandBuffer::beginRendering in src/rhi/vulkan/vulkanCommandBuffer.cpp
Compare opVulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp
glm's 0..1 rangeGLM_FORCE_DEPTH_ZERO_TO_ONE in src/CMakeLists.txt
Readers of depthisOccluded in shaders/lib/occlusionCulling.slang; vertMain in shaders/passes/statsOverlay.slang; getViewDepth in shaders/passes/inspect.slang, which turns a reversed-Z depth back into view depth for the Buffers section
Teststests/cameraTests.cpp: reversed [1, 0] ranges, the infinite limit, rejected projections
Keep these true
  • The projection, the clear value (0) and the compare op (GREATER_OR_EQUAL) are one decision. Change one, change all three.
  • A pass that writes its own depth follows reversed-Z: near is 1, far is 0. A sky at the far plane writes 0.
  • Code that reduces depth, like the Hi-Z build in hiz.slang, keeps the minimum as the farthest value.
  • Do not normalize the frustum plane with a zero-length normal: it is the infinite far plane (Frustum culling).
  • glm config macros stay in CMake (B2). Run ctest --preset x64-debug after a camera change.

Further reading