CodeRigor

LESSON

From heightmap to mesh

Turn a grid of heights into vertices, consistently wound triangles, area-weighted normals and a lower-detail index list, then read the ground height back off the triangles.

A heightmap is a grid of numbers, and a graphics card draws triangles. This lesson builds the bridge: a vertex list and a triangle list from the heights, a normal for every vertex so the surface can be lit, a coarser triangle list for distant views, and a way to ask the mesh how high the ground is at any point. This lesson pairs with [Unity] Procedural Planets (E01 the sphere) by Sebastian Lague, linked under Watch & read. The video builds a sphere from vertices and triangle indices; your surface is a flat grid, but the bookkeeping is the same. You build six NumPy functions: vertices, triangles, normals, a lower-detail triangle list, a height query and height bands.

Start with the vertices. Sample (row, col) of the height array becomes the point (col · cell, height, row · cell): x runs to the right, y is up, and z grows as the row number grows. Store the points row by row, so the vertex of sample (row, col) has the index row · cols + col. A neighbor is found by arithmetic: right is index + 1, below is index + cols.

Each square of four samples, a quad, becomes two triangles. Call its corners v00 (top left), v01, v10 and v11 (bottom right). Split every quad along the same diagonal, v01 to v10, into (v00, v10, v01) and (v01, v10, v11). A triangle is three indices, and their order is the winding. The order matters because a face normal is the cross product (b − a) × (c − a): swap two corners and the normal changes sign, and a renderer then treats the face as seen from behind and may skip it. With the order above and z growing down the grid, both triangles of a flat quad have the normal (0, 1, 0).

One quad, two triangles
start / 3
A 3 × 3 grid of samples numbered by index. The split runs from v01 to v10, so the first quad becomes (0, 3, 1) and (1, 3, 4). Step through to see each triangle.
One quad, two triangles
A 3 × 3 grid of samples numbered by index. The split runs from v01 to v10, so the first quad becomes (0, 3, 1) and (1, 3, 4). Step through to see each triangle.

A mesh like this can be checked without looking at it. A grid of r × c samples has 2(r − 1)(c − 1) triangles. Every edge inside the grid is used by exactly two triangles, once in each direction when the winding is consistent, and every border edge by one. One flipped triangle leaves the counts untouched but uses an edge twice in the same direction.

Python
import numpy as np

def tiles(rows, cols, step=1):
    rs, cs = np.arange(0, rows - 1, step), np.arange(0, cols - 1, step)
    v00 = (rs[:, None] * cols + cs[None, :]).ravel()
    v01, v10 = v00 + step, v00 + step * cols
    v11 = v10 + step
    lower, upper = np.stack([v00, v10, v01], 1), np.stack([v01, v10, v11], 1)
    return np.stack([lower, upper], 1).reshape(-1, 3)

flat = np.array([[c, 0, r] for r in range(3) for c in range(3)])
tri = tiles(3, 3)
print(tri[:2].tolist())
for a, b, c in tri[:2]:
    print((np.cross(flat[b] - flat[a], flat[c] - flat[a]) + 0).tolist())
print([len(tiles(9, 9, s)) for s in (1, 2, 4)])

The last line is the level of detail. simplify(rows, cols, step) builds the same two triangles per quad, but the corners of a quad are step samples apart, and the indices still point into the full vertex array. On a 9 × 9 grid, steps of 1, 2 and 4 give 128, 32 and 8 triangles. The step has to divide rows − 1 and cols − 1, or the last strip of quads would hang over the edge, so any other step is a ValueError.

Smooth lighting needs one normal per vertex. For each triangle compute its cross product and add it to its three corners; normalize each corner's sum at the end. The cross product has a length of twice the triangle's area, so do not normalize before adding: a large triangle should pull the vertex normal harder than a small one.

Python
import numpy as np

v = np.array([[0, 0, 0], [4, 0, 0], [0, 0, 1], [0, 1, -1.0]])
big = np.cross(v[2] - v[0], v[1] - v[0])      # area 2, faces up
small = np.cross(v[3] - v[0], v[2] - v[0])    # area 0.5, faces sideways
unit = lambda a: a / np.linalg.norm(a)
print(unit(big + small).round(4).tolist())
print(unit(unit(big) + unit(small)).round(4).tolist())

The last function you need for a game is the height of the ground between samples. Bilinear blending is the tempting formula, but it is not the surface you drew: when the four corners are not in one plane, the mesh is two flat triangles, and the two diagonals give different heights. Find the quad with floor(x / cell), clamping so the far edge belongs to the last quad, and let u and w be the fractions of the way across it. If u + w ≤ 1 the point is in the lower triangle and its height is h00 + u (h01 − h00) + w (h10 − h00). Otherwise it is in the upper one, interpolated from v11 instead. For the heights [[0, 1], [2, 5]], the point u = w = 0.25 has the height 0.75 on the triangle and 0.875 under bilinear blending. At u = w = 0.75 the answers are 3.25 and 3.375.

Along the diagonal of one quad
Heights [[0, 1], [2, 5]], walking from the top-left sample to the bottom-right one (u = w). The mesh is two flat triangles, so the true surface has a kink at the midpoint; bilinear blending curves away from it.
Along the diagonal of one quad
Heights [[0, 1], [2, 5]], walking from the top-left sample to the bottom-right one (u = w). The mesh is two flat triangles, so the true surface has a kink at the midpoint; bilinear blending curves away from it.
Python
import numpy as np

h = np.array([[0.0, 1.0], [2.0, 5.0]])
def on_triangles(u, w):
    if u + w <= 1:
        return h[0, 0] + u * (h[0, 1] - h[0, 0]) + w * (h[1, 0] - h[0, 0])
    return h[1, 1] + (1 - u) * (h[1, 0] - h[1, 1]) + (1 - w) * (h[0, 1] - h[1, 1])

def bilinear(u, w):
    return (1 - u) * (1 - w) * h[0, 0] + u * (1 - w) * h[0, 1] + (1 - u) * w * h[1, 0] + u * w * h[1, 1]

for t in (0.25, 0.75):
    print(t, on_triangles(t, t), bilinear(t, t))

color_bands(height, levels) counts how many of the ascending levels are at or below each sample, so a sample exactly on a level joins the higher band. Levels that are empty, repeated or out of order raise a ValueError.

Expect these mistakes. Winding one triangle of each quad the wrong way gives correct counts and a dark surface. The wrong diagonal in the height query, or a bilinear blend, is invisible on a plane and wrong on a bumpy quad, so test on bumpy data. Normalizing face normals before adding them loses the area weights. A step that does not divide the grid and a level equal to a height are the edge cases.

The tests compare the normals of a tilted plane with the closed form, count triangles and edge directions, and check the height query against a brute-force search over the triangles. They do not show that the mesh looks right, and they cannot tell you which diagonal your renderer uses. If the engine splits the quads the other way, a height query built here disagrees with what is drawn, by a fraction of the height difference across the quad.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Covers building a mesh from a vertex list and triangle indices, one face of a surface at a time. The shape is a sphere, not a heightmap, but the vertices, the triangle order and the mesh bookkeeping carry over to this lesson.