We closed the previous module with a promise: we already know how to place, orient and move the objects of "Stellar Lighthouse", and now it is time to see them. But before drawing the ship we have to settle a preliminary question that we have dodged so far: what is the ship as far as the computer is concerned? For four modules it has been a point, \((8, 3, 6)\), with an orientation; at most, six loose vertices of a hull. A graphics card needs something more precise: a description of its surface. In this lesson we study how the shape of an object is described, paying special attention to the representation that dominates real-time graphics—the triangle mesh—and we equip mini3d with the functions needed to build, check and save meshes. Everything we do in the rest of the module (cameras, projections, rasterization, lighting, textures) will work on the vertices and faces we define here.

The code assumes that the functions from the previous modules (transform_points, model_matrix, spherical_to_cartesian, aabb_from_points...) and the matrix ship_orientation are already defined.

Ways of describing a shape

There is no single way of telling a computer what shape an object has. The five most common ones are:

Representation What is stored Advantages Drawbacks Typical use
Polygon mesh Vertices and the faces (polygons) that join them Very fast to draw; graphics hardware is built for it Only approximates curves; high resolution costs memory Video games, real time
Parametric surface A formula \(S(u, v)\) or a set of control points Exact, smooth curves at any scale; very compact It has to be converted into a mesh to be drawn Industrial design, modeling
Implicit surface A function \(F(x, y, z)\) that equals 0 on the surface Telling whether a point is inside is immediate; easy to combine Hard to draw directly Collisions, effects, digital sculpting
Voxels A 3D grid of full or empty cells Describes the interior too; easy to dig into or destroy Cubic memory; blocky look Modifiable terrain, medical imaging
Point cloud Loose points, with no connection between them It is what a 3D scanner produces directly There is no surface: no faces and no interior Scanning, photogrammetry

A few remarks:

  • Voxels are to a volume what pixels are to an image: a regular grid of little cubes. A grid 256 cells on a side has \(256^3 \approx 16.8\) million cells; doubling the resolution multiplies the memory by eight.
  • A point cloud is just the first column of a mesh: positions without faces. To draw it as a surface, the connectivity has to be reconstructed first.
  • Parametric and implicit surfaces are exact mathematical descriptions. We will study them in the lesson "Surface Modeling"; there we will see that, in order to be drawn, they end up being converted into meshes.

So every representation leads to the mesh. It is the one a real-time engine needs and the one that takes up the rest of the lesson.

The polygon mesh: vertices, edges and faces

A polygon mesh describes the surface of an object by means of three kinds of elements:

  • Vertices: points in space. They are the "corners" of the surface.
  • Edges: segments that join two vertices.
  • Faces: flat polygons bounded by edges. Together they form the "skin" of the object.

A mesh has two ingredients of a different nature. The geometry says where each vertex is; the topology (or connectivity) says which vertices form each face. When an object is moved or deformed, only the geometry changes: the model matrix acts on the vertices, and the faces keep joining the same ones.

Why triangles

Faces can be any polygons, but engines work almost exclusively with triangles:

  • A triangle is always flat. Three non-collinear points determine a single plane, as we saw in "Equations of Planes and Lines". Four points, in general, do not: a quadrilateral can be "bent", and then neither its normal nor its interior is well defined.
  • A triangle is always convex. It has no indentations, which makes it simpler to decide which points fall inside.
  • It is still a triangle after being transformed. Any affine transformation, and even the perspective projection, maps triangles to triangles: transforming the three vertices is enough.
  • It has barycentric coordinates. Any piece of data known at the three vertices can be spread over the interior without ambiguity.
  • Any polygon can be split into triangles. A convex polygon with \(n\) sides is divided into \(n - 2\) triangles fanning out from one of its vertices.

Modeling programs usually show quadrilaterals (quads) because they are more convenient to edit, but they are triangulated before being sent to the graphics card.

Triangle soup versus indexed mesh

The ship's hull is, in its local space, an octahedron: six vertices on the axes, \((\pm 1, 0, 0)\), \((0, \pm 1, 0)\), \((0, 0, \pm 1)\), and eight triangular faces. How should we store it?

Triangle soup. The most direct way: a list of triangles, each with its three vertices written out in full. Eight triangles, 24 vertices. It is simple, but each vertex of the octahedron belongs to four faces and is repeated four times. What is more, nothing says that two triangles share a corner: if one copy is moved and the others are not, the mesh comes apart.

Indexed mesh. Two lists are stored:

  • a vertex list, with each vertex appearing only once;
  • an index list: each face is three integers, the positions of its vertices in the previous list.
graph LR
    subgraph Indices
        C0["face 0: 0, 2, 4"]
        C1["face 1: 4, 2, 1"]
    end
    subgraph Vertices
        V0["0: (1, 0, 0)"]
        V1["1: (-1, 0, 0)"]
        V2["2: (0, 1, 0)"]
        V4["4: (0, 0, 1)"]
    end
    C0 --> V0
    C0 --> V2
    C0 --> V4
    C1 --> V4
    C1 --> V2
    C1 --> V1

Faces 0 and 1 share vertices 2 and 4: they share an edge, and that fact is written down in the indices.

Triangle soup Indexed mesh
Vertices stored 3 per triangle Each one once
Connectivity Lost Explicit in the indices
Transforming the object The calculation is repeated for every copy Once per vertex
Octahedron (8 faces) 24 vertices · 12 bytes = 288 bytes 6 · 12 + 24 · 2 = 120 bytes
Sphere with 960 faces 2880 · 12 = 34,560 bytes 482 · 12 + 2880 · 2 = 11,544 bytes

(We have assumed three 4-byte float values per vertex and 2-byte indices.) In a smooth mesh each vertex is shared by about six faces, so the indexed version takes up roughly a third of the space and requires transforming a sixth of the vertices.

In mini3d a mesh will be a dictionary with two NumPy arrays:

import numpy as np

def create_mesh(vertices, faces):
    """Indexed mesh: dictionary with the vertices (n x 3) and the faces (m x 3, indices)."""
    return {"vertices": np.asarray(vertices, dtype=float),
            "faces": np.asarray(faces, dtype=int)}

def octahedron_mesh():
    """Unit octahedron: 6 vertices on the axes and 8 triangular faces."""
    vertices = [[1, 0, 0], [-1, 0, 0],      # 0: +X   1: -X
                [0, 1, 0], [0, -1, 0],      # 2: +Y   3: -Y
                [0, 0, 1], [0, 0, -1]]      # 4: +Z   5: -Z
    faces = [[0, 2, 4], [4, 2, 1], [1, 2, 5], [5, 2, 0],    # upper half
             [4, 3, 0], [1, 3, 4], [5, 3, 1], [0, 3, 5]]    # lower half
    return create_mesh(vertices, faces)

def triangle_soup(mesh):
    """Unrolls the mesh: array (m, 3, 3) with the three vertices of each face."""
    return mesh["vertices"][mesh["faces"]]

octahedron = octahedron_mesh()
print(octahedron["vertices"].shape, octahedron["faces"].shape)
print(octahedron["vertices"][octahedron["faces"][0]])
print(triangle_soup(octahedron).shape)
(6, 3) (8, 3)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
(8, 3, 3)

The expression vertices[faces] uses NumPy's advanced indexing: it replaces each index with the corresponding row. Applied to one face it returns its three vertices; applied to the whole table of faces, the complete soup. Going from an indexed mesh to a soup is therefore a one-liner; the way back (detecting the repeated vertices and merging them) is considerably more laborious.

Vertex order: front face and back face

The three indices of a face are not written in just any order. A triangle has two sides, and the order of its vertices (its winding) says which one is the outside. The convention in mini3d, which is the usual one in OpenGL, is:

The front face of a triangle is the one from which its vertices are seen running counterclockwise.

There are two possible directions of travel. The three cyclic permutations \((0, 2, 4)\), \((2, 4, 0)\) and \((4, 0, 2)\) describe the same triangle with the same orientation; swapping two indices, \((0, 4, 2)\), flips it over.

Let us check it with face 0 of the octahedron, with vertices \(A = (1, 0, 0)\), \(B = (0, 1, 0)\) and \(C = (0, 0, 1)\). It is the face in the first octant. Looking at it from outside—from a point such as \((2, 2, 2)\), with the Y axis pointing up—\(A\) is at the bottom right, \(B\) at the top and \(C\) at the bottom left: the path \(A \to B \to C\) is counterclockwise. All eight faces of octahedron_mesh are written this way, counterclockwise as seen from the outside.

This order has two practical consequences:

  • It determines the normal, as we will see in the next section.
  • It lets us discard half of the triangles. In a closed, opaque object, the faces that turn their back on the camera are always hidden by the ones facing it. If the engine can tell them apart by the winding with which they appear on screen, it can skip drawing the back ones. We will implement this technique, backface culling, in the lesson "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer".

Face normals

The normal of a face is the unit vector perpendicular to it that points toward its front side. We have known how to compute it since "Dot Product and Cross Product": for a triangle \(ABC\),

\[ \hat{\mathbf{n}} = \frac{(B - A) \times (C - A)}{\lVert (B - A) \times (C - A) \rVert} \]

The right-hand rule of the cross product and the counterclockwise convention fit together: if the fingers follow the path \(A \to B \to C\), the thumb points along the normal, toward the observer who sees the triangle from the front. Remember, too, that the norm of that cross product, before normalizing, is twice the area of the triangle.

Example. For face 0 of the octahedron: \((B - A) \times (C - A) = (-1, 1, 0) \times (-1, 0, 1) = (1, 1, 1)\). The normal is \((1, 1, 1)/\sqrt{3} \approx (0.577, 0.577, 0.577)\), which points toward the first octant: outward. The area is \(\sqrt{3}/2 \approx 0.866\).

With NumPy all the faces are computed at once:

def face_normals(mesh):
    """Unit normal of each face (m x 3), according to the counterclockwise order of its vertices."""
    a, b, c = (mesh["vertices"][mesh["faces"][:, i]] for i in range(3))
    normals = np.cross(b - a, c - a)
    return normals / np.linalg.norm(normals, axis=1, keepdims=True)

def face_areas(mesh):
    """Area of each face: half the norm of the cross product."""
    a, b, c = (mesh["vertices"][mesh["faces"][:, i]] for i in range(3))
    return 0.5 * np.linalg.norm(np.cross(b - a, c - a), axis=1)

def transform_mesh(m, mesh):
    """New mesh with the vertices transformed by the 4x4 matrix m (same faces)."""
    return create_mesh(transform_points(m, mesh["vertices"]), mesh["faces"])

hull_model = model_matrix([8.0, 3.0, 6.0], ship_orientation, (4.0, 1.0, 2.0))
hull = transform_mesh(hull_model, octahedron)

print(hull["vertices"])
print(np.round(face_normals(hull)[:4], 4))
print(np.round(face_areas(hull)[:4], 4), round(face_areas(hull).sum(), 4))
[[10.4  3.   2.8]
 [ 5.6  3.   9.2]
 [ 8.   4.   6. ]
 [ 8.   2.   6. ]
 [ 9.6  3.   7.2]
 [ 6.4  3.   4.8]]
[[ 0.4801  0.8729  0.0873]
 [ 0.2182  0.8729  0.4364]
 [-0.4801  0.8729 -0.0873]
 [-0.2182  0.8729 -0.4364]]
[4.5826 4.5826 4.5826 4.5826] 36.6606

In face_normals, faces[:, i] is column \(i\) of the index table (the first vertex of every face, the second...), so a, b and c are three arrays with one row per face. np.cross works row by row, and keepdims=True keeps the shape needed to divide each row by its norm.

transform_mesh applies the hull's model matrix, \(T(8, 3, 6),N,S(4, 1, 2)\), and touches only the geometry. The resulting vertices are old acquaintances, in this order: right wing, left wing, top, bottom, nose and tail. The first normal, the one for the face (right wing, top, nose), is the one we computed in "Dot Product and Cross Product". The total surface area of the hull is 36.66 m², eight equal faces of \(\sqrt{21} \approx 4.58\) m².

The hull's normals were obtained by recomputing them from the already transformed vertices. They would not be obtained by transforming the octahedron's normals with the model matrix: with a non-uniform scaling such as \(S(4, 1, 2)\), normals do not transform the same way as points. We will prove it in the lesson "Lighting and Shading".

Vertex normals

A mesh is a faceted approximation of a surface that we often want to look smooth. The face normal is constant over the whole triangle and changes abruptly on crossing over to its neighbor: it gives the facets away. To disguise them, a normal is assigned to each vertex, representing the orientation of the "ideal" smooth surface at that point. Its role in lighting is the subject of the lesson "Lighting and Shading"; here we are only concerned with how to compute it.

The standard recipe is to average the normals of the faces that share the vertex. There are several ways of weighting that average:

Weighting Weight of each face Comment
Uniform 1 Simple, but many small triangles outweigh a single large one
By area The area of the face Large faces count for more; it comes for free from the cross product
By angle The angle of the face at that vertex The most robust: it does not depend on how the surface was triangulated

Area weighting is the most widely used thanks to a happy coincidence: the unnormalized cross product, \((B - A) \times (C - A)\), has the direction of the normal and a length equal to twice the area. It is enough to add up those unnormalized vectors at each vertex and normalize at the end:

\[ \hat{\mathbf{n}}v = \frac{\sum{f ,\ni, v} \mathbf{n}f}{\left\lVert \sum{f ,\ni, v} \mathbf{n}_f \right\rVert} \qquad \text{with } \mathbf{n}_f = (B - A) \times (C - A) \text{ for each face } f \text{ that contains } v \]

Example. Vertex 2 of the octahedron, \((0, 1, 0)\), belongs to the four upper faces, whose cross products are \((1, 1, 1)\), \((-1, 1, 1)\), \((-1, 1, -1)\) and \((1, 1, -1)\). The sum is \((0, 4, 0)\) and, normalized, \((0, 1, 0)\): the normal points up, as was to be expected at the top.

def vertex_normals(mesh):
    """Unit normal of each vertex: average of the normals of its faces, weighted by area."""
    v, faces = mesh["vertices"], mesh["faces"]
    a, b, c = (v[faces[:, i]] for i in range(3))
    area_normals = np.cross(b - a, c - a)           # direction: normal; length: 2 * area
    total = np.zeros_like(v)
    for i in range(3):
        np.add.at(total, faces[:, i], area_normals)  # each face contributes to its three vertices
    return total / np.linalg.norm(total, axis=1, keepdims=True)

print(np.round(vertex_normals(hull), 4) + 0.0)
[[ 0.6  0.  -0.8]
 [-0.6  0.   0.8]
 [ 0.   1.   0. ]
 [ 0.  -1.   0. ]
 [ 0.8  0.   0.6]
 [-0.8  0.  -0.6]]

np.add.at(total, indices, values) adds each row of values to the row of total given by its index, accumulating correctly when an index is repeated (a plain total[indices] += values would not).

The result reads very cleanly: the normals at the hull's vertices are \(\pm\mathbf{n}_1\), \(\pm\mathbf{n}_2\) and \(\pm\mathbf{n}_3\), the ship's axes. The right wing tip "looks" toward the ship's right, the top looks up and the nose looks forward.

A word of warning: vertex normals smooth, and that is not always what we want. On a cube the edges must look sharp. Since a vertex in the list can carry only one normal, the solution is to duplicate the vertices: each corner of the cube appears three times, once for each face that touches it, with that face's normal. A "sharp-edged" cube thus has 24 vertices instead of 8.

Euler's formula and closed meshes

In any polyhedron without holes—a cube, an octahedron, a faceted sphere—the numbers of vertices \(V\), edges \(E\) and faces \(F\) satisfy a relation discovered by Euler:

\[ V - E + F = 2 \]

Mesh \(V\) \(E\) \(F\) \(V - E + F\)
Octahedron 6 12 8 2
Cube (square faces) 8 12 6 2
Triangulated cube 8 18 12 2

When the cube is triangulated, each square face gains a diagonal (one more edge) and is split in two (one more face): \(-1 + 1 = 0\), so the sum does not change. The same happens with any deformation: moving the vertices does not alter the count. The formula speaks of the topology, not of the geometry. That is why the value 2 characterizes all "sphere-shaped" surfaces; a doughnut-shaped mesh (a torus) gives 0, and in general \(V - E + F = 2 - 2g\), where \(g\) is the number of handles or through-holes.

Consequences for triangle meshes

A mesh is closed (or watertight) if it has no boundary: each edge is shared by exactly two faces. In a closed triangle mesh, each face has 3 edges and each edge belongs to 2 faces, so \(3F = 2E\). Substituting \(E = \tfrac{3}{2}F\) into Euler's formula:

\[ V - \tfrac{3}{2}F + F = 2 \quad\Longrightarrow\quad F = 2V - 4 \qquad E = 3V - 6 \]

A closed triangle mesh has approximately twice as many faces as vertices and three times as many edges. For the octahedron: \(2 \cdot 6 - 4 = 8\) faces and \(3 \cdot 6 - 6 = 12\) edges.

Checking a mesh

Euler's formula and the edge condition provide a cheap test that a mesh is well built. In addition, if the orientation is consistent, the two faces that share an edge traverse it in opposite directions: if one face contains the ordered pair \((i, j)\), its neighbor contains \((j, i)\). In the octahedron, face 0, \((0, 2, 4)\), traverses the edge as \(2 \to 4\), and face 1, \((4, 2, 1)\), traverses it as \(4 \to 2\).

def edges(mesh):
    """Set of edges (pairs of indices sorted from smaller to larger) of the mesh."""
    result = set()
    for a, b, c in mesh["faces"]:
        for i, j in ((a, b), (b, c), (c, a)):
            result.add((min(i, j), max(i, j)))
    return result

def euler_characteristic(mesh):
    """V - E + F."""
    return len(mesh["vertices"]) - len(edges(mesh)) + len(mesh["faces"])

def is_closed(mesh):
    """True if each edge is traversed by exactly two faces, once in each direction."""
    traversed = {}
    for a, b, c in mesh["faces"]:
        for i, j in ((a, b), (b, c), (c, a)):
            traversed[(int(i), int(j))] = traversed.get((int(i), int(j)), 0) + 1
    return all(n == 1 and traversed.get((j, i), 0) == 1
               for (i, j), n in traversed.items())

print(len(edges(octahedron)), euler_characteristic(octahedron), is_closed(octahedron))

punctured = create_mesh(octahedron["vertices"], octahedron["faces"][1:])    # one face missing
flipped = create_mesh(octahedron["vertices"],
                      [[0, 4, 2]] + octahedron["faces"][1:].tolist())       # one face reversed
print(euler_characteristic(punctured), is_closed(punctured))
print(euler_characteristic(flipped), is_closed(flipped))
12 2 True
1 False
2 False

For the octahedron with a face missing, the formula fails (\(6 - 12 + 7 = 1\)) and there are three boundary edges. The mesh with a flipped face is more treacherous: Euler's formula holds, because it does not distinguish orientations, but is_closed detects that some edges are traversed twice in the same direction. That face would have its normal pointing inward and would disappear when back faces are culled.

Primitives in code: cube and UV sphere

Primitives are the basic shapes that every engine can generate without needing a file: cubes, spheres, cylinders. We already have the octahedron; we add two more.

The cube

Eight vertices \((\pm 1, \pm 1, \pm 1)\) and six square faces, each divided into two triangles by a diagonal. The delicate part is writing each square counterclockwise as seen from outside.

def cube_mesh():
    """Cube of side 2 centered at the origin: 8 vertices and 12 triangles."""
    vertices = [[x, y, z] for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)]
    quads = [[4, 6, 7, 5],    # +X face
             [0, 1, 3, 2],    # -X face
             [2, 3, 7, 6],    # +Y face
             [0, 4, 5, 1],    # -Y face
             [1, 5, 7, 3],    # +Z face
             [0, 2, 6, 4]]    # -Z face
    faces = []
    for a, b, c, d in quads:                  # each square, two triangles
        faces += [[a, b, c], [a, c, d]]
    return create_mesh(vertices, faces)

cube = cube_mesh()
print(np.round(face_normals(cube)[::2], 3) + 0.0)
[[ 1.  0.  0.]
 [-1.  0.  0.]
 [ 0.  1.  0.]
 [ 0. -1.  0.]
 [ 0.  0.  1.]
 [ 0.  0. -1.]]

The list comprehension numbers the vertices like a binary counter: the vertex with index \(4i + 2j + k\) has \(x\), \(y\), \(z\) equal to \(-1\) or \(+1\) depending on whether \(i\), \(j\), \(k\) are 0 or 1. So vertex 5 (\(101\) in binary) is \((1, -1, 1)\). The square \((a, b, c, d)\) is split into \((a, b, c)\) and \((a, c, d)\), which keep the winding. The normals (every other one, because the two triangles of a square share a normal) confirm that all six faces look outward.

The UV sphere

A sphere can be built like a globe: we draw parallels (circles of constant latitude) and meridians (semicircles from pole to pole), and place vertices where they cross. The spherical coordinates from "Coordinates and Planes" give the position of each one: the azimuth runs around the meridians and the elevation drops from \(+90°\) at the north pole to \(-90°\) at the south pole.

With parallels bands from pole to pole and meridians wedges:

  • There are parallels − 1 intermediate rings of meridians vertices, plus the two poles: \(V = m,(p - 1) + 2\).
  • The bands that touch a pole are triangle fans: \(m\) triangles each.
  • The other bands are made up of \(m\) quadrilaterals, each split into two triangles.
  • In total, \(F = 2m + 2m,(p - 2) = 2m,(p - 1)\) faces. The relation \(F = 2V - 4\) holds, as it should.
def sphere_mesh(radius, parallels, meridians):
    """UV sphere: `parallels` bands from pole to pole and `meridians` wedges around the Y axis."""
    vertices = [[0.0, radius, 0.0]]                             # north pole
    for i in range(1, parallels):                               # intermediate rings
        elevation = np.pi / 2.0 - np.pi * i / parallels
        for j in range(meridians):
            azimuth = 2.0 * np.pi * j / meridians
            vertices.append(spherical_to_cartesian(radius, azimuth, elevation))
    vertices.append([0.0, -radius, 0.0])                        # south pole
    south = len(vertices) - 1

    def index(i, j):                                            # vertex j of ring i
        return 1 + (i - 1) * meridians + j % meridians

    faces = []
    for j in range(meridians):                                  # the two caps
        faces.append([0, index(1, j), index(1, j + 1)])
        faces.append([south, index(parallels - 1, j + 1), index(parallels - 1, j)])
    for i in range(1, parallels - 1):                           # intermediate bands
        for j in range(meridians):
            a, b = index(i, j), index(i, j + 1)
            c, d = index(i + 1, j), index(i + 1, j + 1)
            faces += [[a, c, d], [a, d, b]]
    return create_mesh(vertices, faces)

for name, m in (("cube", cube), ("sphere 4x8", sphere_mesh(10.0, 4, 8)),
                ("sphere 16x32", sphere_mesh(10.0, 16, 32))):
    print(name, len(m["vertices"]), len(edges(m)), len(m["faces"]),
          euler_characteristic(m), is_closed(m))

asteroid = sphere_mesh(10.0, 16, 32)
print(round(face_areas(asteroid).sum(), 1), round(4.0 * np.pi * 10.0 ** 2, 1))
deviation = vertex_normals(asteroid) - asteroid["vertices"] / 10.0
print(round(float(np.abs(deviation).max()), 4))
cube 8 18 12 2 True
sphere 4x8 26 72 48 2 True
sphere 16x32 482 1440 960 2 True
1246.6 1256.6
0.0329

The key detail of the function is j % meridians: the last wedge connects back to the first meridian, and that is how the sphere closes up. All three meshes pass the Euler and closure tests.

The last two lines measure the quality of the approximation with a sphere of radius 10, the size of the lighthouse asteroid. The area of its 960 triangles is 1246.6 m², 0.8% less than the exact area \(4\pi r^2 = 1256.6\) m²: the mesh always runs inside the sphere. And the ideal normal of a sphere at a point \(\mathbf{p}\) is \(\mathbf{p}/r\) (the radius is perpendicular to the surface); the vertex normals computed by averaging faces deviate from it by less than 0.033 in each component. The average does a good job of reconstructing the smooth surface that the mesh approximates.

The UV sphere has a well-known flaw: the triangles bunch up and become thin near the poles. There are alternatives with more uniform triangles, such as the icosphere, which is obtained by subdividing an icosahedron; or, closer to home, subdividing our octahedron and pushing the new vertices out onto the sphere.

Per-vertex attributes

So far a vertex has been just a position. In a real engine it is a small data record, each item of which is called an attribute:

Attribute Type What it is for
Position 3 numbers \((x, y, z)\), local space Where the vertex is
Normal Unit vector \((n_x, n_y, n_z)\) Orientation of the surface; used in lighting
Color 3 or 4 numbers (RGB or RGBA) The vertex's own tint
Texture coordinates 2 numbers \((u, v)\) Which point of an image is stuck onto that vertex

All the attributes share the same index: vertex 2 is row 2 of the table of positions, of the table of normals and of the table of colors. In mini3d it is enough to add entries to the dictionary:

hull["normals"] = vertex_normals(hull)
hull["colors"] = np.array([[0.9, 0.2, 0.2], [0.2, 0.9, 0.2],        # wings: red and green
                           [0.8, 0.8, 0.8], [0.3, 0.3, 0.3],        # light top, dark bottom
                           [1.0, 1.0, 1.0], [1.0, 0.6, 0.0]])       # white nose, orange tail
print(sorted(hull), hull["colors"].shape)
['colors', 'faces', 'normals', 'vertices'] (6, 3)

(The navigation lights follow nautical and aeronautical tradition: red on one side and green on the other.) Two rules govern attributes:

  • Inside the triangle, they are interpolated. Attributes are only known at the vertices; for interior points the three values are blended using the barycentric coordinates. We will do so in "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer".
  • If an attribute must be discontinuous, the vertex is duplicated. This is the case of the sharp-edged cube, and of texture seams, which we will see in "Texture Coordinates and Mapping". Two vertices can coincide in position and differ in another attribute: to the engine they are different vertices.

The OBJ format

Complex meshes are not written by hand: an artist creates them in a modeling program and they are exported to a file. The simplest and most universal format is Wavefront OBJ, a text file in which each line begins with a keyword:

Line Meaning
# text Comment
v x y z Position of a vertex
vn x y z A normal
vt u v A pair of texture coordinates
f i j k ... A face: indices of its vertices

Three details worth knowing:

  • Indices start at 1, not at 0. This is the number one source of errors when reading an OBJ.
  • A face can have more than three vertices; it has to be triangulated on reading.
  • Each vertex of a face can be written as i/j/k: position index, texture coordinate index and normal index, with independent tables. For our minimal reader it is enough to keep the first one.
def write_obj(mesh):
    """Text in minimal OBJ format: lines 'v x y z' and 'f i j k' (indices from 1)."""
    lines = ["# mesh exported by mini3d"]
    lines += ["v {:g} {:g} {:g}".format(*v) for v in mesh["vertices"]]
    lines += ["f {} {} {}".format(*(face + 1)) for face in mesh["faces"]]
    return "\n".join(lines) + "\n"

def read_obj(text):
    """Reads a minimal OBJ (positions and faces only). Triangulates faces with more than 3 sides."""
    vertices, faces = [], []
    for line in text.splitlines():
        parts = line.split()
        if not parts or parts[0].startswith("#"):
            continue
        if parts[0] == "v":
            vertices.append([float(x) for x in parts[1:4]])
        elif parts[0] == "f":
            indices = [int(p.split("/")[0]) - 1 for p in parts[1:]]    # 'i/j/k' -> i
            for k in range(1, len(indices) - 1):                       # triangle fan
                faces.append([indices[0], indices[k], indices[k + 1]])
    return create_mesh(vertices, faces)

text = write_obj(hull)
print(text)

loaded = read_obj(text)
print(np.allclose(loaded["vertices"], hull["vertices"]),
      np.array_equal(loaded["faces"], hull["faces"]))

panel = read_obj("v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1/1/1 2/2/1 3/3/1 4/4/1\n")
print(panel["faces"].tolist())
# mesh exported by mini3d
v 10.4 3 2.8
v 5.6 3 9.2
v 8 4 6
v 8 2 6
v 9.6 3 7.2
v 6.4 3 4.8
f 1 3 5
f 5 3 2
f 2 3 6
f 6 3 1
f 5 4 1
f 2 4 5
f 6 4 2
f 1 4 6

True True
[[0, 1, 2], [0, 2, 3]]

The face [0, 2, 4] is written as f 1 3 5 and is read back as [0, 2, 4]. The last example is a square panel with indices in i/j/k format: only the positions are read, and the quadrilateral is split into a fan of two triangles. To work with real files, open(path).read() and open(path, "w").write(text) are all you need.

The bounding box of a mesh

In "Intersections: Rays, Spheres, Triangles and Boxes" we saw that engines wrap each object in a simple volume in order to rule out tests quickly. With the mesh in hand, computing it is immediate, because the bounding volume of a mesh is that of its vertices: the faces are flat and do not stick out beyond them.

print(aabb_from_points(octahedron["vertices"]))     # in local space
print(aabb_from_points(hull["vertices"]))           # in the world
(array([-1., -1., -1.]), array([1., 1., 1.]))
(array([5.6, 2. , 2.8]), array([10.4,  4. ,  9.2]))

The box in local space is computed only once, when the mesh is loaded; the one in the world changes every time the object moves or rotates, and has to be recomputed (or derived from the local one).

Common Mistakes and Tips

  • Mixing windings. A single face written clockwise is enough for its normal to point inward and for the face to "disappear" when back faces are culled. Run is_closed on the meshes you generate in code.
  • Forgetting that OBJ counts from 1. On reading you subtract 1 and on writing you add 1. If an imported model shows up as a tangle of triangles, this is almost certainly why.
  • Normalizing before adding when computing vertex normals (when you want area weighting). Face normals that are already normalized give the uniform average, which is a different weighting.
  • Trusting area weighting on unevenly distributed meshes. In the triangulated cube, the corners that a face's diagonal passes through receive two triangles from that face and the others only one, and the vertex normal drifts off. Angle weighting does not have that problem.
  • Expecting sharp edges with shared vertices. A vertex carries a single normal. For a cube with crisp edges, vertices have to be duplicated.
  • Degenerate triangles. Three collinear vertices (or two coincident ones) give a zero cross product and a division by zero when normalizing. In the UV sphere we avoid them by treating the poles as single vertices.
  • Transforming normals as if they were points. With non-uniform scalings this is wrong; for now, recompute the normals from the transformed vertices.
  • Tip. Always store meshes in local space, centered and at unit size, and leave the size, orientation and position to the model matrix: the same mesh then serves for a thousand different objects.

Exercises

Exercise 1. The roof of the lighthouse is a square-based pyramid with these vertices (local space): \(P_0 = (1, 0, 1)\), \(P_1 = (1, 0, -1)\), \(P_2 = (-1, 0, -1)\), \(P_3 = (-1, 0, 1)\) and the top vertex \(P_4 = (0, 2, 0)\).

a) Write the six triangular faces (four lateral ones and two for the base) with counterclockwise orientation as seen from outside. b) Compute by hand the normal and the area of the lateral face \((P_0, P_1, P_4)\). c) Count \(V\), \(E\) and \(F\), and check Euler's formula and the relation \(F = 2V - 4\).

Exercise 2. Compute by hand the normal at the top vertex \(P_4\) of the pyramid with area weighting. Before computing, what result do you expect by symmetry?

Exercise 3. To represent an asteroid we want a UV sphere with about 5000 triangles and twice as many meridians as parallels. a) What values of parallels and meridians should be used? b) How many vertices and edges will it have? c) Check it with sphere_mesh and work out how much memory the indexed mesh saves compared with the triangle soup (12-byte positions; 2-byte indices).

Solutions

Solution 1.

a) For the lateral faces we go along the base and finish at the apex. Seen from the \(+X\) side, with Y pointing up, \(P_0\) (with \(z = 1\)) is on the left and \(P_1\) (with \(z = -1\)) on the right, so \(P_0 \to P_1 \to P_4\) is counterclockwise. The four lateral faces are \((0, 1, 4)\), \((1, 2, 4)\), \((2, 3, 4)\) and \((3, 0, 4)\). The base is viewed from below, which reverses the direction: \((0, 2, 1)\) and \((0, 3, 2)\).

b) \((P_1 - P_0) \times (P_4 - P_0) = (0, 0, -2) \times (-1, 2, -1)\):

\[ \big(0 \cdot (-1) - (-2) \cdot 2,\ \ (-2)(-1) - 0 \cdot (-1),\ \ 0 \cdot 2 - 0 \cdot (-1)\big) = (4, 2, 0) \]

Its norm is \(\sqrt{20} \approx 4.472\). The normal is \((4, 2, 0)/\sqrt{20} \approx (0.894, 0.447, 0)\): it points toward \(+X\) and slightly upward, that is, outward. The area is \(\sqrt{20}/2 = \sqrt{5} \approx 2.236\).

c) \(V = 5\). Edges: 4 on the base, 4 going up to the apex and 1 diagonal of the base, \(E = 9\). \(F = 6\). Then \(5 - 9 + 6 = 2\) ✓ and \(2V - 4 = 6 = F\) ✓ (also \(3V - 6 = 9 = E\)).

Solution 2. By symmetry, the pyramid looks identical from its four sides, so the normal at the apex must be vertical: \((0, 1, 0)\).

The unnormalized cross products of the four lateral faces are \((4, 2, 0)\), \((0, 2, -4)\), \((-4, 2, 0)\) and \((0, 2, 4)\) (each one is obtained by rotating the previous one 90° about Y). Their sum is \((0, 8, 0)\), which normalized gives \((0, 1, 0)\) ✓. The two faces of the base do not touch \(P_4\) and play no part.

Typical mistake: including in the average all the faces of the mesh, and not just the ones that contain the vertex.

Solution 3.

a) With \(m = 2p\): \(F = 2m,(p - 1) = 4p,(p - 1) \approx 5000\), that is, \(p,(p - 1) \approx 1250\). Since \(36 \cdot 35 = 1260\), we take \(p = 36\) and \(m = 72\): \(F = 2 \cdot 72 \cdot 35 = 5040\) triangles.

b) \(V = m,(p - 1) + 2 = 72 \cdot 35 + 2 = 2522\). By the formula for closed meshes, \(E = 3V - 6 = 7560\) (and, indeed, \(2V - 4 = 5040\)).

c)

pyramid = create_mesh([[1, 0, 1], [1, 0, -1], [-1, 0, -1], [-1, 0, 1], [0, 2, 0]],
                      [[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [0, 2, 1], [0, 3, 2]])
print(np.round(face_normals(pyramid)[0], 4), round(face_areas(pyramid)[0], 4))
print(len(pyramid["vertices"]), len(edges(pyramid)), len(pyramid["faces"]),
      euler_characteristic(pyramid), is_closed(pyramid))
print(np.round(vertex_normals(pyramid)[4], 4) + 0.0)

rock = sphere_mesh(10.0, 36, 72)
v, f = len(rock["vertices"]), len(rock["faces"])
print(v, len(edges(rock)), f, is_closed(rock))
print(f * 3 * 12, v * 12 + f * 3 * 2)
[0.8944 0.4472 0.    ] 2.2361
5 9 6 2 True
[0. 1. 0.]
2522 7560 5040 True
181440 60504

The first three lines confirm Exercises 1 and 2. The triangle soup would take up 181,440 bytes and the indexed mesh 60,504: exactly a third.

Conclusion

To a real-time engine, a 3D object is a triangle mesh: a list of vertices and a list of indices that groups them in threes. The counterclockwise order of those indices marks the front face and fixes the direction of each face's normal, which is obtained with a cross product; averaging the normals of the neighboring faces, weighted by area, gives a normal at each vertex that describes the smooth surface the mesh approximates. Euler's formula, \(V - E + F = 2\), and the rule that each edge belongs to two faces that traverse it in opposite directions let us verify that a mesh is closed and consistently oriented. We have also seen that a vertex can carry more attributes than its position, we have generated an octahedron, a cube and a UV sphere in code, and we have read and written the OBJ format. mini3d gains create_mesh, octahedron_mesh, cube_mesh, sphere_mesh, triangle_soup, transform_mesh, face_normals, face_areas, vertex_normals, edges, euler_characteristic, is_closed, write_obj and read_obj.

We have the ship's vertices in the world, but a picture is not taken "from the world": it is taken from a camera. The first step in drawing the mesh is to express its vertices relative to whoever is looking at it. That is the subject of the next lesson, "Coordinate Spaces and the View Matrix", where we will walk through the chain of coordinate systems that each vertex passes through and build, at last, the view matrix and the famous look-at function that we announced in Module 2.

© Copyright 2026. All rights reserved