3D Graphics: Transform Pipelines
Every vertex drawn by a game engine or a 3D web page passes through a chain of matrices: model, view and projection. This lesson builds that pipeline from scratch in NumPy, so you can see exactly what the GPU's vertex shader does with projection * view * model * position.
Why matrices?
Rotation and scaling are linear maps of , so they are matrices (The Matrix of a Linear Transformation). Translation is not linear (it moves the origin), so it has no matrix. The trick is homogeneous coordinates: write a point as and a direction as . Then a translation becomes a linear map of :
Directions () ignore the translation column, which is what we want for normals and velocities. Now every transform, including translation and perspective, is one matrix, and a chain of them collapses into one product. See Homogeneous Coordinates for the game-programming view.
The pipeline
| Stage | Matrix | From → to |
|---|---|---|
| Model | object (local) space → world space | |
| View | world space → camera (eye) space | |
| Projection | eye space → clip space | |
| Perspective divide | divide by | clip space → normalized device coordinates, each in |
| Viewport | scale and shift | NDC → pixel coordinates |
A vertex is transformed as . Read right to left: the matrix nearest the vector acts first. The order inside matters too: scales, then rotates, then translates (TRS).
import numpy as np
def translate(tx, ty, tz):
M = np.eye(4); M[:3, 3] = [tx, ty, tz]; return M
def rotate_y(deg):
c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]])
def scale(sx, sy, sz):
return np.diag([sx, sy, sz, 1.0])
M = translate(5, 0, 0) @ rotate_y(90) @ scale(2, 2, 2)
corner = np.array([1, 0, 0, 1.0]) # a point in model space
print("world position:", np.round(M @ corner, 4))
print("direction (w=0):", np.round(M @ np.array([1, 0, 0, 0.0]), 4))
wrong = scale(2, 2, 2) @ rotate_y(90) @ translate(5, 0, 0)
print("other order: ", np.round(wrong @ corner, 4))world position: [ 5. 0. -2. 1.]
direction (w=0): [ 0. 0. -2. 0.]
other order: [ 0. 0. -12. 1.]
The point is scaled to , rotated 90° about to and moved to . Multiplying in the wrong order translates first and then rotates and scales the translation too.
The view matrix
A camera at position looking at a target has an orthonormal basis: right , up and backward (OpenGL cameras look down their axis). Its world transform is (as columns, with a bottom row 0 0 0 1). The view matrix is , and since the part is orthogonal, the inverse is cheap: transpose the rotation and apply as the translation. This is the classic lookAt (Look Rotation).
The projection matrix
A perspective projection with vertical field of view , aspect ratio and near/far planes (OpenGL convention) is
The last row copies into . After the perspective divide by , and are divided by the depth: far objects shrink. This is the same idea as Perspective Rendering, packed into a matrix so the GPU can treat it like any other transform. The third row maps depth so that goes to and to in NDC.
import numpy as np
def look_at(eye, target, up=(0, 1, 0)):
eye, target, up = map(np.asarray, (eye, target, up))
b = eye - target; b = b / np.linalg.norm(b) # backward
r = np.cross(up, b); r = r / np.linalg.norm(r) # right
u = np.cross(b, r) # true up
V = np.eye(4); V[:3, :3] = np.vstack([r, u, b]) # R^T: rows are the basis
V[:3, 3] = -V[:3, :3] @ eye
return V
def perspective(fov_deg, aspect, near, far):
f = 1 / np.tan(np.radians(fov_deg) / 2)
return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0],
[0, 0, (far + near) / (near - far), 2 * far * near / (near - far)],
[0, 0, -1, 0]])
V = look_at(eye=(0, 2, 6), target=(0, 0, 0))
P = perspective(60, 16 / 9, 0.1, 100)
W, H = 1920, 1080
for name, p in [("origin", (0, 0, 0)), ("near corner", (1, 0, 1)), ("far corner", (1, 0, -1))]:
clip = P @ V @ np.array([*p, 1.0])
ndc = clip[:3] / clip[3]
px = ((ndc[0] + 1) / 2 * W, (1 - ndc[1]) / 2 * H) # flip y: pixel rows go down
print(f"{name:11s} w={clip[3]:.3f} ndc=({ndc[0]:+.3f}, {ndc[1]:+.3f}, {ndc[2]:+.4f}) "
f"pixel=({px[0]:.0f}, {px[1]:.0f})")origin w=6.325 ndc=(+0.000, +0.000, +0.9703) pixel=(960, 540)
near corner w=5.376 ndc=(+0.181, -0.102, +0.9648) pixel=(1134, 595)
far corner w=7.273 ndc=(+0.134, +0.075, +0.9745) pixel=(1089, 499)
The camera looks at the origin, so it lands in the middle of the screen. The two corners are both at , but the one closer to the camera (smaller ) is drawn further from the centre. Notice how close the NDC depths are to 1: depth precision is concentrated near the near plane, which is why a tiny near value causes z-fighting.
Note: Conventions differ. Direct3D, Vulkan and WebGPU map depth to instead of , Vulkan flips , and some engines use row vectors (, so the order is reversed and the matrices are transposed). The linear algebra is identical; only the bookkeeping changes.
Normals need the inverse transpose
A surface normal must stay perpendicular to tangent vectors . If tangents transform by the part of , then normals must transform by , because . For rotations , but non-uniform scaling breaks normals if you skip this.
import numpy as np
A = np.diag([3.0, 1.0, 1.0]) # stretch x by 3
t = np.array([1.0, -1.0, 0.0]) # tangent of the plane x + y = 0
n = np.array([1.0, 1.0, 0.0]) # its normal
print("naive A n . A t =", float((A @ n) @ (A @ t)))
N = np.linalg.inv(A).T
print("correct N n . A t =", float((N @ n) @ (A @ t)))naive A n . A t = 8.0
correct N n . A t = 0.0
In software
- Vertex shaders compute
gl_Position = proj * view * model * vec4(pos, 1.0); engines precompute once per frame and once per object. - Scene graphs multiply parent and child model matrices (Hierarchy); Spaces and Screen Space cover the conversions engines expose.
- Picking runs the pipeline backwards with to turn a mouse click into a ray (Screen to World).
- CSS
transform: matrix3d(...)and Three.jsMatrix4are these same matrices (column-major in memory).
Exercises
Exercise 1: Translate a direction
What does do to the point and to the direction ?
Answer
The point becomes ; the direction stays .
Solution
Points have and pick up the translation column; directions have and do not.
Exercise 2: Order of operations
Compute and applied to the origin.
Answer
and .
Solution
In the first product the scale acts first (the origin stays put) and then the translation moves it to . In the second the origin is translated to and then scaled to .
Exercise 3: The perspective divide
A point has clip coordinates . What are its NDC coordinates, and is it inside the view volume?
Answer
: inside, since all three lie in .
Solution
Divide by .
Exercise 4: View matrix inverse (code)
Check that look_at(eye=(3, 4, 5), target=(0, 0, 0)) maps the eye to the origin and the target onto the negative axis, at distance .
Answer
; .
Solution
The camera looks down its axis, and the distance from eye to target is .
import numpy as np
def look_at(eye, target, up=(0, 1, 0)):
eye, target, up = map(np.asarray, (eye, target, up))
b = (eye - target) / np.linalg.norm(eye - target)
r = np.cross(up, b); r = r / np.linalg.norm(r); u = np.cross(b, r)
V = np.eye(4); V[:3, :3] = np.vstack([r, u, b]); V[:3, 3] = -V[:3, :3] @ eye
return V
V = look_at((3, 4, 5), (0, 0, 0))
print(np.round(V @ [3, 4, 5, 1], 4) + 0, np.round(V @ [0, 0, 0, 1], 4) + 0)[0. 0. 0. 1.] [ 0. 0. -7.0711 1. ]
Test yourself
Why do 3D engines use matrices for 3D points?
- GPUs cannot multiply matrices
- So that translation (and perspective) become matrix multiplications
- To store colour in the fourth component
- To make matrices invertible
In , which transform is applied to first?
- They commute
How should normals be transformed when the model matrix has a non-uniform scale?
- By the model matrix
- By the inverse transpose of its part
- By the projection matrix
- They should not be transformed