Over thirty-one lessons, Polaris Studio has been adding functions to mini3d one at a time, and each has been tested in its own example. In this last lesson no new concept appears: the point is to make them all work at once, in a single program that assembles the scene of "Stellar Lighthouse", makes it evolve over time, interrogates it with geometric queries and draws it. It is a guided project: each block of code is short, because almost everything it does is call something we have already built, and you will see pieces from all six modules appear one after another. At the end you will find a checklist for debugging 3D programs, several extensions to carry on with by yourself and a review of the whole road traveled.
Organizing mini3d as a module
Until now we have "assumed to be defined" the functions from the previous lessons. For a real program they have to be gathered into an importable module. The natural organization follows the blocks of the course, and it has an important property: each block depends only on the earlier ones, just as each module of the course built on the previous ones.
| File | Content (lessons) | Representative functions | Depends on |
|---|---|---|---|
algebra.py |
Module 1: vectors, matrices, systems, inverses, eigenvalues | lerp, linear_combination, solve_system, inverse, is_orthogonal, diagonalize |
NumPy |
transforms.py |
Module 2: 4×4 matrices, composition, change of coordinate system | translation_matrix, rotation_matrix_y, model_matrix, compose, rigid_inverse, transform_point, world_to_local |
algebra |
geometry.py |
Module 3: norm, products, planes, distances, intersections | normalize, cross_product, orthonormal_basis, plane_from_point_normal, reflect, slide, ray_sphere, ray_triangle, spheres_overlap |
algebra |
rotations.py |
Module 4: Euler, axis-angle, quaternions, interpolation | euler_to_matrix, axis_angle_matrix, quaternion_product, quaternion_to_matrix, matrix_to_quaternion, quaternion_slerp, rotate_toward |
geometry |
graphics.py |
Module 5 and "Computer Graphics": meshes, cameras, projection, rasterization, surfaces, light, textures, renderer | octahedron_mesh, look_at_matrix, follow_camera, perspective_matrix, frustum_planes, rasterize_triangle, bezier, shade_point, render, to_ascii |
All of the above |
dynamics.py |
"Physics Simulation" | gravitation, semi_implicit_euler_step, verlet_step, bounce_on_plane, resolve_sphere_collision, integrate_orientation |
geometry, rotations |
animation.py |
"3D Animation" | sample_track, smoothstep, catmull_rom, arc_length_table, parameter_at_length, two_bone_ik, linear_skinning |
rotations, graphics |
xr.py |
"Virtual and Augmented Reality" | stereo_views, asymmetric_perspective_matrix, project_with_intrinsics, ray_from_screen, radial_distortion |
graphics |
In practice: copy the functions of each lesson into the corresponding file, inside a mini3d/ folder, and add an __init__.py that re-exports them (from .algebra import *, etc.). That way the program of this lesson starts with a single line, from mini3d import *. Two pieces of advice when doing so:
- Only functions and constants; no scene data.
ship,lamporhull_modelbelong to the game, not to the library. An engine function must not read global variables of the example in which it was born. - Keep the examples as tests. Every block of code with its expected output is a potential automated test: if something stops giving the same result when you reorganize, you will know right away.
The plan of the program
An interactive 3D program, whether a game or a simulator, always has the same skeleton: a main loop that repeats once per time step.
flowchart TD
A["Build the scene<br/>(graph of nodes)"] --> B["Update<br/>animation and physics, with a fixed step"]
B --> C["Query<br/>lighthouse beam, visibility, picking"]
C --> D["Draw<br/>follow camera + render"]
D --> E{"Done?"}
E -- no --> B
E -- yes --> F["Log and frames"]
Our sequence lasts 12 seconds and tells a small story: the ship travels the approach route and settles on the strip; on the way it releases a probe, which falls toward the lighthouse asteroid and bounces; the lighthouse lamp rotates and its beam sweeps the scene; and the rogue asteroid—it is not called that for nothing—drifts slowly, so that its shadow does not always fall in the same place.
| Phase | What happens | Lessons involved |
|---|---|---|
| Scene | Graph with 13 nodes | "Composition of Transformations", "Representing 3D Objects" |
| Animation | Ship along a spline, with easing and slerp; rotation of the lamp; drift of the asteroid | "3D Animation", "Surface Modeling", "Interpolating Rotations: Lerp, Nlerp and Slerp" |
| Physics | Probe with gravitation and bounce | "Physics Simulation" |
| Queries | Cone of the beam, shadow ray, frustum, picking ray | Module 3, "Projections and Views", "Virtual and Augmented Reality" |
| Drawing | Follow camera and renderer | Module 5, "Computer Graphics" |
The scene: a graph with all the objects
Each object is a node with a local matrix (its position and orientation relative to its parent) and, optionally, a mesh. The world matrix of a node is the product of the local matrices from the root, as in "Composition of Transformations". We make two design decisions:
- Scale is not inherited. Each node keeps the scale of its own mesh apart from its local matrix, which is therefore always rigid. The model matrix it is drawn with is \(M_{\text{world}},S\). This way the hull can measure \(4 \times 1 \times 2\) without deforming whatever hangs from the ship, and all the world matrices can be inverted with
rigid_inverse. - Each node with a mesh carries the radius of its bounding sphere, for the quick queries.
graph TD
M["World"] --> A["asteroid"]
A --> F["lighthouse"]
F --> T["tower"]
F --> O["lamp (rotates)"]
O --> C["dome"]
M --> N["ship (animated)"]
N --> K["hull"]
M --> E["rogue (drifts)"]
M --> P["strip"]
M --> B["beacon1, beacon2, beacon3"]
M --> S["probe (physics)"]
import numpy as np
from mini3d import *
np.set_printoptions(suppress=True)
def node(parent, local, mesh=None, scale=(1.0, 1.0, 1.0), material=None, radius=0.0):
"""Node of the scene graph. `local`: rigid matrix relative to the parent; `scale`: only
for its own mesh; `radius`: that of its bounding sphere, centered on the node."""
return {"parent": parent, "local": local, "mesh": mesh, "scale": scale,
"material": material, "radius": radius}
def world_matrix(nodes, name):
"""World matrix of a node: product of the local matrices from the root."""
current = nodes[name]
if current["parent"] is None:
return current["local"]
return world_matrix(nodes, current["parent"]) @ current["local"]
def position_of(nodes, name):
"""World position of the origin of a node (fourth column of its world matrix)."""
return world_matrix(nodes, name)[:3, 3]
rock = {"diffuse": (0.55, 0.5, 0.45), "specular": (0.1, 0.1, 0.1), "shininess": 8.0}
glass = {"diffuse": (0.2, 0.3, 0.5), "specular": (1.0, 1.0, 1.0), "shininess": 64.0}
metal = {"diffuse": (0.6, 0.65, 0.7), "specular": (0.9, 0.9, 0.9), "shininess": 32.0}
signal = {"diffuse": (1.0, 0.8, 0.2), "specular": (0.0, 0.0, 0.0), "shininess": 1.0}
hull = octahedron_mesh()
hull["colors"] = np.array([[0.9, 0.2, 0.2], [0.2, 0.9, 0.2], [0.8, 0.8, 0.8],
[0.3, 0.3, 0.3], [1.0, 1.0, 1.0], [1.0, 0.6, 0.0]])
B1, B2, B3 = np.array([13.0, 0.0, 2.0]), np.array([9.0, 4.0, 0.0]), np.array([9.0, 0.0, 4.0])
B4 = B2 + B3 - B1 # fourth corner of the strip: (5, 4, 2)
strip_center = (B1 + B4) / 2.0
strip_mesh = create_mesh(np.array([B1, B2, B4, B3]) - strip_center, [[0, 1, 2], [0, 2, 3]])
IDENTITY = np.eye(4)
nodes = {
"asteroid": node(None, translation_matrix(0.0, -10.0, 0.0), unit_sphere(10, 20),
(10.0, 10.0, 10.0), rock, 10.0),
"lighthouse": node("asteroid", translation_matrix(0.0, 10.0, 0.0)),
"tower": node("lighthouse", translation_matrix(0.0, 6.0, 0.0), cube_mesh(), (1.0, 6.0, 1.0), rock, 6.25),
"lamp": node("lighthouse", translation_matrix(0.0, 12.0, 0.0)),
"dome": node("lamp", IDENTITY, unit_sphere(8, 16), (1.5, 1.5, 1.5), glass, 1.5),
"rogue": node(None, translation_matrix(2.0, 8.0, 5.0), unit_sphere(10, 20),
(5.0, 5.0, 5.0), rock, 5.0),
"strip": node(None, translation_matrix(*strip_center), strip_mesh, (1.0, 1.0, 1.0), metal,
distance(B1, strip_center)),
"ship": node(None, IDENTITY),
"hull": node("ship", IDENTITY, hull, (4.0, 1.0, 2.0), metal, 4.0),
"probe": node(None, translation_matrix(0.0, -100.0, 0.0), unit_sphere(6, 12),
(0.4, 0.4, 0.4), signal, 0.4),
}
for k, beacon in enumerate((B1, B2, B3), start=1):
nodes[f"beacon{k}"] = node(None, translation_matrix(*beacon), octahedron_mesh(),
(0.4, 0.4, 0.4), signal, 0.4)
print(len(nodes), sum(1 for n in nodes.values() if n["mesh"] is not None))
print(position_of(nodes, "dome"), position_of(nodes, "tower"), strip_center,
np.round(triangle_normal(B1, B2, B4), 4))Thirteen nodes, ten of them with a mesh. The dome inherits three translations (asteroid → lighthouse → lamp) and ends up at \((0, 12, 0)\); the tower, a cube scaled to \(2 \times 12 \times 2\), is centered at \((0, 6, 0)\). The strip is the parallelogram of the three beacons and the fourth corner, two triangles with the vertices in the order that makes its normal \(\left(\tfrac{1}{3}, \tfrac{2}{3}, \tfrac{2}{3}\right)\): the visible face is the top one. The nodes lighthouse, lamp and ship have no mesh: they are intermediate coordinate systems, and their only job is to pass their motion on to their children. The probe waits outside the scene until the ship releases it.
Update (I): animation of the ship, the lamp and the rogue asteroid
Three nodes change their local matrix as a function of time, each with a different technique from "3D Animation":
- The ship travels the approach route (the cubic Bézier curve of "Surface Modeling") in 6 s, with the pace of the smoothstep and its speed controlled by the arc-length table. Its orientation follows the tangent and, on the final stretch, is blended with slerp toward the orientation of the strip. We add one detail with respect to the previous lesson: with the same blend, the center of the ship rises 1 m above the route along the normal of the strip. That is half the height of the hull: this way, at the end, the ship is left resting on the strip and not sunk halfway into it.
- The lamp rotates at 40°/s about the vertical axis, with a fixed downward tilt of 45°: \(R_y(\omega t),R_x(45°)\). Its beam, which leaves along the local \(+Z\) axis, sweeps out a cone.
- The rogue asteroid drifts with constant velocity \((-0.2, 0, 0.15)\) m/s: the simplest parametric line.
route = np.array([[8.0, 3.0, 6.0], [12.0, 3.0, 9.0], [9.0, 2.0, 5.0], [11.0, 0.0, 3.0]])
table = arc_length_table(lambda t: bezier(route, t))
strip_normal = np.array([1.0, 2.0, 2.0]) / 3.0
q_strip = matrix_to_quaternion(orthonormal_basis(slide(bezier_tangent(route, 1.0), strip_normal),
strip_normal))
APPROACH_DURATION = 6.0
ROGUE_VELOCITY = np.array([-0.2, 0.0, 0.15])
def ship_pose(t):
"""Pose (position, quaternion) of the ship at the instant t."""
u = min(t / APPROACH_DURATION, 1.0)
parameter = parameter_at_length(table, float(smoothstep(u)) * table[1][-1])
q_tangent = matrix_to_quaternion(orthonormal_basis(bezier_tangent(route, parameter)))
blend = float(smoothstep((u - 0.6) / 0.4)) # 0 up to 60% of the maneuver, 1 at the end
return (bezier(route, parameter) + blend * 1.0 * strip_normal,
quaternion_slerp(q_tangent, q_strip, blend))
def animate(nodes, t):
"""Updates the local matrices of the animated nodes."""
position, q = ship_pose(t)
nodes["ship"]["local"] = model_matrix(position, quaternion_to_matrix(q))
nodes["lamp"]["local"] = (translation_matrix(0.0, 12.0, 0.0)
@ rotation_matrix_y(np.radians(40.0) * t)
@ rotation_matrix_x(np.radians(45.0)))
nodes["rogue"]["local"] = translation_matrix(*(np.array([2.0, 8.0, 5.0]) + ROGUE_VELOCITY * t))
for t in (0.0, 3.0, 6.0):
animate(nodes, t)
lamp_world = world_matrix(nodes, "lamp")
print(t, np.round(position_of(nodes, "ship"), 3),
np.round(transform_direction(lamp_world, [0.0, 0.0, 1.0]), 3) + 0.0,
np.round(position_of(nodes, "rogue"), 2))0.0 [8. 3. 6.] [ 0. -0.707 0.707] [2. 8. 5.] 3.0 [10.239 2.017 5.959] [ 0.612 -0.707 -0.354] [1.4 8. 5.45] 6.0 [11.333 0.667 3.667] [-0.612 -0.707 -0.354] [0.8 8. 5.9]
At \(t = 0\) the ship is in its usual position and the beam points toward \(+Z\) and 45° downward, \((0, -0.707, 0.707)\). At 6 s the ship rests with its center at \((11.333, 0.667, 3.667)\), that is, the touchdown point \((11, 0, 3)\) plus the normal of the strip, and the rogue asteroid has moved 1.5 m.
Update (II): a probe with physics
After 1 s, the ship releases a 50 kg probe. From that moment on, the probe is not animated but simulated: at each time step the gravitation of the lighthouse asteroid (\(\mu = 80\) m³/s²) is applied to it, it is integrated with semi-implicit Euler and we check whether it has touched the ground. Since the ground is a sphere, at each step we build the tangent plane under the probe—its normal is the direction from the center of the asteroid to the probe—and reuse bounce_on_plane with a coefficient of restitution of 0.5.
MU, PROBE_MASS, PROBE_RADIUS = 80.0, 50.0, 0.4
def physics_step(nodes, probe, dt):
"""Advances the probe one step. Returns True if it has bounced on the asteroid in this step."""
center = position_of(nodes, "asteroid")
force = lambda p, v: gravitation(p, center, MU, PROBE_MASS)
p, v = semi_implicit_euler_step(probe["p"], probe["v"], force, PROBE_MASS, dt)
normal = direction_to(center, p)
ground = plane_from_point_normal(center + nodes["asteroid"]["radius"] * normal, normal)
probe["p"], probe["v"] = bounce_on_plane(p, v, PROBE_RADIUS, ground, 0.5)
nodes["probe"]["local"] = translation_matrix(*probe["p"])
return not np.allclose(v, probe["v"])The state of the probe (p, v) lives outside the graph, and after each step it is copied to the local matrix of its node: the physics writes to the scene graph, just as the animation does.
Query: the lighthouse beam, frustum culling and ray picking
With the scene updated, the program asks it questions. The three that follow are geometric queries from Module 3 applied to the world positions that the graph provides.
Does the beam light the ship? Two tests have to be passed. First, being inside the cone of the lamp: in_view_cone with the axis of the beam—the lamp's local \(+Z\) taken to the world—and a half-angle of 10°. Second, that nothing is in the way: a ray from the lamp to the ship, tested with ray_sphere against the two asteroids; there is shadow if the hit occurs before reaching the ship. It is the shadow we discovered in "Lighting and Shading", now with the asteroid in motion.
Which objects can be seen? Before drawing, frustum_planes extracts the six planes from the matrix \(P,V\) and sphere_in_frustum culls the nodes whose bounding sphere lies entirely outside one of them.
Which object is under the cursor? ray_from_screen turns the pixel into a ray. Picking applies the two-phase strategy of "Intersections: Rays, Spheres, Triangles and Boxes": a broad phase with the bounding spheres and, only for those the ray hits, a narrow phase with ray_triangle on the triangles of the mesh, already transformed to the world. The hit with the smallest \(t\) wins.
def beam_status(nodes):
"""'outside the beam', 'in shadow (who)' or 'lit', depending on whether the lighthouse beam reaches the ship."""
lamp_world = world_matrix(nodes, "lamp")
origin, axis = lamp_world[:3, 3], transform_direction(lamp_world, [0.0, 0.0, 1.0])
target = position_of(nodes, "ship")
if not in_view_cone(origin, axis, target, np.radians(10.0)):
return "outside the beam"
toward_ship = direction_to(origin, target)
for name in ("rogue", "asteroid"):
t = ray_sphere(origin, toward_ship, position_of(nodes, name), nodes[name]["radius"])
if t is not None and t < distance(origin, target):
return "in shadow (" + name + ")"
return "lit"
def model_of(nodes, name):
"""Model matrix for drawing a node: its world matrix times its own scale."""
return world_matrix(nodes, name) @ scaling_matrix(*nodes[name]["scale"])
def visible_objects(nodes, vp):
"""Names of the nodes with a mesh whose bounding sphere touches the frustum of the matrix vp."""
planes = frustum_planes(vp)
return [name for name, n in nodes.items() if n["mesh"] is not None
and sphere_in_frustum(planes, position_of(nodes, name), n["radius"])]
def pick(nodes, x_px, y_px, width, height, camera):
"""Name of the closest object under a pixel (or None) and distance along the ray."""
origin, direction = ray_from_screen(x_px, y_px, width, height,
camera["view"], camera["projection"])
picked, t_min = None, np.inf
for name, n in nodes.items():
if n["mesh"] is None:
continue
if ray_sphere(origin, direction, position_of(nodes, name), n["radius"]) is None:
continue # broad phase: it does not even hit the sphere
in_world = transform_mesh(model_of(nodes, name), n["mesh"])
for a, b, c in in_world["vertices"][in_world["faces"]]: # narrow phase
t = ray_triangle(origin, direction, a, b, c)
if t is not None and t < t_min:
picked, t_min = name, t
return picked, t_minDraw: from the scene graph to the renderer
The renderer of "Computer Graphics" expects a list of objects with their mesh, their model matrix and their material, and a camera. The draw function acts as a bridge: it goes through the graph, keeps the visible nodes and computes their model matrices. The lighthouse light is rebuilt every frame from the world matrix of the lamp, so that it rotates with it. The camera is a follow camera: it is anchored to the ship, 5 m to one side, 2 m above and 6 m behind, and it looks at a point located 4 m ahead of the nose.
WIDTH, HEIGHT = 72, 20
projection = perspective_matrix(np.radians(60.0), 16.0 / 9.0, 0.5, 100.0)
star_light = {"type": "directional", "direction": np.array([0.36, 0.8, 0.48]),
"color": (0.3, 0.3, 0.35)}
def current_camera(nodes):
"""Follow camera anchored to the ship."""
view = follow_camera(world_matrix(nodes, "ship"), [5.0, 2.0, -6.0], [0.0, 0.0, 4.0])
return {"view": view, "projection": projection}
def draw(nodes, camera, width=WIDTH, height=HEIGHT):
"""Renders the visible nodes. Returns the image, their names and the per-stage count."""
visible = visible_objects(nodes, camera["projection"] @ camera["view"])
lamp_world = world_matrix(nodes, "lamp")
lighthouse_light = {"type": "spot", "position": lamp_world[:3, 3], "color": (2.0, 1.9, 1.6),
"attenuation": (1.0, 0.05, 0.005),
"axis": transform_direction(lamp_world, [0.0, 0.0, 1.0]),
"angles": (np.radians(6.0), np.radians(10.0))}
objects = [{"mesh": nodes[n]["mesh"], "material": nodes[n]["material"],
"model": model_of(nodes, n)} for n in visible]
scene = {"objects": objects, "lights": [lighthouse_light, star_light], "ambient": (0.05, 0.05, 0.08)}
image, _, counts = render(scene, camera, width, height)
return image, visible, countsThe main loop
Everything is ready. The loop advances with a fixed step of 0.05 s (20 steps per second), as we recommended in "Physics Simulation", for 12 s: 241 instants. At each one:
- Update: it animates the nodes and, if the probe has already been released, takes a physics step. The probe is released at step 20, 1.2 m below the center of the ship and with the ship's velocity, which we estimate by central differences of the animated position.
- Query the status of the beam and note an event when it changes.
- Draw once per second (every 20 steps) and add a row to the log.
DT = 0.05
probe, previous_beam = None, None
events, log, frames = [], [], {}
for step in range(241):
t = step * DT
animate(nodes, t) # 1. update
if step == 20:
velocity = (ship_pose(t + DT)[0] - ship_pose(t - DT)[0]) / (2.0 * DT)
probe = {"p": ship_pose(t)[0] - np.array([0.0, 1.2, 0.0]), "v": velocity}
events.append((t, "the ship releases the probe"))
elif probe is not None and physics_step(nodes, probe, DT):
events.append((t, f"the probe bounces and leaves at {norm(probe['v']):.2f} m/s"))
if step == 120:
events.append((t, "the ship settles on the strip"))
beam = beam_status(nodes) # 2. query
if beam != previous_beam:
events.append((t, "ship " + beam))
previous_beam = beam
if step % 20 == 0: # 3. draw
image, visible, counts = draw(nodes, current_camera(nodes))
frames[step // 20] = image
height = "-" if probe is None else round(
distance(probe["p"], position_of(nodes, "asteroid")) - 10.0, 2)
log.append((t, np.round(position_of(nodes, "ship"), 2), len(visible),
counts["rasterized"], counts["fragments"], height))It is thirty lines. Behind them, on every pass, several dozen functions from the six modules of the course are at work.
Results: log, events and frames
0.0 [8. 3. 6.] 7 33 292 - 1.0 [8.45 3. 6.33] 7 27 247 5.83 2.0 [9.64 2.88 7.03] 8 70 133 6.36 3.0 [10.24 2.02 5.96] 9 138 719 6.63 4.0 [10.32 1.15 4.46] 9 105 520 6.65 5.0 [10.92 0.74 3.76] 7 72 318 6.4 6.0 [11.33 0.67 3.67] 7 80 260 5.9 7.0 [11.33 0.67 3.67] 7 78 259 5.12 8.0 [11.33 0.67 3.67] 7 78 259 4.03 9.0 [11.33 0.67 3.67] 7 78 258 2.59 10.0 [11.33 0.67 3.67] 7 76 259 0.71 11.0 [11.33 0.67 3.67] 7 78 257 1.11 12.0 [11.33 0.67 3.67] 7 76 257 1.45
Each row of the log corresponds to a drawn frame: the instant, the position of the ship, how many of the 10 objects with a mesh survive frustum culling, how many triangles reach the rasterizer, how many fragments are written and the height of the probe above the asteroid. You can see the profile of the smoothstep (the ship advances little in the first second and in the last), that from 6 s on the ship no longer moves, and that the number of visible objects changes as the camera, dragged along by the ship, turns: frustum culling avoids processing between one and three objects per frame. The probe, which leaves with the almost horizontal velocity of the ship, gains height at first—the spherical surface of the asteroid curves away beneath it—and then falls faster and faster; it touches the ground shortly after 10 s and rises again.
0.00 s ship outside the beam 1.00 s the ship releases the probe 1.05 s ship in shadow (rogue) 1.60 s ship outside the beam 6.00 s the ship settles on the strip 10.15 s the probe bounces and leaves at 1.63 m/s 10.50 s ship lit 11.15 s ship outside the beam
The timeline summarizes the queries. The lighthouse beam passes over the ship twice. The first time, at 1.05 s, the ship is inside the cone but in shadow: the rogue asteroid is in the way, as we discovered in Module 5. The second time, at 10.50 s, the ship has settled and the rogue asteroid has moved aside far enough: for the first time in the whole course, the beam arrives. In between, the probe has bounced on the lighthouse asteroid at 10.15 s.
And the frames. We show two of the thirteen, in ASCII: halfway through the approach (\(t = 3\) s) and with the ship settled (\(t = 6\) s).
::::::::::::::::::::::
:::::::::::::::::::::
:::::::::::::::::::: +++++=+
::::::::::::::::::.******+++++++++
::::::::::::::::.. ******++++++++++
:::::::::::::... *****++++++++++
:::::::::::.. ***+++++++++++
::::::::...===--- *+++++++++++++
:::.....============ +++++++++++++
.....==================- ++++++++++++===++
..=======================- +++++==========+++++===
=========================== ---===================
===========================-------------============
=============================
=============================- -=+
============================== :==
==============================
==============================-
==============================-
==============================
------------------------------------------------------------------------
++
::::
++++
++++++++++========
+++++++++++++++++=====
++++++++++++++++++++++++=
+++++++++
+++++++++++++++++ ++=
++++++++++++++++++++++++=
++++++++++++++++++++++++++
+++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++
++==:++++++++++++++++++++++++++++++++++ ===In the first one, the camera sees the ship from its side, in the center of the image; behind it, to the left, the rogue asteroid (above, in half-light) and the great curve of the lighthouse asteroid (below) peek out, and to the right, the strip toward which it is descending, with one of its beacons. In the second one, the elongated outline of the ship rests on the parallelogram of the strip, which fills the lower half of the image with beacons at its corners; at the top right, in the distance, the lighthouse dome can be made out. It is not an image to frame, but each character is the result of a model matrix taken from a scene graph, a view computed from an animated pose, a perspective projection, a clipping, a rasterization with a z-buffer and a Blinn-Phong calculation with two lights. To get color images, just call draw with more resolution and pass the result to save_ppm:
animate(nodes, 6.0)
large_image, _, _ = draw(nodes, current_camera(nodes), 144, 40)
save_ppm(large_image, "final_frame.ppm")Finally, ray picking, on that same final frame. We project the center of the hull to find out at which pixel it is seen and "click" on it and on two other points:
camera = current_camera(nodes)
vp = camera["projection"] @ camera["view"]
ship_pixel = ndc_to_screen(project_point(vp, position_of(nodes, "ship")), WIDTH, HEIGHT)
print(np.round(ship_pixel[:2], 1))
for x, y in ((ship_pixel[0], ship_pixel[1]), (30.0, 16.0), (5.0, 2.0)):
name, t = pick(nodes, x, y, WIDTH, HEIGHT, camera)
print((round(float(x), 1), round(float(y), 1)), name, None if name is None else round(t, 2))The click on the projected center of the ship picks the hull, at the distance at which the ray hits its surface; the click in the lower left area gives the strip, and the one in the top left corner finds nothing: sky.
Numerical checks
A 3D program can produce a plausible image and still be wrong. These checks, made with tools from the whole course, give guarantees that an image does not:
animate(nodes, 12.0)
ship_world = world_matrix(nodes, "ship")
strip_plane = plane_from_points(B1, B2, B3)
bottom = transform_point(model_of(nodes, "hull"), [0.0, -1.0, 0.0])
print(is_rigid(ship_world), is_rigid(world_matrix(nodes, "dome")))
print(round(abs(point_plane_distance(strip_plane, bottom)), 6), np.round(bottom, 3) + 0.0)
print(np.round(transform_direction(ship_world, [0.0, 1.0, 0.0]), 4), np.round(strip_plane[0], 4))
print(round(norm(ship_pose(4.5)[1]), 6))
energy = lambda p, v: 0.5 * PROBE_MASS * v @ v - MU * PROBE_MASS / distance(p, [0.0, -10.0, 0.0])
p, v = ship_pose(1.0)[0] - np.array([0.0, 1.2, 0.0]), (ship_pose(1.05)[0] - ship_pose(0.95)[0]) / 0.1
e0 = energy(p, v)
for _ in range(180): # 9 s of falling, before the bounce
p, v = semi_implicit_euler_step(p, v, lambda p, v: gravitation(p, [0.0, -10.0, 0.0], MU, PROBE_MASS),
PROBE_MASS, DT)
print(round(e0, 2), round(energy(p, v), 2), round(100.0 * (energy(p, v) - e0) / abs(e0), 3))- The world matrices are rigid, including that of the dome, which composes four transformations (two of them rotations): no scale or deformation has slipped into the hierarchy.
- The ship has settled: its lowest point, the "bottom" vertex of the hull, is at distance 0 from the plane of the strip, exactly at the touchdown point \((11, 0, 3)\).
- And it is correctly oriented: its "up" axis coincides with the normal of the strip.
- The quaternion of the pose is still a unit quaternion in the middle of the slerp blend.
- The energy of the probe is conserved reasonably well: in 9 s of falling it deviates by less than 1%, and with no tendency to grow. It is what you would expect from the semi-implicit integrator with a step of 0.05 s; with
verlet_stepthe deviation would be much smaller.
Checklist for debugging 3D mathematics
Almost every failure of a 3D program comes down to a dozen causes. The table sorts them by the symptom they produce; in parentheses, the lesson where each one was covered.
| Symptom | Probable cause | How to check it |
|---|---|---|
| The object rotates around the world origin instead of on the spot | Order of the matrices: \(R,T\) has been written instead of \(T,R\) ("Composition of Transformations") | Apply the matrix to the point \((0, 0, 0)\): it must give the position of the object |
| The scene appears mirrored, or the rotations go the wrong way | Handedness or axis convention differs between the model and the engine ("Coordinates and Planes") | Determinant of the 3×3 block: it must be \(+1\); a \(-1\) gives away a reflection |
| Directions shift when they are transformed; the normals "wander off" | \(w\) component: \(w = 1\) has been used for a direction ("Transformation Matrices") | Transform \((0, 0, 0)\) as a direction: it must remain the zero vector |
| Everything comes out squashed against a point, or huge | The division by \(w\) is missing after the projection or after an unprojection ("Projections and Views") | Print the \(w\) of a vertex: if it is not 1, you have to divide |
| The lighting is too strong or too weak; the angles do not add up | Unnormalized vectors in a dot product ("Dot Product and Cross Product") | Print the norm of \(\hat{\mathbf{N}}\), \(\hat{\mathbf{L}}\), \(\hat{\mathbf{V}}\) |
| The object barely rotates, or rotates wildly | Degrees instead of radians ("Rotations, Translations and Scalings") | A rotation of 90 must be passed as np.radians(90.0) |
| The object gradually deforms when it rotates for a long time | Quaternion or matrix not renormalized after accumulating products ("Quaternions", "Physics Simulation") | Print the norm of the quaternion; is_orthogonal on the matrix |
| When interpolating, the object turns the long way around | The shortest-path test (\(q\) and \(-q\)) is missing ("Interpolating Rotations: Lerp, Nlerp and Slerp") | Sign of the dot product of the two quaternions |
| One rotation axis stops responding with the ship pointing straight up or down | Gimbal lock from using Euler angles as the state ("Euler Angles and Gimbal Lock") | Store the orientation as a quaternion |
| The lit faces are the back ones; the object looks "inside out" | Vertex order (winding) or flipped normals ("Representing 3D Objects") | triangle_normal of a face: it must point outward |
| The lighting is wrong only on stretched objects | Normals transformed with the model matrix instead of its inverse transpose ("Lighting and Shading") | Dot product of the normal with a transformed edge: it must be 0 |
| Black screen | The camera is looking the other way (\(+Z\) instead of \(-Z\)), the object is outside the near or far planes, or the z-buffer was initialized to 0 ("From Clip Space to the Screen: Viewport, Rasterization and Z-buffer") | Follow one vertex stage by stage; look at the count from render |
| Flickering stripes on distant surfaces | Z-fighting: near plane too close ("From Clip Space to the Screen: Viewport, Rasterization and Z-buffer") | Move the near plane farther away |
| A child moves the opposite way to its parent, or the local coordinates come out absurd | Inverse matrix where the direct one belonged (local↔world) ("Inverse Transformations and Change of Coordinate System") | Round trip: world_to_local(local_to_world(p)) must return p |
| The simulation gains energy and "blows up" | Explicit Euler, or a variable or excessive time step ("Physics Simulation") | Watch the energy; use a fixed step and the semi-implicit integrator |
| Speckled shadow points; rays that hit their own origin | Self-intersection due to rounding ("Intersections: Rays, Spheres, Triangles and Boxes", "Computer Graphics") | Move the origin of the ray a small distance along the normal |
The general rule is the one we have followed in every lesson: test each piece with a case whose result is known in advance. One point, one matrix, one result computed by hand.
Common Mistakes and Tips
- Starting with the whole program. Build it up in layers, as here: first the graph, printing positions; then the animation, printing poses; next the queries, and drawing last. If you draw first, every bug is a black screen.
- Letting scale be inherited. A parent with non-uniform scale deforms its rotated children and renders
rigid_inverseuseless. Keep the nodes' matrices rigid and apply the scale only to the mesh. - Recomputing world matrices unnecessarily. Our
world_matrixwalks the chain on every call; it is clear, but slow. A real engine computes all the matrices once per frame, from the root to the leaves, and stores them. - Mixing the physics step with the drawing rate. Here we simulate at 20 steps per second and draw at one; they are independent rates. The physics must not depend on how long drawing takes.
- Querying before updating. The queries must see the state of the current frame: first the whole graph is updated, then the questions are asked.
- Trusting the image. Add numerical checks: distances that must be zero, matrices that must be rigid, quantities that must be conserved.
- Tip. Keep a numerical log like the one in this lesson and compare it after every change to the engine. It is the cheapest way of detecting that something that used to work has stopped working.
Exercises
The extensions that follow are open-ended: they do not have a single correct solution. Each one includes a hint, and in the solutions you will find an outlined approach with a figure or two to check against.
Exercise 1. Shadows in the renderer. The event log knows that the ship is in shadow, but the rasterizer draws it lit by the lighthouse all the same. Make the image consistent with the query.
Hint: there is no need to touch the rasterizer. Before calling shade_point in the fragment shader, filter the list of lights with a shadow ray from the point, as trace_ray does. The obstacles can be the bounding spheres of the two asteroids: in_shadow already accepts a list of spheres.
Exercise 2. A camera with inertia. The follow camera is rigidly bolted to the ship and reproduces all its rotations. Make it follow smoothly: have its position chase the ideal position instead of coinciding with it.
Hint: at each step, eye = lerp(eye, ideal_eye, f). If \(f\) is a constant, the behavior depends on the time step. What expression for \(f\) as a function of \(\Delta t\) avoids that?
Exercise 3. Do the ship and the rogue asteroid collide? At the initial instant, the bounding sphere of the ship (radius 4) and the rogue asteroid (radius 5, center \((2, 8, 5)\)) have their centers less than 9 m apart. Hint: the broad phase says "maybe"; decide with a narrow phase. If you do not have a function for the distance from a point to a triangle, sample the surface of the hull with barycentric coordinates.
Solutions
Solution 1 (outline). We define a function that, given a point and its normal, returns only the lights that arrive, and use it inside fragment_shader: lights = unblocked_lights(point, normal, scene["lights"], spheres). The spheres are built every frame with position_of and the radius of the nodes asteroid and rogue. The cost is one ray per light and per fragment, reasonable with two spheres; with polygonal obstacles an acceleration structure would be needed. The code below checks it at two instants: at 1.3 s, only one light reaches the center of the ship (the star); at 10.9 s, both do.
Solution 2 (outline). With a constant \(f\), each step removes a fixed fraction of the remaining distance: with shorter steps there would be more steps per second and the camera would move faster. The correct fraction is
\[ f = 1 - e^{-k,\Delta t} \]
because then the remaining distance after a time \(T\) is \(\left(e^{-k,\Delta t}\right)^{T/\Delta t} = e^{-k,T}\), independent of the step. With \(k = 3\) s⁻¹, after one second \(e^{-3} = 5%\) of the distance remains, whether we simulate with steps of 0.05 or of 0.1 s; with a constant \(f = 0.15\), 3.9% or 19.7% would remain. For the orientation of the camera we do the same with quaternion_slerp, or recompute the look-at from the smoothed eye.
Solution 3 (outline). We take the vertices of the hull to the world, generate points on each face with barycentric weights \((i, j, n - i - j)/n\) and measure the minimum distance to the center of the asteroid. It comes out as 6.59 m, and it is reached at the point \((6.24, 3, 5.68)\) of the edge that joins the tail to the left wing: greater than the radius, 5. They do not collide: the bounding sphere of an object as elongated as the hull greatly exaggerates its size, and that is why the broad phase gives a false positive. To make the check along the whole maneuver, it is enough to repeat it at each step with the updated matrices.
def unblocked_lights(point, normal, lights, spheres):
"""Sublist of lights not blocked by any sphere, as seen from a point on a surface."""
start = np.asarray(point) + 1e-4 * np.asarray(normal)
return [light for light in lights if not in_shadow(start, light, spheres)]
for t in (1.3, 10.9):
animate(nodes, t)
lamp_world = world_matrix(nodes, "lamp")
lighthouse = {"type": "spot", "position": lamp_world[:3, 3]}
spheres = [{"center": position_of(nodes, n), "radius": nodes[n]["radius"]}
for n in ("asteroid", "rogue")]
print(t, beam_status(nodes),
len(unblocked_lights(position_of(nodes, "ship"), [0.0, 1.0, 0.0], [lighthouse, star_light], spheres)))
for dt in (0.05, 0.1):
remaining_right, remaining_wrong = 1.0, 1.0
for _ in range(round(1.0 / dt)):
remaining_right *= 1.0 - (1.0 - np.exp(-3.0 * dt))
remaining_wrong *= 1.0 - 0.15
print(dt, round(remaining_right, 4), round(remaining_wrong, 4))
animate(nodes, 0.0)
in_world = transform_mesh(model_of(nodes, "hull"), hull)
n, points = 10, []
for a, b, c in in_world["vertices"][in_world["faces"]]:
points += [(i * a + j * b + (n - i - j) * c) / n for i in range(n + 1) for j in range(n + 1 - i)]
distances = [distance(p, position_of(nodes, "rogue")) for p in points]
print(round(distance(position_of(nodes, "ship"), position_of(nodes, "rogue")), 3),
round(min(distances), 3), np.round(points[int(np.argmin(distances))], 2))Final review of the course
Look at the main loop once more. Each line rests on a module:
| Module | Core idea | Where it has appeared in the project |
|---|---|---|
| 1. Linear Algebra Fundamentals | Vectors and matrices as a language; systems, inverses, orthogonal matrices, eigenvalues | Every @ product; lerp; the inverse of \(P,V\) in picking |
| 2. Linear Transformations | A matrix is a function that moves space; homogeneous coordinates; composing and inverting | The scene graph; model_matrix; taking the axis of the lamp's beam to the world |
| 3. Geometry in 3D Space | Measuring: norm, dot and cross products, planes, distances, intersections | The cone of the beam, the shadow ray, the tangent plane of the bounce, picking, the checks |
| 4. Rotations and Orientation in 3D | Euler, axis-angle and quaternions; interpolating orientations | The pose of the ship; the slerp toward the orientation of the strip |
| 5. 3D Graphics | From the object to the pixel: meshes, view, projection, rasterization, light, textures | follow_camera, the frustum, the Bézier route, all of render |
| 6. Practical Applications | The same mathematics, in motion: pipeline, physics, VR/AR, animation | The renderer, the probe, ray_from_screen, the spline with easing |
If we had to sum up the course in four ideas, they would be these:
- A matrix is a change of coordinate system. Model, view, projection, viewport, bones, anchors: it is always the same operation, chained.
- The dot product measures and the cross product builds. Angles, projections, distances, lighting and side tests come from the first; normals, bases, areas and torques, from the second.
- Orientations are not vectors. They cannot simply be added or averaged: they are composed, and they are interpolated on a sphere.
- Every big problem is a chain of small problems that can be checked separately. Besides being a mathematical idea, it is a way of working.
Where to go from here
- A real engine (Unity, Unreal, Godot...). You will find the same matrices, quaternions and queries under other names and, in some cases, with other axis and handedness conventions: the table in "Coordinates and Planes" will serve as your translator.
- Shaders (GLSL, HLSL, WGSL). Rewriting on the GPU the vertex shader and the fragment shader of "Computer Graphics" is the natural next step; the mathematics is identical and the result runs at 60 frames per second.
- Rigid body physics. We have dealt with particles and spheres. The next step adds the inertia tensor—a symmetric matrix that is diagonalized, as in Module 1—contacts with friction and constraints (hinges, springs, ropes).
- Physically based rendering (PBR) and global illumination. Replace Blinn-Phong with models that conserve energy and follow the rays beyond the first bounce. The foundation is the intersections and dot products you already handle, plus a little probability.
- Computational geometry. Acceleration structures (BVHs, octrees), convex hulls, triangulations, collision detection between convex shapes (GJK), operations between meshes.
- Advanced animation. Dual quaternions for skinning, full-body inverse kinematics, animation blending and curves with continuous acceleration.
Conclusion
The final project has brought together in a single program what we built in parts: a scene graph with thirteen nodes and rigid matrices; an update with a fixed step that combines designed animation (a spline traveled at a controlled pace, with the orientation interpolated by slerp), procedural animation (the rotation of the lamp, the drift of an asteroid) and simulation (a probe that falls and bounces); geometric queries that decide whether the lighthouse beam reaches the ship, which objects are worth drawing and which one is under the cursor; and a renderer that turns all of it into images. And it has accompanied it with what distinguishes a reliable program from one that merely looks reliable: a numerical log and checks that can be verified.
This brings the course to an end. We began by asking what the difference is between a point and a vector, and we end with a ship that lands, lit by a lighthouse, in a scene that we know how to build, move, measure, orient, draw, simulate and animate. Along the way, the mathematics has stopped being a collection of formulas and become a toolbox: each tool solves a specific problem, they all fit together, and you have seen them work with your own numbers. mini3d is a tiny, slow engine, but it has no part that you do not understand; professional engines are enormous and extremely fast, and inside they do exactly the same thing. Now you know how to read them. The next scene is yours.
