Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 62 ยท Projects

Project: A Tiny 3D Wireframe Renderer

Draw a spinning 3D cube using only matrices: vertex arrays, rotation matrices, a camera shift, perspective projection and matplotlib line drawing.

Every 3D game and animation is built on the same linear algebra you have been learning: shapes are lists of points, moving a shape is a matrix product, and the picture on your screen is a projection of 3D numbers onto a 2D plane. Here you will build the smallest possible version, a renderer that draws wireframe objects such as a cube, with nothing but NumPy and matplotlib.

The pipeline has four steps. First, describe the object as an array of vertices and a list of edges. Second, rotate it with a rotation matrix. Third, push it away from the camera. Fourth, project it to 2D with a perspective divide and draw the edges as lines. By the end you will see why far things look smaller, and why the same rotation code works for any object.

The wireframe pipeline

Model Vertices and edges describe the shape.
Rotate A 3 by 3 matrix turns every vertex.
Camera Move the object in front of the viewer.
Project Divide by depth to get 2D points.

Each step is a matrix product or one array expression.

1 / 2

Step 1: vertices and edges

A cube centered on the origin has eight corners, each with every coordinate equal to -1 or +1. itertools.product lists all eight sign combinations for us. Two corners are joined by an edge exactly when they differ in one coordinate; that rule produces the twelve edges of a cube without typing them out.

We store the vertices in an array with one row per point (shape (8, 3)), which is the usual layout in NumPy code.

Python Describe a cube

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 2: rotation matrices

In 3D there is one rotation matrix per axis. Rotating by angle a around the y axis mixes the x and z coordinates and leaves y alone:

TEXT
Ry(a) = [[ cos a, 0, sin a],
         [     0, 1,     0],
         [-sin a, 0, cos a]]

Rotations around x and z look alike with the cosine and sine in the other positions. To turn an object about two axes, multiply the matrices; remember that matrix multiplication is not commutative, so the order matters (the rightmost matrix acts first).

Because our points are rows, we apply a matrix R to all of them at once with vertices @ R.T. The transpose is needed because R @ v is the formula for a single point written as a column.

Python Rotate the cube and prove the rotation is rigid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first picture looks like a flat square, because looking straight down the z axis hides the depth: the front and back faces land on top of each other. The rotated cube already looks three-dimensional. Two checks in the output explain why the cube is not distorted. R.T @ R is the identity, so R is an orthogonal matrix, and its determinant is +1 (a rotation, not a reflection). Rigid motions keep every length and angle, so each corner stays the same distance from the center.

Step 3: the camera and perspective

Dropping z has a flaw: a far-away object and a nearby object of the same size look identical. Our eyes do not work that way. Things that are farther away look smaller, in proportion to their distance.

The standard fix is a perspective projection. Put the camera at the origin looking down the positive z axis and move the object d units in front of it by adding d to every z coordinate. A point at (x, y, z) then lands on the screen at

TEXT
(x', y') = ( f * x / (z + d),  f * y / (z + d) )

where f is a focal length that zooms the whole picture. Dividing by z + d is the key: doubling the distance halves the size. That division is not a linear map (it divides by a coordinate), which is why graphics code uses homogeneous coordinates to wrap it in matrix form, with the division left as a final step.

Python Perspective: near edges look bigger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The corner that is closer (z = -1, so its depth is 4) projects to (0.75, 0.75); the same corner on the far face (depth 6) projects to (0.5, 0.5). A cube looked at straight on now draws as a small square inside a larger one, joined by four lines: the familiar picture of a tunnel.

Step 4: one function that renders anything

Now we assemble the pipeline. render takes any vertices and edges, applies a rotation, shifts the object away from the camera, projects it and draws. We also shade each edge by its depth, so that edges farther away are drawn lighter, which gives a cheap sense of depth without hidden-line removal.

We then draw six frames of a spinning cube, plus a second shape (a pyramid) to show that the code does not know anything about cubes.

Python A spinning cube and a pyramid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The plot shows both shapes turning in 15 degree steps with the nearer edges drawn dark and the far ones light. The last two lines of output demonstrate a classic graphics bug in numbers: rotating 90 degrees about x and then 90 degrees about y does not give the same orientation as the opposite order, so the point (1, 0, 0) ends up in different places ([0, 0, -1] for the first order, [0, 1, 0] for the second).

Real graphics pipelines use 4 by 4 matrices so that rotation, translation and the perspective step all multiply into a single matrix that is applied once per vertex on the GPU. The structure you built here (model, rotate, move, project) is exactly that pipeline in miniature. See homogeneous coordinates.

Ideas to extend it

  • Add a scale matrix (np.diag([2, 1, 1])) to stretch the cube into a brick.
  • Draw a rotating grid of points, or an octahedron with six vertices.
  • Rotate about an arbitrary axis using the Rodrigues formula (build it from the cross product matrix).
  • Fill the faces with colors, and sort them by depth (the painter's algorithm).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Your vertices are stored one per row in an array of shape (8, 3). How do you apply a 3 by 3 matrix R to all of them?

    R @ v is the formula for one point as a column. With points as rows, the same product for all points at once is vertices @ R.T.
  2. 2. What does a determinant of +1 together with R.T @ R = I tell you about R?

    R.T @ R = I means R is orthogonal, so it preserves lengths and angles. A determinant of +1 rules out the reflection (-1), leaving a proper rotation.
  3. 3. In the perspective formula x' = f * x / (z + d), what makes distant objects look smaller?

    A larger depth in the denominator gives a smaller screen coordinate, so doubling an object's distance halves its apparent size.
  4. 4. Why does rot_y(90) @ rot_x(90) differ from rot_x(90) @ rot_y(90)?

    Composing rotations in a different order generally gives a different orientation. In A @ B @ v, the matrix B acts on v first.

Summary

  • A wireframe object is a vertex array (one point per row) plus a list of edges.
  • Rotation matrices are orthogonal with determinant 1; vertices @ R.T rotates every point at once and composing them is order-dependent.
  • Move the object in front of the camera by adding a distance to z, then project with f * x / (z + d).
  • The perspective divide is what makes far things small; it is the one non-linear step in the pipeline.
  • The same render function draws any shape: only the data changes.

Next project: Linear Regression from Scratch.