We have the scene expressed relative to the camera: each vertex knows how far it lies to the right, how far above and at what depth. But an image is flat. Projecting means going from three dimensions to two, and the way it is done decides the look of the image: in an orthographic projection objects keep their size wherever they are, as in a technical drawing; in a perspective projection what is far away looks smaller, as in a photograph. In this lesson we derive the matrices of both step by step, discover the true role of the \(w\) coordinate that we have been carrying along since Module 2, see why depth is distributed so unevenly and learn to discard, with six planes, everything the camera cannot see.

The code assumes that the functions from the previous lessons (to_homogeneous, transform_point, norm, point_plane_distance, look_at_matrix, orbit_camera, follow_camera, octahedron_mesh...) and the scene data are already defined: ship, lamp, camera, ship_world, hull_model, initial_view (the camera at \((0, 5, 20)\) with no rotation) and view (the same camera looking at the ship).

What projecting means

A projection casts, for each point of the scene, a line called a projector and marks where it crosses the projection plane (the image). Depending on what the projectors are like, there are two large families:

Parallel projection Perspective projection
Projectors Parallel to one another Converge at a point: the eye
Apparent size Does not depend on distance Decreases with distance
Parallel lines Stay parallel Converge at vanishing points

When the parallel projectors are also perpendicular to the projection plane, the projection is called orthographic. It is the camera version of the "projection onto a coordinate plane" that we saw in "Transformation Matrices": in view space it consists, quite simply, of forgetting the \(z\) coordinate.

In both cases projecting destroys information: all the points on a projector end up at the same point of the image. It is not an invertible transformation. However, the projection matrices we are going to build are invertible, because they do not throw depth away: they keep it in a third coordinate, which will be used in the next lesson to decide which object hides which.

The common destination: the NDC cube

A camera does not see the whole of space, but a limited region: the view volume. The job of the projection matrix is to take that volume, whatever its shape, to a standard cube:

\[ -1 \le x \le 1 \qquad -1 \le y \le 1 \qquad -1 \le z \le 1 \]

These are the normalized device coordinates (NDC). In them, \(x = -1\) is the left edge of the image and \(x = 1\) the right one; \(y = -1\) the bottom edge and \(y = 1\) the top one; \(z = -1\) the nearest thing the camera can see and \(z = 1\) the farthest. Whatever falls outside the cube is not drawn.

Working with a fixed cube decouples the stages: clipping and the step to pixels are programmed only once, without knowing which projection was used or how big the window is. One detail of the OpenGL convention, which is ours: in NDC, \(z\) grows toward the back, the opposite of view space. The projection flips the Z axis, and NDC is a left-handed system.

Orthographic projection

The view volume

In the orthographic projection the view volume is a box aligned with the camera's axes, defined by six numbers:

Parameter Meaning (in view space)
left \(l\), right \(r\) Limits in \(x\)
bottom \(b\), top \(t\) Limits in \(y\)
near \(n\), far \(f\) Positive distances to the near and far planes: the box goes from \(z = -n\) to \(z = -f\)

Deriving the matrix

We have to take a box to a cube. With what we know from Module 2, that is two steps:

  1. Translate the center of the box to the origin.
  2. Scale each axis so that the box measures 2 on a side.

For the X axis: the center is at \(\tfrac{r + l}{2}\) and the width is \(r - l\), so

\[ x_{\text{ndc}} = \frac{2}{r - l}\left(x - \frac{r + l}{2}\right) = \frac{2}{r - l},x - \frac{r + l}{r - l} \]

Check it at the ends: \(x = l\) gives \(-1\) and \(x = r\) gives \(+1\). The Y axis is identical with \(b\) and \(t\). On the Z axis, the box goes from \(-n\) to \(-f\) and the direction also has to be reversed (\(z = -n\) must go to \(-1\) and \(z = -f\) to \(+1\)), which changes the sign of the scale factor:

\[ z_{\text{ndc}} = -\frac{2}{f - n},z - \frac{f + n}{f - n} \]

Gathered into a 4×4 matrix:

\[ P_{\text{ortho}} = \begin{pmatrix} \dfrac{2}{r - l} & 0 & 0 & -\dfrac{r + l}{r - l} \\ 0 & \dfrac{2}{t - b} & 0 & -\dfrac{t + b}{t - b} \\ 0 & 0 & -\dfrac{2}{f - n} & -\dfrac{f + n}{f - n} \\ 0 & 0 & 0 & 1 \end{pmatrix} \]

It is an ordinary affine matrix (last row \(0, 0, 0, 1\)): a scaling and a translation. There is nothing new in it.

Example. A 32 × 18 m box centered on the camera's axis (\(l = -16\), \(r = 16\), \(b = -9\), \(t = 9\)), with \(n = 1\) and \(f = 100\). With the initial view, the ship is at \((8, -2, -14)\):

\[ x_{\text{ndc}} = \frac{2}{32} \cdot 8 = 0.5 \qquad y_{\text{ndc}} = \frac{2}{18} \cdot (-2) = -0.222 \qquad z_{\text{ndc}} = -\frac{2}{99}(-14) - \frac{101}{99} = \frac{28 - 101}{99} = -0.737 \]

The ship appears halfway between the center and the right edge, somewhat below the center.

import numpy as np

def orthographic_matrix(left, right, bottom, top, near, far):
    """Orthographic projection: takes the view box to the NDC cube [-1, 1]^3.

    `near` and `far` are positive distances measured in front of the camera.
    """
    m = np.eye(4)
    m[0, 0] = 2.0 / (right - left)
    m[1, 1] = 2.0 / (top - bottom)
    m[2, 2] = -2.0 / (far - near)
    m[0, 3] = -(right + left) / (right - left)
    m[1, 3] = -(top + bottom) / (top - bottom)
    m[2, 3] = -(far + near) / (far - near)
    return m

def project_point(mvp, p):
    """Takes a 3D point to NDC: multiplies by the matrix and divides by w."""
    clip = mvp @ to_homogeneous(p, 1.0)
    return clip[:3] / clip[3]

ortho = orthographic_matrix(-16.0, 16.0, -9.0, 9.0, 1.0, 100.0)
print(np.round(project_point(ortho @ initial_view, ship), 4))
[ 0.5    -0.2222 -0.7374]

project_point receives the complete matrix of the journey—here projection times view, applied to a point in the world—and divides by \(w\). With the orthographic projection \(w\) equals 1 and the division does nothing; we will see in a moment what it is there for.

Uses. The orthographic projection is used wherever measuring matters more than impressing: editors and CAD programs, 2D and strategy games, user interfaces (with a box that matches the window in pixels) and, as we will see later on, computing the shadows of a directional light.

Classic orthographic views: front view, plan view and side view

Technical drawing describes an object with three orthographic views taken along the axes. With the machinery we already have, each one is simply a well-placed camera plus an orthographic projection:

View The camera looks toward What is seen in the image Position of the camera
Front view (elevation) \(-Z\) \(x\) to the right, \(y\) up On the \(+Z\) axis
Plan view (top) \(-Y\) \(x\) to the right, \(-z\) up Above, with "up" \(= (0, 0, -1)\)
Side view (profile) \(-X\) \(-z\) to the right, \(y\) up On the \(+X\) axis

The plan view requires the alternative "up" vector, as we saw in the degenerate case of look-at.

front_view = look_at_matrix([0.0, 5.0, 50.0], [0.0, 5.0, 0.0])
plan_view = look_at_matrix([0.0, 50.0, 0.0], [0.0, 0.0, 0.0], up=(0.0, 0.0, -1.0))
side_view = look_at_matrix([50.0, 5.0, 0.0], [0.0, 5.0, 0.0])

for name, v in (("front", front_view), ("plan", plan_view), ("side", side_view)):
    print(name, np.round(transform_point(v, ship), 3) + 0.0,
          np.round(project_point(ortho @ v, ship)[:2], 4) + 0.0)
front [  8.  -2. -44.] [ 0.5    -0.2222]
plan [  8.  -6. -47.] [ 0.5    -0.6667]
side [ -6.  -2. -42.] [-0.375  -0.2222]
  • In the front view, the ship is drawn at \((x, y - 5) = (8, -2)\) m relative to the center of the image.
  • In the plan view, at \((x, -z) = (8, -6)\): it is the XZ plane seen from above that we have been using since Module 1.
  • In the side view, at \((-z, y - 5) = (-6, -2)\).

The distance from the camera to the object (44, 47 or 42 m) has no influence on the image: moving an orthographic camera away shrinks nothing. To zoom, the size of the box has to be changed.

Axonometric views: the isometric view

Each of the three previous views shows only two axes. An axonometric view is an orthographic projection from an oblique direction, so that all three axes are seen at once. They are classified by how many axes are foreshortened in the same proportion:

Type Axes with the same scale
Isometric All three
Dimetric Two
Trimetric None

The isometric view is obtained by looking along the diagonal of the cube: the camera lies in the direction \((1, 1, 1)\) relative to the target, which treats the three axes alike. In the spherical coordinates of the orbit camera, that is:

  • Azimuth 45°: halfway between \(+Z\) and \(+X\).
  • Elevation \(\arctan\left(1/\sqrt{2}\right) \approx 35.26°\): the vertical component is 1 and the horizontal one \(\sqrt{1^2 + 1^2} = \sqrt{2}\).
iso_elevation = np.arctan(1.0 / np.sqrt(2.0))
isometric = orbit_camera([0.0, 0.0, 0.0], 50.0, np.radians(45.0), iso_elevation)
unit = orthographic_matrix(-1.0, 1.0, -1.0, 1.0, 1.0, 100.0)

print(round(np.degrees(iso_elevation), 2))
for axis in ([1, 0, 0], [0, 1, 0], [0, 0, 1]):
    q = project_point(unit @ isometric, axis)[:2]
    print(axis, np.round(q, 4) + 0.0, round(norm(q), 4), round(np.degrees(np.arctan2(q[1], q[0])), 1))
35.26
[1, 0, 0] [ 0.7071 -0.4082] 0.8165 -30.0
[0, 1, 0] [0.     0.8165] 0.8165 90.0
[0, 0, 1] [-0.7071 -0.4082] 0.8165 -150.0

The unit box goes from \(-1\) to \(1\), so the NDC coordinates coincide with meters on the image plane. The three unit vectors of the axes are projected with the same length, \(\sqrt{2/3} \approx 0.8165\), and in directions 120° apart: the Y axis vertical, and the X and Z axes 30° below the horizontal. It is the diamond grid of classic "isometric" games. (Many of them actually use a dimetric view with a 2:1 slope, about 26.57° instead of 30°, because it is easier to draw with pixels.)

Perspective projection: the pinhole camera

The simplest model of a camera is the pinhole camera (or camera obscura): a closed box with a tiny hole. Each point of the scene sends a single ray of light through the hole, and that ray marks a point on the back wall. The image comes out upside down; to avoid that, in graphics we imagine the image plane in front of the hole, at a distance \(n\). The hole is the eye, at the origin of view space.

Let \(P = (x, y, z)\) be a point in view space, with \(z < 0\) (in front of the camera). Its depth is \(-z\). The line that joins it to the eye crosses the image plane, \(z = -n\), at a point \(P'\). Looking at the scene from the side we see two right triangles with their vertex at the eye: one reaches as far as \(P'\), with legs \(n\) and \(y'\); the other as far as \(P\), with legs \(-z\) and \(y\). They share the angle at the eye, so they are similar and their legs are proportional:

\[ \frac{y'}{n} = \frac{y}{-z} \quad\Longrightarrow\quad y' = \frac{n,y}{-z} \qquad\qquad \text{and likewise} \quad x' = \frac{n,x}{-z} \]

This is all there is to perspective: dividing by the depth. An object twice as far away looks half as big. The points \((8, -2, -14)\) and \((4, -1, -7)\) give the same \((x', y')\): they are on the same projector.

And here the problem appears. Dividing by a coordinate is not a linear operation, nor even an affine one: no 3×3 matrix and no affine 4×4 matrix can do it. The solution lies in homogeneous coordinates.

Field of view, aspect ratio and frustum

The view volume of a perspective camera is a pyramid with its apex at the eye, cut by two planes perpendicular to the line of sight. The result is a truncated pyramid called the frustum. It is described with four parameters:

Parameter Meaning Value in mini3d
Vertical field of view (FOV) Angle between the top and bottom edges of the image 60°
Aspect ratio \(a\) Width of the image divided by its height \(16/9 \approx 1.778\)
Near plane \(n\) Minimum visible distance 1 m
Far plane \(f\) Maximum visible distance 100 m

The top edge of the image forms an angle \(\text{FOV}/2\) with the line of sight, so at depth \(d\) half the visible height is \(d \tan(\text{FOV}/2)\), and half the width, \(a\) times that. With our values, \(\tan 30° = 0.5774\): at 14 m from the camera we see \(\pm 8.08\) m vertically and \(\pm 14.37\) m horizontally. The horizontal field of view turns out to be \(2 \arctan(a \tan 30°) \approx 91.5°\).

The FOV acts like the zoom of a lens: a small value (20°) is a telephoto lens that brings the scene closer and "flattens" it; a large one (100°) is a wide-angle lens that takes in a lot and exaggerates the perspective.

It is convenient to define the quantity

\[ c = \frac{1}{\tan(\text{FOV}/2)} = \cot\left(\frac{\text{FOV}}{2}\right) \]

which for 60° equals \(\sqrt{3} \approx 1.7321\). It is the distance at which the image plane would have to be placed for its upper half to measure exactly 1.

Deriving the perspective matrix

The x and y coordinates

We want the top edge of the frustum to go to \(y_{\text{ndc}} = 1\). At depth \(-z\), that edge is at height \(-z \tan(\text{FOV}/2) = -z/c\). Therefore:

\[ y_{\text{ndc}} = \frac{y}{-z/c} = \frac{c,y}{-z} \qquad\qquad x_{\text{ndc}} = \frac{c,x}{a,(-z)} \]

The \(x\) is also divided by the aspect ratio, because the frustum is \(a\) times wider than it is tall and both must end up in the interval \([-1, 1]\).

The w trick

In "Transformation Matrices" we said that a homogeneous point \((x, y, z, w)\) represents the 3D point \((x/w,\ y/w,\ z/w)\), and from_homogeneous has been dividing by \(w\) ever since. Until today \(w\) was always 1 and that division was a formality. Now we give it a job: we make the matrix copy the depth \(-z\) into \(w\), and the division by \(w\), which is done afterward and outside the matrix, will be the perspective division.

Copying \(-z\) into \(w\) is a linear operation. It is enough for the last row of the matrix to be \((0, 0, -1, 0)\):

\[ w_{\text{clip}} = -z \]

The first two rows compute the numerators, \(x_{\text{clip}} = \tfrac{c}{a},x\) and \(y_{\text{clip}} = c,y\).

The z coordinate

The third row is still missing. Since \(z_{\text{ndc}}\) will also be divided by \(w = -z\), we look for two constants \(A\) and \(B\) such that

\[ z_{\text{ndc}} = \frac{A,z + B}{-z} \]

takes the near plane to \(-1\) and the far plane to \(+1\):

\[ z = -n:\ \ \frac{-A,n + B}{n} = -1 \ \Longrightarrow\ -A,n + B = -n \qquad\qquad z = -f:\ \ \frac{-A,f + B}{f} = 1 \ \Longrightarrow\ -A,f + B = f \]

It is a system of two equations in two unknowns. Subtracting the first from the second: \(-A,(f - n) = f + n\), and substituting:

\[ A = -\frac{f + n}{f - n} \qquad\qquad B = -n + A,n = -\frac{2 f n}{f - n} \]

The matrix

\[ P_{\text{persp}} = \begin{pmatrix} \dfrac{c}{a} & 0 & 0 & 0 \\ 0 & c & 0 & 0 \\ 0 & 0 & -\dfrac{f + n}{f - n} & -\dfrac{2 f n}{f - n} \\ 0 & 0 & -1 & 0 \end{pmatrix} \qquad c = \cot\left(\frac{\text{FOV}}{2}\right) \]

For the first time in the course, the last row of a 4×4 matrix is not \((0, 0, 0, 1)\). That is the hallmark of a projective transformation, which is no longer affine.

With our parameters: \(c/a = 1.7321/1.7778 = 0.9743\), \(A = -101/99 = -1.0202\) and \(B = -200/99 = -2.0202\).

def perspective_matrix(vertical_fov, aspect, near, far):
    """OpenGL-style perspective projection. vertical_fov in radians; aspect = width / height."""
    c = 1.0 / np.tan(vertical_fov / 2.0)
    m = np.zeros((4, 4))
    m[0, 0] = c / aspect
    m[1, 1] = c
    m[2, 2] = -(far + near) / (far - near)
    m[2, 3] = -2.0 * far * near / (far - near)
    m[3, 2] = -1.0
    return m

projection = perspective_matrix(np.radians(60.0), 16.0 / 9.0, 1.0, 100.0)
print(np.round(projection, 4))
[[ 0.9743  0.      0.      0.    ]
 [ 0.      1.7321  0.      0.    ]
 [ 0.      0.     -1.0202 -2.0202]
 [ 0.      0.     -1.      0.    ]]

The perspective divide: from clip space to NDC

The result of multiplying by the projection matrix is a point in clip space, with four coordinates and \(w \ne 1\). Dividing the first three by \(w\)—the perspective divide—gives the point in NDC.

Example. The ship, at \((8, -2, -14)\) with the initial view:

\[ \begin{pmatrix} 0.9743 \cdot 8 \ 1.7321 \cdot (-2) \ -1.0202 \cdot (-14) - 2.0202 \ -(-14) \end{pmatrix} = \begin{pmatrix} 7.794 \ -3.464 \ 12.263 \ 14 \end{pmatrix} \quad\xrightarrow{\ \div, w\ }\quad \begin{pmatrix} 0.557 \ -0.247 \ 0.876 \end{pmatrix} \]

The coordinate \(w = 14\) is, literally, the depth of the point. It is worth remembering: we will use it several times in what remains of the module.

clip = projection @ to_homogeneous([8.0, -2.0, -14.0])
print(np.round(clip, 4), np.round(clip[:3] / clip[3], 4))

print(np.round(project_point(projection @ view, ship), 4))          # camera looking at the ship
print(np.round(project_point(projection @ view, lamp), 4))

mvp = projection @ view @ hull_model
for vertex in octahedron_mesh()["vertices"]:
    print(np.round(project_point(mvp, vertex), 4))
[ 7.7942 -3.4641 12.2626 14.    ] [ 0.5567 -0.2474  0.8759]
[0.     0.     0.8959]
[-0.5905  0.9611  0.8968]
[0.0239 0.0419 0.9201]
[-0.0393 -0.0687  0.8561]
[0.     0.1066 0.8949]
[ 0.     -0.105   0.8968]
[ 0.1208 -0.0033  0.894 ]
[-0.1172  0.0032  0.8977]
  • With the camera aimed at the ship, its center falls at the center of the image, \((0, 0)\). The lighthouse lamp only just makes it in: top left, with \(y_{\text{ndc}} = 0.96\).
  • The product projection @ view @ hull_model is the MVP matrix (model-view-projection): it takes a vertex from local space directly to clip space. It is computed once per object.
  • The six vertices of the hull occupy a small region around the center: from \(-0.12\) to \(0.12\) horizontally and from \(-0.10\) to \(0.11\) vertically. Seen from 16 m with a 60° field of view, the ship takes up roughly a tenth of the height of the image.
  • Look at the two wing tips (the first two vertices). In view space they were at \(x = \pm 0.496\); in NDC, the farther one ends up at \(0.024\) and the nearer one at \(-0.039\). The same length, closer up, looks bigger: that is perspective.

Depth is not linear

Let us write \(z_{\text{ndc}}\) as a function of the distance \(d = -z\) to the camera:

\[ z_{\text{ndc}} = \frac{A,(-d) + B}{d} = \frac{f + n}{f - n} - \frac{2 f n}{f - n} \cdot \frac{1}{d} \]

Depth in NDC is not proportional to \(d\), but to \(1/d\). Let us see what that implies, with \(f = 100\) and two choices of near plane:

Distance \(d\) (m) \(z_{\text{ndc}}\) with \(n = 1\) \(z_{\text{ndc}}\) with \(n = 0.01\) Orthographic (\(n = 1\))
1 \(-1\) 0.9802 \(-1\)
2 0.0101 0.9902 \(-0.980\)
5 0.6162 0.9962 \(-0.919\)
10 0.8182 0.9982 \(-0.818\)
50 0.9798 0.9998 \(-0.010\)
100 1 1 1

With \(n = 1\), half the range of depth (from \(-1\) to 0) is spent on the first visible meter, between 1 and 2 m; everything between 50 and 100 m is squeezed into the last 1%. With \(n = 0.01\) it is much worse: from 1 m onward, the whole scene fits into the final 1% of the range. The orthographic projection, by contrast, distributes depth uniformly.

This matters because depth is stored with a limited number of bits. Differentiating the formula above gives the minimum separation that can be told apart at a distance \(d\) when the step of \(z_{\text{ndc}}\) is \(\Delta z\):

\[ \Delta d \approx \Delta z \cdot \frac{d^2,(f - n)}{2 f n} \]

def depth_step(d, near, far, bits=24):
    """Minimum separation (in meters) that a depth buffer can tell apart at distance d."""
    ndc_step = 2.0 / 2 ** bits
    return ndc_step * d * d * (far - near) / (2.0 * far * near)

for near in (1.0, 0.01):
    print(near, ["{:.2g}".format(depth_step(d, near, 100.0)) for d in (2.0, 14.0, 50.0, 100.0)])
1.0 ['2.4e-07', '1.2e-05', '0.00015', '0.00059']
0.01 ['2.4e-05', '0.0012', '0.015', '0.06']

With 24 bits and \(n = 1\), at 50 m surfaces 0.15 mm apart can be told apart. With \(n = 0.01\), the resolution at 50 m drops to 1.5 cm, and at 100 m, to 6 cm: two surfaces closer together than that will receive the same depth and the engine will not know which one is in front. Two practical lessons:

  • Precision gets worse with the square of the distance.
  • It depends on \(1/n\): bringing the near plane a hundred times closer costs a hundred times more precision, whereas pushing the far plane away hardly matters (with \(f \gg n\), the factor \((f - n)/f\) is almost 1). The golden rule is to put the near plane as far away as the scene allows.

We will see the visible consequences of running out of precision in the next lesson, when we study the z-buffer.

Orthographic versus perspective

Orthographic Perspective
View volume Box Truncated pyramid (frustum)
Parameters \(l, r, b, t, n, f\) FOV, aspect, \(n\), \(f\)
Type of matrix Affine: last row \((0, 0, 0, 1)\) Projective: last row \((0, 0, -1, 0)\)
Clip-space \(w\) Always 1 The depth, \(-z\)
Apparent size Independent of distance Proportional to \(1/\text{distance}\)
Parallel lines Stay parallel Converge at vanishing points
Depth in NDC Linear Proportional to \(1/d\): concentrated up close
Near plane Can be 0 or negative Must be strictly positive
Feel Technical, "flat" Realistic
Uses CAD, editors, 2D, strategy, interface, shadows Almost all 3D games

The frustum planes and object culling

Transforming and drawing an object that lies outside the field of view is wasted work. Frustum culling avoids it with a cheap test per object, before anything is sent to be drawn. It is a broad phase, in the sense of "Intersections: Rays, Spheres, Triangles and Boxes": the object's bounding sphere is tested against the six planes that bound the view volume.

Extracting the planes

The planes can be read directly from the matrix \(VP = P,V\) (projection times view). A point of the world \(\mathbf{p}\) lies inside the volume if, in clip space, it satisfies \(-w \le x \le w\), and the same for \(y\) and \(z\). Take the condition for the left edge, \(x_{\text{clip}} + w_{\text{clip}} \ge 0\). Since \(x_{\text{clip}}\) is row 1 of \(VP\) multiplied by \((\mathbf{p}, 1)\) and \(w_{\text{clip}}\) is row 4 times the same thing:

\[ (\text{row}_4 + \text{row}_1) \cdot (p_x, p_y, p_z, 1) \ge 0 \]

That is exactly the condition of a half-space, \(\mathbf{n} \cdot \mathbf{p} + d \ge 0\): the first three numbers of \(\text{row}_4 + \text{row}_1\) are the normal of the left plane (pointing into the frustum) and the fourth is \(d\). All six planes come out the same way:

Plane Condition Coefficients
Left / right \(w + x \ge 0\) / \(w - x \ge 0\) \(\text{row}_4 \pm \text{row}_1\)
Bottom / top \(w + y \ge 0\) / \(w - y \ge 0\) \(\text{row}_4 \pm \text{row}_2\)
Near / far \(w + z \ge 0\) / \(w - z \ge 0\) \(\text{row}_4 \pm \text{row}_3\)

Dividing each 4-tuple by the norm of its normal gives planes in the (unit_normal, d) format of "Equations of Planes and Lines", ready for point_plane_distance.

The sphere test

A sphere with center \(\mathbf{c}\) and radius \(r\) is completely outside the frustum if it lies entirely on the outer side of some plane, that is, if the signed distance from its center to that plane is less than \(-r\).

def frustum_planes(vp):
    """The six planes (inward unit normal, d) of the view volume of the matrix vp."""
    planes = []
    for sign, row in ((1, 0), (-1, 0), (1, 1), (-1, 1), (1, 2), (-1, 2)):
        coefficients = vp[3] + sign * vp[row]       # left, right, bottom, top, near, far
        length = norm(coefficients[:3])
        planes.append((coefficients[:3] / length, coefficients[3] / length))
    return planes

def sphere_in_frustum(planes, center, radius):
    """False if the sphere lies entirely outside some plane; True if it may be visible."""
    return all(point_plane_distance(plane, center) >= -radius for plane in planes)

planes = frustum_planes(projection @ initial_view)
for name, (n, d) in zip(("left", "right", "bottom", "top", "near", "far"), planes):
    print(name, np.round(n, 4) + 0.0, round(d, 4))

objects = [("ship", ship, 4.0), ("lighthouse asteroid", [0.0, -10.0, 0.0], 10.0),
           ("stray asteroid", [-6.0, 2.0, 10.0], 2.0), ("freighter", [30.0, 3.0, 10.0], 3.0),
           ("satellite", [0.0, 5.0, 26.0], 2.0), ("distant drone", [0.0, 5.0, -90.0], 3.0)]
for name, center, radius in objects:
    distances = [point_plane_distance(plane, center) for plane in planes]
    print(name, sphere_in_frustum(planes, center, radius), np.round(distances, 1))
left [ 0.6978  0.     -0.7163] 14.3252
right [-0.6978  0.     -0.7163] 14.3252
bottom [ 0.     0.866 -0.5  ] 5.6699
top [ 0.    -0.866 -0.5  ] 14.3301
near [ 0.  0. -1.] 19.0
far [0. 0. 1.] 80.0
ship True [15.6  4.4  5.3  8.7 13.  86. ]
lighthouse asteroid True [14.3 14.3 -3.  23.  19.  80. ]
stray asteroid True [ 3.  11.3  2.4  7.6  9.  90. ]
freighter False [ 28.1 -13.8   3.3   6.7   9.   90. ]
satellite False [ -4.3  -4.3  -3.   -3.   -7.  106. ]
distant drone False [ 78.8  78.8  55.   55.  109.  -10. ]

The planes are easy to read. The near one has normal \((0, 0, -1)\) and \(d = 19\): it is the plane \(z = 19\), one meter in front of the camera (which is at \(z = 20\)). The far one is \(z = -80\), 100 m away. The top and bottom planes have their normals tilted 30° from the vertical—half the FOV, which is how far those planes open out from the line of sight—and the side planes are opened wider, because of the aspect ratio.

As for the objects:

  • The ship is inside all six planes, 13 m from the near one and 4.4 m from the right one.
  • The lighthouse asteroid has its center 3 m outside the bottom plane, but its radius is 10: it pokes into the lower part of the image. That is why we test the sphere and not just the center.
  • The freighter lies 13.8 m outside the right plane; the satellite is behind the camera (7 m outside the near plane) and the distant drone, 10 m beyond the far plane. All three are culled without touching a single one of their triangles.

Like every broad phase, the test is conservative: a "no" is final, but a "yes" may be a false positive (a sphere near a corner of the frustum may not be entirely outside any one plane and still be outside). Whatever survives will be resolved exactly, triangle by triangle, in the clipping stage.

Common Mistakes and Tips

  • Passing near and far with a negative sign. They are positive distances; the planes are at \(z = -n\) and \(z = -f\).
  • Setting the near plane to 0 in perspective. \(B\) vanishes, all the depths have the same value (\(z_{\text{ndc}} = 1\)) and the ordering is lost. Tiny values such as 0.0001 are no good either: they wreck the precision.
  • Forgetting the division by \(w\). Clip coordinates are not yet positions in the image. If objects do not shrink with distance, the division is missing.
  • Dividing by \(w\) points that are behind the camera. They have \(w < 0\), and the division changes their sign: they would appear in front, inverted. We have to clip before dividing, as we will see in the next lesson.
  • Giving the FOV in degrees. Trigonometric functions work in radians: np.radians(60.0).
  • Confusing the vertical FOV with the horizontal one. Our matrix uses the vertical one; the horizontal one follows from it and from the aspect ratio.
  • Not updating the aspect ratio when the window is resized. The image gets stretched: circles look like ellipses.
  • Multiplying in the wrong order. \(MVP = P,V,M\): the model matrix acts first and the projection last.
  • Tip. To check a projection matrix, project the corners of the view volume: they must give exactly \((\pm 1, \pm 1, \pm 1)\).

Exercises

Exercise 1. For the game's minimap we use the lesson's plan-view camera (at \((0, 50, 0)\), looking down with "up" \((0, 0, -1)\)) and an orthographic projection with \(l = -20\), \(r = 20\), \(b = -15\), \(t = 15\), \(n = 10\) and \(f = 70\).

a) Write the projection matrix. b) Compute the NDC coordinates of the ship, whose view coordinates are \((8, -6, -47)\). c) What range of world heights \(y\) does the view volume span?

Exercise 2. A camera has a vertical FOV of 90°, aspect ratio 2, \(n = 2\) and \(f = 50\).

a) Write its perspective matrix. b) Compute the clip and NDC coordinates of the view-space points \((8, -2, -14)\) and \((4, -1, -7)\). What do you notice? c) Do the same with \((8, -2, -2)\). Is that point visible?

Exercise 3. The ship's cockpit camera is at its local point \((0, 0.5, 1)\) and looks at the local point \((0, 0.5, 10)\). With the lesson's projection projection, decide with sphere_in_frustum whether beacon Alpha (center \((12, 7, 4)\), radius 0.5) can appear in the image, and explain why using its NDC coordinates.

Solutions

Solution 1.

a) Since the box is symmetric, \(r + l = 0\) and \(t + b = 0\). We are left with \(\tfrac{2}{40} = 0.05\), \(\tfrac{2}{30} = 0.0667\), \(-\tfrac{2}{60} = -0.0333\) and \(-\tfrac{80}{60} = -1.3333\):

\[ P = \begin{pmatrix} 0.05 & 0 & 0 & 0 \ 0 & 0.0667 & 0 & 0 \ 0 & 0 & -0.0333 & -1.3333 \ 0 & 0 & 0 & 1 \end{pmatrix} \]

b) \(x = 0.05 \cdot 8 = 0.4\); \(y = 0.0667 \cdot (-6) = -0.4\); \(z = -0.0333 \cdot (-47) - 1.3333 = 1.5667 - 1.3333 = 0.2333\).

c) The camera is at \(y = 50\) and looks down. The near plane is 10 m below it (\(y = 40\)) and the far plane, 70 m below (\(y = -20\)). It spans from \(y = -20\) to \(y = 40\): it includes the whole lighthouse asteroid, the tower and the ship.

Solution 2.

a) \(c = \cot 45° = 1\); \(c/a = 0.5\); \(A = -\tfrac{52}{48} = -1.0833\); \(B = -\tfrac{2 \cdot 50 \cdot 2}{48} = -4.1667\):

\[ P = \begin{pmatrix} 0.5 & 0 & 0 & 0 \ 0 & 1 & 0 & 0 \ 0 & 0 & -1.0833 & -4.1667 \ 0 & 0 & -1 & 0 \end{pmatrix} \]

b) For \((8, -2, -14)\): clip \((4,\ -2,\ 15.167 - 4.167,\ 14) = (4, -2, 11, 14)\); NDC \((0.2857, -0.1429, 0.7857)\).

For \((4, -1, -7)\): clip \((2,\ -1,\ 7.583 - 4.167,\ 7) = (2, -1, 3.417, 7)\); NDC \((0.2857, -0.1429, 0.4881)\).

The two points have the same \(x\) and \(y\) in NDC: they are on the same projector (one is half the other) and fall on the same point of the image. Only \(z\) tells them apart: the second is closer and would hide the first.

c) Clip \((4,\ -2,\ 2.167 - 4.167,\ 2) = (4, -2, -2, 2)\); NDC \((2, -1, -1)\). It is exactly on the near plane (\(z_{\text{ndc}} = -1\)) and on the bottom edge (\(y_{\text{ndc}} = -1\)), but \(x_{\text{ndc}} = 2\) is outside the interval \([-1, 1]\): it is not visible; it lies to the right of the field of view.

Solution 3.

minimap = orthographic_matrix(-20.0, 20.0, -15.0, 15.0, 10.0, 70.0)
print(np.round(project_point(minimap @ plan_view, ship), 4))

wide_angle = perspective_matrix(np.radians(90.0), 2.0, 2.0, 50.0)
for p in ([8.0, -2.0, -14.0], [4.0, -1.0, -7.0], [8.0, -2.0, -2.0]):
    r = wide_angle @ to_homogeneous(p)
    print(np.round(r, 4), np.round(r[:3] / r[3], 4))

cockpit = follow_camera(ship_world, [0.0, 0.5, 1.0], [0.0, 0.5, 10.0])
print(sphere_in_frustum(frustum_planes(projection @ cockpit), [12.0, 7.0, 4.0], 0.5),
      np.round(project_point(projection @ cockpit, [12.0, 7.0, 4.0]), 3))
[ 0.4    -0.4     0.2333]
[ 4. -2. 11. 14.] [ 0.2857 -0.1429  0.7857]
[ 2.     -1.      3.4167  7.    ] [ 0.2857 -0.1429  0.4881]
[ 4. -2. -2.  2.] [ 2. -1. -1.]
False [-3.897  6.062 -1.   ]

The first four lines confirm Exercises 1 and 2. Beacon Alpha cannot appear: in the previous lesson we saw that the cockpit camera has it at \((-4, 3.5, -1)\), ahead but only 1 m away and far off to one side. Its NDC coordinates, \((-3.9, 6.1, -1)\), are well outside the square \([-1, 1]\): it lies above and to the left of the field of view.

Conclusion

Projecting means taking the volume the camera sees to the NDC cube \([-1, 1]^3\). In the orthographic projection that volume is a box and the matrix is a translation followed by a scaling; placing the camera along the axes gives the front, plan and side views, and looking along the diagonal, the isometric view. In the perspective projection the volume is a frustum defined by the field of view, the aspect ratio and the near and far planes; the image is formed by dividing by the depth, something no affine matrix can do and which is achieved by copying \(-z\) into the \(w\) coordinate and dividing afterward. That division turns clip space into NDC and distributes depth very unevenly, which forces us to choose the near plane with care. From the matrix \(VP\) we also extract the six planes of the frustum, with which the objects that cannot be seen are culled. mini3d gains orthographic_matrix, perspective_matrix, project_point, depth_step, frustum_planes and sphere_in_frustum.

We have arrived at a cube of abstract coordinates between \(-1\) and \(1\), but a screen is made of pixels. In the next lesson, "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer", we will clip the triangles that stick out of the view volume, convert NDC into pixel coordinates, decide which pixels each triangle covers and use the depth we have so carefully preserved to work out which surface is seen at each one.

© Copyright 2026. All rights reserved