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.
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.
- (x, y, z, 1)view space
- × projectionin the vertex shader; copies D into w
- clip spacethe point before the divide
- ÷ wthe perspective divide, done by the GPU
- 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:
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.
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.
| Convention | near → , far → | A | B | depth 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..1 | 1, 0 | n / (f − n) | fn / (f − n) | n (f − D) / (D (f − n)) |
| Reversed, infinite far | 1, 0 (never reached) | 0 | n | n / 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".
Read the standard curve as a bar, and the problem shows: most of the depth range goes to the first few meters.
Try other planes. The bars below use the formulas of the table, cut at the depth of one distance D.
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.
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:
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 D | Standard depth | Smallest step, standard, 32-bit float | Smallest step, standard, 24-bit integer | Reversed depth | Smallest step, reversed, 32-bit float |
|---|---|---|---|---|---|
| 1 | 0.900090 | 6.0 × 10−7 | 6.0 × 10−7 | 0.099910 | 7.5 × 10−8 |
| 10 | 0.990099 | 6.0 × 10−5 | 6.0 × 10−5 | 0.009901 | 9.3 × 10−7 |
| 100 | 0.999100 | 0.006 | 0.006 | 0.000900 | 5.8 × 10−6 |
| 900 | 0.999989 | 0.48 | 0.48 | 0.000011 | 7.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 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.
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:
Projection
Standard: near → 0, far → 1.
Reversed: near → 1, far → 0 (swap n and f).
Depth clear value
Standard: 1 (the far plane).
Reversed: 0 (the far plane).
Depth test
Standard: LESS: nearer is smaller.
Reversed: GREATER: nearer is larger.
- 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.
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 |
A far plane
It clips away distant geometry, and choosing its value is a trade-off with standard depth.
No far plane
The depth falls toward 0 but never reaches it, so nothing is ever clipped by distance.
For frustum culling, the "far plane" of this matrix comes out as (0, 0, 0, n), which every point passes (Frustum culling).
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
Only the third row of the matrix differs. The x, y and w rows are the same.
2. A point at distance 10
Same distance, mirror-image depths: 0.9901 = 1 − 0.0099.
3. How finely each value is stored
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
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.
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.- Also reversed-Z:
getFrustumPlanes(plane 4 is the far plane), occlusion culling (the Hi-Z keeps the minimum, the farthest), and the stats overlay, whose panel sits at depth 1 (the near plane). prepareSceneViewfits the aspect ratio to each target's size; the stored camera does not change.- Depth is a distance from the camera, so a world far from the origin needs nothing more here: the view's matrices are in its camera's render space (large worlds). With an infinite far plane the depth step is about 1.2 · 10−7 of the distance: 12 cm at 1000 km.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Depth convention | standard or reversed | Reversed for every camera kind: toProjectionMatrix in camera.cpp. |
| Far plane | finite or infinite | Infinite 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 matrix | third 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 view | an angle | fovY is in degrees; toProjectionMatrix converts it. |
| Depth format | 32-bit float | D32_SFLOAT (DEPTH_FORMAT), no stencil. Render targets that Renderer::addScenePasses draws into must use it too. |
| Clear value | 0 | 0.0 in VulkanCommandBuffer::beginRendering, for every pass that clears. |
| Depth test | GREATER | VK_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 ratio | update on resize | updateCameraAspectRatio 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
| What | Where |
|---|---|
| Projection settings | CameraProjection in include/rasm/camera.h |
| The matrices | toProjectionMatrix, hasInfiniteFar, setProjectionAspect in src/scene/camera.cpp |
| Checks | isValidProjection in src/scene/camera.cpp |
| Per-pass aspect | Renderer::getProjectionMatrix (with an aspect), called by Renderer::prepareSceneView in src/renderer/gpuScene.cpp |
| Depth textures | DEPTH_FORMAT in include/rasm/renderer.h; created with each render target in src/rhi/renderContext.cpp (the swapchain has none) |
| Clear to 0 | VulkanCommandBuffer::beginRendering in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Compare op | VulkanDevice::createGraphicsPipeline in src/rhi/vulkan/vulkanDevice.cpp |
| glm's 0..1 range | GLM_FORCE_DEPTH_ZERO_TO_ONE in src/CMakeLists.txt |
| Readers of depth | isOccluded 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 |
| Tests | tests/cameraTests.cpp: reversed [1, 0] ranges, the infinite limit, rejected projections |
- 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). Runctest --preset x64-debugafter a camera change.
Further reading
- Nathan Reed, Depth Precision Visualized (2015): the standard explanation of reversed-Z.
- Emil Persson, Creating Vast Game Worlds, SIGGRAPH 2012: reversed depth and an infinite far plane in practice.
- Kurt Akeley and Jonathan Su, Minimum Triangle Separation for Correct Z-Buffer Occlusion, Graphics Hardware 2006.
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: section 4.7, Projections.