Culling and the frame
Frustum culling
Frustum culling skips the objects that are outside the camera's view, before the GPU does any work for them. It needs three things: the six planes that bound the view, a simple shape around each object, and a test of one against the other. This page explains each part. The last part shows how RASM does it.
In short
- The camera sees a frustum: a pyramid with its top cut off, bounded by 6 planes (near, far, left, right, top, bottom).
- A plane gives every point a signed distance: positive inside, negative outside.
- Each object gets a bounding volume, usually a sphere or a box. Testing it is much cheaper than testing triangles.
- A sphere is outside when its center is more than one radius behind any one plane. If it passes all 6, it is kept.
- The 6 planes come straight from the rows of the view-projection matrix (Gribb and Hartmann).
- The test is conservative: it may keep an object that is not visible, but it never removes one that is.
1Why cull at all
The GPU already throws away triangles outside the view. It does this in clipping, after the vertex shader. So an object behind the camera never shows up on screen, even without culling. But by then the GPU has already done work for it:
No culling
The GPU reads the object's vertices, runs the vertex shader on each one and builds its triangles. Clipping then drops every triangle. No pixels: all of that is wasted.
Frustum culling
One test per object removes it before the draw. The vertex shader, clipping and pixels are all skipped. One test replaces thousands of vertex shader runs.
Culling works on whole objects. It saves the work that clipping would throw away later.
This also tells us the one rule of culling. It is only a way to save time: the GPU would get the same image without it. So a culling test may make one kind of mistake, and never the other:
May keep an invisible object
That only costs a little time.
Must never remove a visible object
That would make it vanish from the screen.
A test with this property is called conservative.
2The view frustum
A perspective camera sees everything inside a pyramid that starts at the eye. The pyramid is cut off twice: at the near plane, close to the eye, and at the far plane, far away. What is left is called a frustum. It has 6 faces, and each face lies on a plane.
A point is inside the frustum when it is on the inner side of all 6 planes. So to work with the frustum, we first need a way to ask "which side of this plane is this point on?".
3A plane, and the distance to it
A plane is stored as 4 numbers: a normal n = (a, b, c), the direction the plane faces, and an offset d. A point p is on the plane when n · p + d = 0. For any other point, the same expression gives a number that is not zero, and its sign tells the side.
distance(p) = n · p + d
- > 0
- p is on the side n points to
- = 0
- p is on the plane
- < 0
- p is on the other side
When n has length 1, the number is the real distance, in the same units as p. To get there, divide all 4 numbers (a, b, c, d) by the length of (a, b, c).
For a single point, only the sign matters, so the length of n does not matter either. For a sphere it does: we will compare the distance with the radius, so both must be in the same units. That is why frustum planes are almost always normalized: scaled so that n has length 1.
4Bounding volumes
A mesh can have millions of triangles. Testing each one against the frustum would cost more than drawing them. Instead, every object gets a simple shape that fully contains it, a bounding volume. If the bounding volume is outside, the object inside it is outside too.
Spheres are the most common choice for frustum culling. They are small, they do not change when the object rotates, and the test is one line. Boxes are a good second choice (see below).
How to build a bounding sphere
The sphere is built once, when the mesh is loaded, from its vertex positions. The smallest possible sphere is not needed; any sphere that contains every vertex is correct.
Box center
Find the min and max of all positions. The center is halfway between them. The radius is the distance to the farthest vertex.
Two passes over the vertices. A bit bigger than needed, simple.
Ritter's method
Start with a sphere through two far-apart points. Walk the vertices; when one is outside, grow the sphere just enough to hold it.
Two or three passes. Usually close to the smallest sphere.
Welzl's algorithm
A randomized recursive algorithm that finds the exact smallest sphere.
The smallest sphere. More code, and slower in practice.
5The test: a sphere against the frustum
Take a sphere with center c and radius r, and one plane. Compute the signed distance of the center, s = n · c + d. There are three cases:
| Distance of the center | Meaning | For culling |
|---|---|---|
| s ≥ r | the whole sphere is inside this plane | keep testing the other planes |
| −r ≤ s < r | the sphere crosses the plane | keep testing the other planes |
| s < −r | the whole sphere is outside this plane | cull, stop: no other plane can bring it back |
For the whole frustum, run this for all 6 planes. One "fully outside" is enough to cull. The sphere is kept only when no plane rejects it:
bool sphereInFrustum(float4 planes[6], float3 center, float radius)
{
for (int i = 0; i < 6; ++i)
{
if (dot(planes[i].xyz, center) + planes[i].w < -radius)
return false;
}
return true;
}
The picture below runs this test from above, with 4 of the 6 planes (left, right, near, far). Turn the camera and move the big sphere across an edge of the frustum.
That is 6 dot products and 6 compares per object. Each plane is stored as a float4: the normal in xyz, d in w.
6Where the planes come from
One way to get the planes is geometry: take the camera's position, direction, field of view and aspect ratio, build the 8 corners of the frustum, and make a plane from three corners of each face. It works, but it is a lot of code and easy to get wrong. There is a shorter way that needs only the matrix the camera already has.
The idea: the frustum is a box in clip space
The view matrix V moves the world into the camera's space. The projection matrix P then moves it into clip space. A point p = (x, y, z, 1) becomes q = P · V · p = (qx, qy, qz, qw). The projection is built so that the frustum becomes a simple box there. A point is visible when (with the depth range of Vulkan and Direct3D)
−qw ≤ qx ≤ qw −qw ≤ qy ≤ qw 0 ≤ qz ≤ qw
r0 … r3 are the four rows of M = P · V.From an inequality to a plane
Call the rows of M = P · V r0 to r3. Each part of q is one row times the point: qx = r0 · p and qw = r3 · p. Now take the left side of the box:
−qw ≤ qx
⇔ 0 ≤ qw + qx
⇔ 0 ≤ r3·p + r0·p
⇔ 0 ≤ (r3 + r0)·p
The last line is exactly "p is on the inner side of a plane", with the plane's 4 numbers equal to r3 + r0. No angles, no corners: just add two rows. This trick was published by Gil Gribb and Klaus Hartmann in 2001, and almost every engine uses it. Each side of the box gives one plane:
| Plane | Clip-space side | Plane = |
|---|---|---|
| Left | qx ≥ −qw | r3 + r0 |
| Right | qx ≤ qw | r3 − r0 |
| Bottom, top | qy ≥ −qw, qy ≤ qw | r3 + r1, r3 − r1 (which one is "top" depends on the API's y direction; Vulkan's points down) |
| Near, far | depend on the depth range, see the next table | |
Near and far depend on the depth convention
| Depth convention | Clip-space range | Near plane | Far plane |
|---|---|---|---|
| OpenGL | −qw ≤ qz ≤ qw | r3 + r2 | r3 − r2 |
| Vulkan, Direct3D, Metal | 0 ≤ qz ≤ qw, near at 0 | r2 | r3 − r2 |
| Reversed-Z (0 to 1 range) | 0 ≤ qz ≤ qw, near at qw | r3 − r2 | r2 |
The two inequalities are the same in the last two rows; only their names swap. The code that builds the planes can stay the same. Only the names "near" and "far" change.
An infinite far plane
Some projections have no far plane: the depth only gets closer to its far value and never reaches it. Then the far plane comes out as (0, 0, 0, k) with k > 0. It has no direction, and every point gets the distance k, so every sphere passes it. That is correct: nothing is beyond infinity. Do not divide this plane by the length of its normal, which is 0.
Which space the planes are in
The planes are in the space that the matrix starts from. Use P alone and they are in view space. Use P · V and they are in world space, which is the usual choice. Use P · V · W (with one object's world matrix W) and they are in that object's own space.
void extractPlanes(const glm::mat4 &viewProjection, glm::vec4 planes[6])
{
// glm stores columns: transpose to get the rows.
const glm::mat4 rows = glm::transpose(viewProjection);
planes[0] = rows[3] + rows[0];
planes[1] = rows[3] - rows[0];
planes[2] = rows[3] + rows[1];
planes[3] = rows[3] - rows[1];
planes[4] = rows[2];
planes[5] = rows[3] - rows[2];
for (int i = 0; i < 6; ++i)
{
const float length = glm::length(glm::vec3(planes[i]));
if (length > 0.0f)
planes[i] /= length;
}
}
Left, right, bottom, top, then the two depth planes for a 0 to qw depth range. A plane with no direction (an infinite far plane) is left as it is.
7Worked example
A small case you can check by hand. The camera sits at the origin and looks down −Z, with a 90° field of view and the near plane at distance 1. With 90°, the side planes are at 45°, so their normals are (±0.707, 0, −0.707). Four spheres, each with radius 1:
| Sphere | Center | Near (0, 0, −1, −1) | Left (0.707, 0, −0.707, 0) | Right (−0.707, 0, −0.707, 0) | Result |
|---|---|---|---|---|---|
| A | (0, 0, −5) | 4.00 | 3.54 | 3.54 | keep: inside all |
| B | (3.5, 0, −3) | 2.00 | 4.60 | −0.35 | keep: −0.35 ≥ −1, it crosses the right plane |
| C | (6, 0, −3) | 2.00 | 6.36 | −2.12 | cull: −2.12 < −1, fully right of the view |
| D | (−2, 0, 1) | −2.00 | −2.12 | 0.71 | cull: behind the near plane (the test stops there) |
For example, C against the right plane: −0.707 · 6 + (−0.707) · (−3) + 0 = −4.24 + 2.12 = −2.12.
8Moving the sphere into world space
The sphere is built in the mesh's own space. The planes are in world space. So each frame, the sphere is moved with the object's world matrix W. The center is easy: it is a point, so it is W · (c, 1). The radius is harder, because W can scale the object.
The exact largest stretch of a matrix is its largest singular value. Computing that is too slow for every object every frame, so engines use a cheap number that is never smaller than it:
| Way to get the stretch | Cost | Correct? |
|---|---|---|
| Longest column of the 3×3 part of W | 3 dot products | Exact for rotate + scale. Can be too small when the matrix also has shear, for example a child rotated under a parent with a non-uniform scale. |
| Frobenius norm: the square root of the sum of all 9 entries squared | 9 multiplies | Always safe, but up to 1.73 (√3) times too big. |
| Gershgorin bound on WTW: take the dot products of the columns, and the largest row sum of their absolute values | 6 dot products | Always safe. Exact for rotate + scale, because then the columns are at right angles and the off-diagonal products are 0. |
9Boxes instead of spheres
A box is tested almost the same way as a sphere. Store the box as a center c and a half-size e (half its width, height and depth). For one plane, the part of the box that reaches furthest towards the plane is a corner. How far that corner reaches depends on the plane's direction, so the box acts like a sphere whose radius changes per plane:
s = n · c + d
r = e.x · |n.x| + e.y · |n.y| + e.z · |n.z|
s < −r → cull
- s
- the signed distance of the box's center, as for a sphere
- r
- how far the box reaches along n: the distance from c to the corner farthest along n (the "p-vertex")
It is the same test as the sphere, with a radius that depends on the plane.
Boxes have one more nice property. The test only needs the sign of the corner's distance, not its size. So the planes do not need to be normalized, and they can be moved into the object's own space instead of moving the box into world space: a plane π becomes WT · π. The box then stays exact under any rotation and scale, with no stretch bound.
10The corner problem: false positives
The test asks one plane at a time: "is the sphere fully behind this plane?". Near a corner of the frustum, a sphere can be outside the frustum and still cross each plane on its own. Then no plane rejects it, and it is kept.
False positives happen most for big objects and near sharp corners. Most engines accept them. When they matter, there are two fixes:
Test the other way round
Also check the frustum's 8 corners against the object's box. If all 8 are outside one face of the box, the box is outside.
A second, cheap test
Separating-axis test
A full test of the two shapes against each other. It is exact.
Costs much more
11Fewer tests: hierarchies, and the GPU
The test is cheap, but a big scene has many objects. There are two common ways to keep the total cost low.
Test groups first
Put objects into a tree: a scene graph, an octree, or a bounding volume hierarchy (BVH). Each node has a bounding volume around all its children. Test the node first:
A related trick is the plane mask. If a node is fully inside, say, the left plane, all its children are too. So the node passes down a mask of the planes still worth testing, and its children skip the others.
Test everything at once on the GPU
A GPU can run the flat test for every object in parallel, one thread per object. For tens of thousands of objects this takes a fraction of a millisecond, often less than walking a tree on the CPU. The tree tricks matter less there, because the GPU does not branch well and wants the same work on every thread. The hard part on the GPU is what comes next: packing the kept objects into a list that a single indirect draw can read. That is stream compaction, which has its own guide.
Other views use the same code
Shadow maps, reflections and split screens each have their own camera, so each gets its own 6 planes and its own culling. Nothing else changes.
12In RASM
RASM frustum-culls every draw (one sub-mesh of one entity) on the GPU, every frame, in the Cull pass that Renderer::addScenePasses adds for each scene view (a scene, a camera and a target). It uses the plain sphere test from section 5, with planes taken from the matrix as in section 6.
Renderer::prepareSceneView), and the test runs once per draw.A skinned mesh changes shape, so its sphere from the load does not hold its posed vertices. For a playing skinned sub-mesh, the Animate pass writes a sphere in its InstanceTransform each frame (boundsCenter, boundsRadius): the sphere around its joints' spheres, each moved by its joint matrix. getWorldSphere takes that one when boundsRadius is not negative, so every view culls the posed mesh (Skinning).
A morphed mesh changes shape too. A morph target t with weight wₜ moves a vertex by at most |wₜ| · rₜ, where rₜ is the target's longest position delta (AnimationMeshData::morphRadii, from the load). The moves add up, so the Animate pass grows the radius by their sum (getMorphGrowth).
Animate pass writes this frame. A weight of 0 adds nothing, so a mesh at rest weights 0 keeps its own sphere.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Bounding volume | sphere or box | A sphere per sub-mesh only (boundsCenter, boundsRadius). No boxes, so no p-vertex test. A posed skinned or morphed sub-mesh uses the sphere the Animate pass writes from its joints and its weights (above). |
| Building the sphere | box center, Ritter or Welzl | Box center, radius to the farthest vertex (computeBounds). Not the smallest sphere. |
| Planes | Gribb–Hartmann rows | The same, from projection * view, in the view's render space (the world moved so that the camera is at the origin, large worlds), normalized (getFrustumPlanes). |
| Depth convention | see the table in section 6 | Vulkan's 0 to qw range with reversed-Z. So plane 4 (r2) is the far plane and plane 5 (r3 − r2) is the near plane. See Projection and reversed-Z depth. |
| Infinite far plane | (0, 0, 0, k) | The default camera has one. Plane 4 comes out as (0, 0, 0, nearZ), is not normalized, and every sphere passes it. |
| Radius under scale | three ways in section 8 | The Gershgorin bound (getWorldSphere). Safe for any matrix, exact for rotate + scale. |
| Hierarchy, plane masks | section 11 | None. Every draw is tested against all 6 planes, flat, one GPU thread each. |
| Corner false positives | accept, or add a second test | Accepted. Many of them are then removed by occlusion culling, which runs the frustum test first. |
| Planes per view | one set per camera | One set per scene view, in that view's SceneData slot. Two cameras are two views, and cull separately. |
| Seeing the test | – | Renderer::setCullingFrozen keeps a shaded view's planes (and its LOD camera) of the frame it froze in, while the camera moves on; shadow views keep following the camera. The culling debug view (DebugView::CULLING) draws what the planes cull as blue ghosts (Debug views). |
After the test, the kept draws are packed into one list and drawn with one indirect call per run of one alpha mode and cull mode. That part is stream compaction. The occlusion and LOD steps run in the same shader.
Where it lives in code
| What | Where |
|---|---|
| Bounding sphere per sub-mesh | computeBounds in src/renderer/geometryPool.cpp |
| Planes from the matrix | getFrustumPlanes in src/renderer/gpuScene.cpp, called by Renderer::prepareSceneView |
| Where the planes are stored | SceneData::frustumPlanes in shaders/lib/core.slang and src/renderer/uberMaterialTypes.h |
| Sphere into world space | getWorldSphere in shaders/lib/frustumCulling.slang |
| The test | isInFrustum in shaders/lib/frustumCulling.slang |
| Where it is called | countMain in shaders/passes/cull.slang |
| The projection (reversed-Z, infinite far) | toProjectionMatrix in src/scene/camera.cpp |
- The test must stay conservative. A smaller radius or a tighter stretch bound that can be too small makes objects vanish at the screen's edges.
- Plane normals point inside, and inside is
dot(xyz, p) + w >= 0, as the comment onfrustumPlanesincore.slangsays.getFrustumPlanesandisInFrustummust agree. - Do not normalize a plane whose normal has length 0. That is the infinite far plane.
SceneDatais a CPU↔GPU struct: a change to it follows the struct layout rules.
Further reading
- Gil Gribb and Klaus Hartmann, Fast Extraction of Viewing Frustum Planes from the World-View-Projection Matrix (2001).
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapters on intersection tests and on culling.
- Jack Ritter, An Efficient Bounding Sphere, in Graphics Gems (1990).
- Christer Ericson, Real-Time Collision Detection (2004): bounding volumes, and the box-plane test.