TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Perspective Rendering

Application: Perspective Rendering

How does a computer draw a 3D scene on a flat screen so that distant things look smaller? With a perspective projection: divide by depth. That division is not linear, but a trick called homogeneous coordinates turns the whole pipeline (move, rotate, project) into matrix products followed by one division. This lesson builds it from scratch and renders a wireframe cube.

The pinhole camera

Put the camera at the origin looking along the +z+z axis, with the image plane at distance ff (the focal length) in front of it. A point P=(x,y,z)P = (x, y, z) with z>0z > 0 projects to where the line from the camera to PP crosses the plane z=fz = f. By similar triangles:

x′=f⋅xz,y′=f⋅yzx' = \frac{f \cdot x}{z}, \qquad y' = \frac{f \cdot y}{z}

Doubling the distance zz halves the image size. That is perspective, and it is not linear: the map (x,y,z)↦(fx/z,fy/z)(x, y, z) \mapsto (fx/z, fy/z) divides by a coordinate, and it is not even defined at z=0z = 0. Compare orthographic projection (x,y,z)↦(x,y)(x, y, z) \mapsto (x, y), which is linear (a projection) but keeps far objects as large as near ones, like an engineering drawing.

Homogeneous coordinates

Represent the point (x,y,z)(x, y, z) by the 4-vector [x,y,z,1][x, y, z, 1], and agree that [X,Y,Z,W][X, Y, Z, W] and any non-zero multiple of it describe the same point (X/W,Y/W,Z/W)(X/W, Y/W, Z/W). Two problems are solved at once:

1. Translation becomes linear. A shift by (tx,ty,tz)(t_x, t_y, t_z) is the 4×4 matrix

[100tx010ty001tz0001][xyz1]=[x+txy+tyz+tz1]\begin{bmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} = \begin{bmatrix} x + t_x \\ y + t_y \\ z + t_z \\ 1 \end{bmatrix}

so rotations, scales and translations all compose by matrix multiplication (Homogeneous Coordinates).

2. Perspective becomes a matrix followed by a division. The 3×4 matrix

P=[f0000f000010],P [x,y,z,1]T=[f⋅xf⋅yz]  →  divide by the last entry: (f⋅x/z, f⋅y/z)P = \begin{bmatrix} f & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix}, \qquad P\,[x, y, z, 1]^T = \begin{bmatrix} f \cdot x \\ f \cdot y \\ z \end{bmatrix} \;\to\; \text{divide by the last entry: } (f \cdot x/z,\ f \cdot y/z)

is linear on homogeneous coordinates; the non-linear step is only the final perspective divide. GPUs do exactly this: the vertex shader outputs a 4-vector (clip coordinates) and fixed hardware divides by ww (Clip Space, NDC and Screen).

The pipeline

text
object coords ──M (model)──▶ world ──V (view)──▶ camera ──P──▶ homogeneous image ──÷w──▶ screen

The whole chain is one matrix PVMPVM applied to every vertex, then one division per vertex. Graphics APIs use a 4×4 version of PP that also keeps a depth value for the z-buffer (Perspective and Orthographic Projection, 3D Graphics: Transform Pipelines).

python · try it yourself
import numpy as np

def translate(tx, ty, tz):
    T = np.eye(4); T[:3, 3] = [tx, ty, tz]; return T

def rot_y(deg):
    t = np.radians(deg); c, s = np.cos(t), np.sin(t)
    R = np.eye(4); R[0, 0], R[0, 2], R[2, 0], R[2, 2] = c, s, -s, c; return R

f = 2.0
P = np.array([[f, 0, 0, 0], [0, f, 0, 0], [0, 0, 1, 0]])

p_object = np.array([1.0, 1.0, 1.0, 1.0])              # a cube corner, homogeneous
M = translate(0, 0, 5) @ rot_y(30)                      # rotate, then push 5 units away
h = P @ M @ p_object
print("homogeneous image:", np.round(h, 4).tolist())
print("screen point:", np.round(h[:2] / h[2], 4).tolist())

for z in (2, 4, 8):                                     # same point, further away
    h = P @ np.array([1.0, 1.0, z, 1.0])
    print(f"z = {z}: screen x = {h[0] / h[2]:.3f}")
homogeneous image: [2.7321, 2.0, 5.366]
screen point: [0.5091, 0.3727]
z = 2: screen x = 1.000
z = 4: screen x = 0.500
z = 8: screen x = 0.250

Rendering a wireframe cube

A cube has 8 corners and 12 edges. Transform the corners with one matrix product, divide, and draw the edges as lines:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from itertools import product

corners = np.array([[x, y, z, 1.0] for x, y, z in product([-1, 1], repeat=3)]).T   # 4 x 8
edges = [(i, j) for i in range(8) for j in range(i + 1, 8)
         if np.sum(corners[:3, i] != corners[:3, j]) == 1]                            # differ in one coord

def rot(axis, deg):
    t = np.radians(deg); c, s = np.cos(t), np.sin(t)
    R = np.eye(4); i, j = {"x": (1, 2), "y": (2, 0)}[axis]
    R[i, i], R[i, j], R[j, i], R[j, j] = c, -s, s, c
    return R

M = rot("x", 25) @ rot("y", 35)
M[:3, 3] = [0, 0, 4.5]                                  # translation: 4.5 units in front of the camera
P = np.array([[2.0, 0, 0, 0], [0, 2.0, 0, 0], [0, 0, 1, 0]])

h = P @ M @ corners                                     # 3 x 8: all corners at once
screen = h[:2] / h[2]                                   # perspective divide

plt.figure(figsize=(4.5, 4.5))
for i, j in edges:
    plt.plot(screen[0, [i, j]], screen[1, [i, j]], color="tab:blue")
plt.gca().set_aspect("equal"); plt.title("perspective wireframe cube")
print("edges:", len(edges))
print("depths of corners:", np.round(h[2], 2).tolist())
edges: 12
depths of corners: [3.85, 5.34, 4.7, 6.18, 2.82, 4.3, 3.66, 5.15]

The face nearer to the camera (smaller depth) is drawn larger, which is what gives the picture depth.

In software

  • Every 3D engine (OpenGL, Vulkan, Direct3D, WebGPU, Unity, Godot, three.js) runs this pipeline on the GPU for every vertex of every frame. The model, view and projection matrices are uploaded as uniforms; the divide by ww and the mapping to pixels are done by fixed-function hardware.
  • Perspective-correct texturing: because the divide is non-linear, attributes such as texture coordinates must be interpolated as u/wu/w and 1/w1/w across a triangle, then divided per pixel; plain linear interpolation makes textures swim.
  • Computer vision runs the pipeline backwards: a camera's 3×4 projection matrix (intrinsics×[R∣t]\text{intrinsics} \times [R \mid \mathbf{t}]) is estimated from images, and points are triangulated from two views. Augmented reality and photogrammetry depend on it.
  • Why homogeneous coordinates use w=1w = 1 for points and w=0w = 0 for directions: a direction [dx,dy,dz,0][dx, dy, dz, 0] ignores translation, which is exactly right for normals and velocities.

Exercises

Exercise 1: Project by hand

With f=3f = 3, where does the point (2,−1,6)(2, -1, 6) land on the image plane? And (4,−2,12)(4, -2, 12)?

Answer

Both land at (1,−0.5)(1, -0.5).

Solution
(2,−1,6):(3⋅2/6, 3⋅(−1)/6)=(1,−0.5)(4,−2,12):(3⋅4/12, 3⋅(−2)/12)=(1,−0.5)\begin{aligned} (2, -1, 6)&: \quad (3 \cdot 2/6,\ 3 \cdot (-1)/6) = (1, -0.5) \\ (4, -2, 12)&: \quad (3 \cdot 4/12,\ 3 \cdot (-2)/12) = (1, -0.5) \end{aligned}

The second point is twice as far along the same ray from the camera, so it lands on the same pixel: perspective projection is not one-to-one.

Exercise 2: Show it is not linear

Using f=1f = 1, show that projecting u=(1,0,1)\mathbf{u} = (1, 0, 1) and v=(1,0,3)\mathbf{v} = (1, 0, 3) separately and adding is not the same as projecting u+v\mathbf{u} + \mathbf{v}.

Answer

proj⁡(u)+proj⁡(v)=(4/3,0)\operatorname{proj}(\mathbf{u}) + \operatorname{proj}(\mathbf{v}) = (4/3, 0), but proj⁡(u+v)=(1/2,0)\operatorname{proj}(\mathbf{u} + \mathbf{v}) = (1/2, 0).

Solution
proj⁡(u)=(1/1,0)=(1,0),proj⁡(v)=(1/3,0)sum=(4/3,0)u+v=(2,0,4)→proj⁡=(2/4,0)=(1/2,0)≠(4/3,0)\begin{aligned} &\operatorname{proj}(\mathbf{u}) = (1/1, 0) = (1, 0), \quad \operatorname{proj}(\mathbf{v}) = (1/3, 0) \\ &\text{sum} = (4/3, 0) \\ &\mathbf{u} + \mathbf{v} = (2, 0, 4) \to \operatorname{proj} = (2/4, 0) = (1/2, 0) \ne (4/3, 0) \end{aligned}

Exercise 3: Compose translations

Write the 4×4 matrices for "translate by (1,2,3)(1, 2, 3)" and "translate by (−4,0,5)(-4, 0, 5)", multiply them, and interpret the product.

Answer

The product is the translation by (−3,2,8)(-3, 2, 8).

Solution

Translations add their offsets, and in homogeneous coordinates that happens through ordinary matrix multiplication.

python · try it yourself
import numpy as np
def T(tx, ty, tz):
    M = np.eye(4); M[:3, 3] = [tx, ty, tz]; return M
print(T(1, 2, 3) @ T(-4, 0, 5))
[[ 1.  0.  0. -3.]
 [ 0.  1.  0.  2.]
 [ 0.  0.  1.  8.]
 [ 0.  0.  0.  1.]]

Exercise 4: Vanishing point

Points on the line (1,−1,2+t)(1, -1, 2 + t) run straight away from the camera as tt grows. With f=1f = 1, project them for t=0,10,100,1000t = 0, 10, 100, 1000. Where do they converge?

Answer

They converge to (0,0)(0, 0), the vanishing point of lines parallel to the zz-axis.

Solution

The image is (1/(2+t),−1/(2+t))(1/(2 + t), -1/(2 + t)), which tends to (0,0)(0, 0) as t→∞t \to \infty. All lines parallel to the viewing direction meet at the image centre, like railway tracks at the horizon.

python · try it yourself
for t in (0, 10, 100, 1000):
    z = 2 + t
    print(t, (round(1 / z, 4), round(-1 / z, 4)))
0 (0.5, -0.5)
10 (0.0833, -0.0833)
100 (0.0098, -0.0098)
1000 (0.001, -0.001)

Test yourself

Why do graphics pipelines use 4-component homogeneous coordinates for 3D points?

  1. To store a colour
  2. So translation and perspective can be written as matrix products
  3. Because GPUs cannot handle 3-vectors
  4. To make rotations faster

With f=1f = 1, where does the point (3,6,3)(3, 6, 3) project?

  1. (1,2)(1, 2)
  2. (3,6)(3, 6)
  3. (9,18)(9, 18)
  4. (0.5,1)(0.5, 1)

Which step of the perspective pipeline is NOT linear?

  1. The model matrix
  2. The view matrix
  3. Multiplying by the projection matrix
  4. The divide by ww