With lighting, the ship has volume; but its hull is still a uniform gray, with no plates, no rivets, no registration number. Adding that detail with geometry would require millions of triangles. The solution, as old as it is effective, is to stick an image onto the surface, just as a box is covered with wrapping paper. That image is a texture, and the mathematical problem is twofold: deciding which point of the image corresponds to each point of the mesh (the mapping, by means of UV coordinates) and reading the image at that point without jagged edges or flickering appearing (sampling and filtering). In this lesson, the last of the module, we solve both and see how the same idea serves to store in an image not only colors, but also normals or the environment that surrounds the scene.

The code assumes that the functions from the previous lessons (dot_product, normalize, triangle_normal, reflect, direction_to, cartesian_to_cylindrical, cartesian_to_spherical, to_homogeneous, perspective_matrix, ndc_to_screen, rasterize_triangle, interpolate_attribute, interpolate_with_perspective, diffuse_light...) and the scene data are already defined: ship and lamp.

Textures and UV coordinates

A texture is an image: a rectangular grid of values. Each cell is called a texel (texture element), by analogy with the pixel, which is a cell of the screen. A texel usually stores an RGB color, but it can store any piece of data.

To refer to a point of the texture regardless of its resolution we use texture coordinates \((u, v)\), which are normalized: \(u\) runs across the image from left to right and \(v\) from bottom to top, both from 0 to 1. So \((0.5, 0.5)\) is the center of the image, whether it is 64 or 4096 texels on a side.

Convention Origin \((0, 0)\) Where it is used
\(v\) up Bottom left corner OpenGL; it is the one in mini3d
\(v\) down Top left corner Direct3D, Vulkan, Metal; almost all image formats

Going from one to the other means replacing \(v\) with \(1 - v\). A model whose texture appears upside down almost always has this problem.

In mini3d a texture is a NumPy array of shape (height, width) (grayscale) or (height, width, 3) (color), in which row 0 is the bottom one: texture[row, column], with the row associated with \(v\) and the column with \(u\). Be careful when printing it: NumPy shows row 0 at the top.

UV as a vertex attribute: interpolation and perspective

UV coordinates are one more vertex attribute, as we announced in "Representing 3D Objects": each vertex of the mesh carries, along with its position and its normal, the point of the texture that corresponds to it. For the interior points of each triangle, the UVs are interpolated with the barycentric coordinates, like any other attribute. A triangle of the mesh thus "cuts out" a triangle of the image and stretches it over itself.

In "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer" we showed that this interpolation must be perspective-corrected (interpolating \(u/w\), \(v/w\) and \(1/w\)) and we promised to show the effect with a checkerboard. The time has come. An 8 m billboard next to the strip recedes from the camera: its left edge is at a depth of 2 m and its right edge at 10 m. Its texture is a checkerboard of 8 × 4 squares. We draw it twice with the rasterizer, once with linear interpolation on screen and once with correction.

import numpy as np
np.set_printoptions(suppress=True)

def checkerboard(side, squares):
    """Square texture of side x side texels with squares x squares cells of 0 and 1."""
    indices = np.arange(side) * squares // side
    return ((indices[:, None] + indices[None, :]) % 2).astype(float)

WIDTH, HEIGHT = 60, 24
billboard_projection = perspective_matrix(np.radians(60.0), 1.0, 1.0, 100.0)
corners = np.array([[-1.0, -1.0, -2.0], [1.5, -1.0, -10.0], [1.5, 1.0, -10.0], [-1.0, 1.0, -2.0]])
uvs = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
clip = [billboard_projection @ to_homogeneous(e) for e in corners]
screen = [ndc_to_screen(r[:3] / r[3], WIDTH, HEIGHT) for r in clip]
w = [r[3] for r in clip]

def checker(u, v):
    """Checkerboard of 8 x 4 squares."""
    return "#" if (int(np.floor(u * 8.0)) + int(np.floor(v * 4.0))) % 2 == 1 else "."

def draw_billboard(correct):
    canvas, z_buffer = np.full((HEIGHT, WIDTH), " "), np.full((HEIGHT, WIDTH), 1.0)
    for i, j, k in ((0, 1, 2), (0, 2, 3)):              # two triangles
        def shader(alpha, beta, gamma):
            weights, uv = (alpha, beta, gamma), (uvs[i], uvs[j], uvs[k])
            if correct:
                u, v = interpolate_with_perspective(weights, uv, (w[i], w[j], w[k]))
            else:
                u, v = interpolate_attribute(weights, uv)
            return checker(u, v)
        rasterize_triangle(screen[i], screen[j], screen[k], canvas, z_buffer, shader)
    return canvas

for correct in (False, True):
    print("\n".join("".join(row).rstrip() for row in draw_billboard(correct)[2:22]))
    print("-" * 40)
    ####
    ####....
    ####....####
    ####....#####...
    ####....#####....###
    ...#....#####....####...
    ....###.#####....####....###
    ....####...##....####....#####..
    ....####.....##..####....#####....
    ....####.....####..##....#####..##
    ##..####.....####....##..###..##..
    ####..##.....####....####...##..##
    ####....##...####....###.###..##
    ####....#####.###...#...#...
    ####....#####....###.###
    .###....#####...#...
    ....#...####.###
    ....####....
    ....####
    ....
----------------------------------------
    ####
    ########
    ############
    ##############..
    ##############......
    ......########.......###
    .....................####...
    ..............#######.###...##..
    ..............#######....###....#.
    ..............#######....###..##.#
    ##############.......####...##..#.
    ##############.......####...####.#
    ##############.......#...###..##
    #####################....###
    ######........#######...
    ..............######
    ..............##
    ............
    ........
    ....
----------------------------------------

The two images occupy the same trapezoid on screen; what changes is what is painted inside.

  • Without correction (top), the eight squares all have the same width on screen, as if the billboard were facing us, and the checkerboard breaks along the diagonal that separates the two triangles: each one interpolates on its own and they do not match up. It is the characteristic defect of the game consoles of the nineties.
  • With correction (bottom), the first square, the nearest one, takes up 14 columns; the following ones get narrower and narrower, and the last ones are less than a character wide. This is the correct perspective: the same lengths, farther away, look smaller.

At the far end of the second image the squares are so small that the pattern turns into noise. It is not a failure of the mapping: it is aliasing, and we will deal with it in the section on mipmaps.

From UV to texel: the nearest neighbor

The interpolated coordinates are real numbers; the texture is a discrete grid. Sampling means converting \((u, v)\) into a value. In a texture of width × height texels, we go to continuous texel coordinates by multiplying:

\[ x = u \cdot \text{width} \qquad y = v \cdot \text{height} \]

The texel in column \(i\) occupies the interval \([i, i + 1)\), with its center at \(i + 0.5\), exactly like the pixels of the screen. The simplest method, nearest neighbor, returns the texel in whose square the point falls:

\[ \text{column} = \lfloor u \cdot \text{width} \rfloor \qquad \text{row} = \lfloor v \cdot \text{height} \rfloor \]

It is fast and keeps edges sharp, but when the texture is seen enlarged (one texel takes up many pixels: magnification) each texel appears as a square of flat color. It is the "pixelated" look, desirable in a game with a retro aesthetic and annoying in almost everything else.

Wrap modes

What happens if the coordinates go outside the interval \([0, 1]\)? It is not an error: it is a tool. The wrap mode (also called the addressing mode) decides which texel is read:

Mode What it does with \(u\) outside \([0, 1]\) Typical use
Repeat Keeps the fractional part: the texture is repeated like a tiling Floors, walls, any continuous pattern
Mirror Like repeat, but flipping every other copy Patterns that do not match at the edges
Clamp Limits it to the edge: the last texel is repeated One-off textures: posters, interface, skies

With "repeat", assigning a wall UV coordinates from 0 to 10 makes a small brick texture repeat ten times, without spending any memory.

def wrap_index(index, n, mode="repeat"):
    """Takes any texel index to the interval [0, n - 1] according to the mode."""
    if mode == "repeat":
        return index % n
    if mode == "mirror":
        index = index % (2 * n)
        return index if index < n else 2 * n - 1 - index
    return min(max(index, 0), n - 1)                    # clamp

def sample_nearest(texture, u, v, mode="repeat"):
    """Texel whose square contains the point (u, v)."""
    height, width = texture.shape[:2]
    column = wrap_index(int(np.floor(u * width)), width, mode)
    row = wrap_index(int(np.floor(v * height)), height, mode)
    return texture[row, column]

panel = np.array([[0.0, 0.2, 0.4, 0.6],        # row 0: the bottom one
                  [0.2, 0.4, 0.6, 0.8],
                  [0.4, 0.8, 1.0, 0.6],
                  [0.1, 0.3, 0.5, 0.7]])

print(sample_nearest(panel, 0.4, 0.6))
for mode in ("repeat", "mirror", "clamp"):
    print(mode, [wrap_index(i, 4, mode) for i in range(-3, 9)],
          sample_nearest(panel, 1.3, 0.1, mode), sample_nearest(panel, -0.2, 0.1, mode))
0.8
repeat [1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0] 0.2 0.6
mirror [2, 1, 0, 0, 1, 2, 3, 3, 2, 1, 0, 0] 0.4 0.0
clamp [0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 3, 3] 0.6 0.0

The point \((0.4, 0.6)\) falls at \(x = 1.6\), \(y = 2.4\): column 1, row 2, value 0.8. The three lists show which texel each index from \(-3\) to 8 ends up at in a texture of 4 texels: in "repeat", Python's % operator (which always returns a non-negative result) does all the work; in "mirror", the pattern has period 8 and the second half is reversed.

Bilinear filtering

Instead of keeping a single texel, bilinear filtering blends the four texels whose centers surround the sampling point, with weights according to how close it is to each one. The result varies continuously and enlarged textures look smooth.

It is derived as a linear interpolation applied twice, the same "lerp of lerps" idea as in De Casteljau's algorithm:

  1. Since the centers are at \(i + 0.5\), half a texel is subtracted in order to measure between centers: \(x = u \cdot \text{width} - 0.5\), \(y = v \cdot \text{height} - 0.5\).
  2. The integer and fractional parts are separated: \(x_0 = \lfloor x \rfloor\), \(f_x = x - x_0\), and the same in \(y\). The four texels are those in columns \(x_0\), \(x_0 + 1\) and rows \(y_0\), \(y_0 + 1\).
  3. Two horizontal lerps, one in each row, with \(f_x\).
  4. One vertical lerp between the two results, with \(f_y\).

\[ \begin{aligned} \text{bottom} &= (1 - f_x),T_{y_0,,x_0} + f_x,T_{y_0,,x_0+1} \\ \text{top} &= (1 - f_x),T_{y_0+1,,x_0} + f_x,T_{y_0+1,,x_0+1} \\ \text{result} &= (1 - f_y),\text{bottom} + f_y,\text{top} \end{aligned} \]

Expanding, each texel receives a weight that is the product of a horizontal factor and a vertical one—\((1 - f_x)(1 - f_y)\), \(f_x (1 - f_y)\), and so on—: the area of the opposite rectangle. The four weights add up to 1. Doing the vertical lerps first and then the horizontal one gives the same result.

Example. In the texture panel, for \((u, v) = (0.4, 0.6)\): \(x = 1.6 - 0.5 = 1.1\) and \(y = 2.4 - 0.5 = 1.9\). Then \(x_0 = 1\), \(f_x = 0.1\), \(y_0 = 1\), \(f_y = 0.9\). The four texels are:

Column 1 Column 2
Row 2 (top) 0.8 1.0
Row 1 (bottom) 0.4 0.6
  • Bottom: \(0.9 \cdot 0.4 + 0.1 \cdot 0.6 = 0.42\).
  • Top: \(0.9 \cdot 0.8 + 0.1 \cdot 1.0 = 0.82\).
  • Result: \(0.1 \cdot 0.42 + 0.9 \cdot 0.82 = 0.042 + 0.738 = 0.78\).

Nearest neighbor gave 0.8, the value of the texel in row 2 and column 1; bilinear gives 0.78: the point is very close to the center of that texel, but the neighbors already have a little influence.

def sample_bilinear(texture, u, v, mode="repeat"):
    """Blend of the four texels whose centers surround the point (u, v)."""
    height, width = texture.shape[:2]
    x, y = u * width - 0.5, v * height - 0.5            # in texel units, between centers
    x0, y0 = int(np.floor(x)), int(np.floor(y))
    fx, fy = x - x0, y - y0
    c0, c1 = wrap_index(x0, width, mode), wrap_index(x0 + 1, width, mode)
    r0, r1 = wrap_index(y0, height, mode), wrap_index(y0 + 1, height, mode)
    bottom = (1.0 - fx) * texture[r0, c0] + fx * texture[r0, c1]
    top = (1.0 - fx) * texture[r1, c0] + fx * texture[r1, c1]
    return (1.0 - fy) * bottom + fy * top

print(round(sample_bilinear(panel, 0.4, 0.6), 4), round(sample_bilinear(panel, 0.375, 0.375), 4))
print(round(sample_bilinear(panel, 0.0, 0.125, "repeat"), 4),
      round(sample_bilinear(panel, 0.0, 0.125, "clamp"), 4))
0.78 0.4
0.3 0.0

The point \((0.375, 0.375)\) is exactly the center of the texel in row 1 and column 1: bilinear returns its value, 0.4, with no blending. The second line samples at the left edge of the image, \(u = 0\): the two neighboring texels are column 0 and column "\(-1\)". In repeat mode, that is column 3 at the other end, and 0.0 and 0.6 are blended; in clamp mode, it is column 0 itself. That is why the wrap mode matters even with coordinates inside \([0, 1]\): with "repeat", the color of the opposite edge creeps in at the edges of a poster.

Minification, aliasing and mipmaps

Bilinear filtering solves magnification. The opposite problem, minification, is more serious: when the texture looks small or far away, one screen pixel covers many texels. Reading just one (or four) means keeping an arbitrary sample of a region that contains much more information.

fine = checkerboard(64, 32)                         # squares 2 texels on a side
u_pixels = (np.arange(12) + 0.5) / 12.0             # 12 pixels cover the 64 texels
print([float(sample_nearest(fine, u, 0.51)) for u in u_pixels])
print([float(sample_nearest(fine, u, 0.51)) for u in (np.arange(16) + 0.5) / 16.0])
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

A fine checkerboard of 32 squares, seen in a strip of 12 pixels, should look gray: each pixel covers more than five texels, half white and half black. Instead a false pattern of period 3 appears that does not exist in the texture. With 16 pixels, all the samples fall on white squares and the strip comes out white. This is aliasing: when a signal is sampled with fewer samples than its detail demands, spurious patterns appear. In motion it is even worse, because those patterns dance and flicker (the moiré effect).

The correct solution would be to average all the texels each pixel covers, but doing so at every pixel and every frame is hugely expensive. Mipmaps do that averaging in advance.

The mipmap pyramid

The original texture (level 0) is stored together with versions successively reduced by half, each one obtained by averaging blocks of 2 × 2 texels of the previous one, down to 1 × 1. Each texel of level \(k\) is the average of a square of \(2^k \times 2^k\) original texels. The cost in memory is modest: \(1 + \tfrac{1}{4} + \tfrac{1}{16} + \dots = \tfrac{4}{3}\), only a third more.

Which level to use

The right level is the one in which a texel measures roughly the same as a pixel. If \(\rho\) is the number of texels (of level 0) that are advanced on going from one pixel to the next:

\[ \text{level} = \log_2 \rho \]

With \(\rho = 1\) level 0 is used; with \(\rho = 4\), level 2. The graphics card computes \(\rho\) for each pixel from the derivatives of the texture coordinates with respect to the screen, that is, by comparing the UVs of neighboring pixels: the more they change from one pixel to the next, the larger the pixel's footprint on the texture.

Since \(\log_2 \rho\) is almost never an integer, and so that no jump is noticeable where the level changes, trilinear filtering does a bilinear sample in the two nearest levels and interpolates between them: a third lerp.

def generate_mipmaps(texture):
    """List of levels: each one averages blocks of 2 x 2 texels of the previous one."""
    levels = [np.asarray(texture, dtype=float)]
    while levels[-1].shape[0] > 1:
        t = levels[-1]
        levels.append((t[0::2, 0::2] + t[1::2, 0::2] + t[0::2, 1::2] + t[1::2, 1::2]) / 4.0)
    return levels

def sample_trilinear(mipmaps, u, v, level):
    """Bilinear in the two neighboring levels and lerp between them."""
    level = float(np.clip(level, 0.0, len(mipmaps) - 1.0))
    n0 = int(np.floor(level))
    n1 = min(n0 + 1, len(mipmaps) - 1)
    f = level - n0
    return ((1.0 - f) * sample_bilinear(mipmaps[n0], u, v)
            + f * sample_bilinear(mipmaps[n1], u, v))

mipmaps = generate_mipmaps(fine)
print([m.shape[0] for m in mipmaps], round(sum(m.size for m in mipmaps) / fine.size, 4))
level = np.log2(64.0 / 12.0)
print(round(level, 3), [round(float(sample_trilinear(mipmaps, u, 0.51, level)), 3) for u in u_pixels])
[64, 32, 16, 8, 4, 2, 1] 1.3333
2.415 [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]

t[0::2, 0::2] takes every other texel in both directions; adding the four combinations of offsets averages the 2 × 2 blocks. With 12 pixels for 64 texels, \(\rho = 5.33\) and the level is 2.4: levels 2 and 3 are blended, in which the checkerboard has already been averaged into a uniform gray. All twelve pixels are 0.5, the correct result.

The limit: grazing surfaces

Mipmaps assume that the pixel's footprint is square. On a surface seen at a grazing angle it is not. For a floor located at a height \(h\) below the camera, with the 60° FOV and an image 720 pixels high, a pixel at depth \(d\) covers on the floor:

Depth \(d\) Width of the footprint Length of the footprint Ratio
2 m 0.32 cm 0.64 cm 1 : 2
5 m 0.80 cm 4.0 cm 1 : 5
10 m 1.6 cm 16 cm 1 : 10

(With \(h = 1\) m; the width is \(\tfrac{2d}{c \cdot \text{height}}\) and the length \(\tfrac{2d^2}{c \cdot h \cdot \text{height}}\), with \(c = \cot 30°\). The length grows with \(d^2\), the same nonlinearity of depth as in "Projections and Views".) At 10 m the footprint is ten times longer than it is wide. If the level is chosen by the long side, the texture blurs in the other direction; if by the short one, the aliasing reappears. Anisotropic filtering solves it by taking several samples spread along the long axis of the footprint.

Filter Texels read Solves Flaw
Nearest neighbor 1 — Pixelated when enlarged, aliasing when reduced
Bilinear 4 Magnification Aliasing when reduced
Trilinear (with mipmaps) 8 Minification Blurry on grazing surfaces
Anisotropic 16 to 128 Grazing surfaces Cost

Mapping projections: planar, cylindrical and spherical

The opening question remains: where do the UVs of each vertex come from? One automatic way is to project: a simple function that converts the 3D position of a point (normally in local space) into a pair \((u, v)\).

Projection \(u\) \(v\) Suitable for Flaw
Planar Coordinate along one axis Coordinate along another, perpendicular axis Almost flat surfaces: floors, posters, terrain It stretches on the faces parallel to the projection direction
Cylindrical Azimuth around the axis Height Towers, trunks, cans Vertical seam; the caps
Spherical Azimuth Elevation Planets, asteroids, domes Seam; the poles get squeezed

The cylindrical and spherical ones are the coordinate conversions from "Coordinates and Planes", normalized to \([0, 1]\). The azimuth, which goes from \(-180°\) to \(180°\), becomes \(u = \tfrac{\text{azimuth}}{360°} + 0.5\); the elevation, from \(-90°\) to \(90°\), becomes \(v = \tfrac{\text{elevation}}{180°} + 0.5\). They are also the parameterizations from "Surface Modeling", read backward: there \((u, v)\) gave the point; here the point gives \((u, v)\).

def planar_uv(p, origin, u_axis, v_axis):
    """Planar projection: coordinates of p - origin along two perpendicular axes.

    The length of each axis is how much the texture measures in that direction.
    """
    d = np.asarray(p, dtype=float) - np.asarray(origin, dtype=float)
    return np.array([dot_product(d, u_axis) / dot_product(u_axis, u_axis),
                     dot_product(d, v_axis) / dot_product(v_axis, v_axis)])

def cylindrical_uv(p, min_height=0.0, max_height=1.0):
    """Cylindrical projection around the Y axis: u = azimuth, v = normalized height."""
    radius, azimuth, height = cartesian_to_cylindrical(p)
    return np.array([azimuth / (2.0 * np.pi) + 0.5,
                     (height - min_height) / (max_height - min_height)])

def spherical_uv(p):
    """Spherical projection from the origin: u = azimuth, v = elevation, both in [0, 1]."""
    radius, azimuth, elevation = cartesian_to_spherical(p)
    return np.array([azimuth / (2.0 * np.pi) + 0.5, elevation / np.pi + 0.5])

# Planar: the hull (local space) seen from above; it spans from -4 to 4 in X and from -2 to 2 in Z
for p in ([4.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0], [26.0 / 15.0, 1.0 / 3.0, -7.0 / 15.0]):
    print(np.round(planar_uv(p, [-4.0, 0.0, -2.0], [8.0, 0.0, 0.0], [0.0, 0.0, 4.0]), 4))

# Cylindrical: the lighthouse tower, from y = 0 to y = 12
for p in ([0.0, 6.0, 1.0], [1.0, 3.0, 0.0], [-1.0, 9.0, 0.0]):
    print(np.round(cylindrical_uv(p, 0.0, 12.0), 4))

# Spherical: the lighthouse asteroid, centered at (0, -10, 0)
asteroid_center = np.array([0.0, -10.0, 0.0])
for p in ([0.0, 0.0, 0.0], [10.0, -10.0, 0.0], ship):
    print(np.round(spherical_uv(np.asarray(p) - asteroid_center), 4))
[1.  0.5]
[0.5 0.5]
[0.5 0.5]
[0.7167 0.3833]
[0.5 0.5]
[0.75 0.25]
[0.25 0.75]
[0.5 1. ]
[0.75 0.5 ]
[0.6476 0.7913]
  • Planar. The projection is two dot products: how far the point advances along each axis, as a fraction of its length. The wing tip goes to the edge of the texture; the top \((0, 1, 0)\) and the bottom \((0, -1, 0)\) go to the same point, the center: a planar projection does not distinguish the upper face from the lower one, and both will receive the same picture. The last point is where the beam hits the hull.
  • Cylindrical. The point of the tower facing \(+Z\), at mid-height, goes to the center of the texture. On turning toward \(+X\), \(u\) increases.
  • Spherical. The base of the lighthouse, at the north pole of the asteroid, goes to \(v = 1\). The last line is the projection of the ship onto the asteroid: azimuth 53.13° and elevation 52.43° as seen from its center.

Seams and UV unwrapping

The seam

The cylindrical and spherical projections have a line, at azimuth \(\pm 180°\) (toward \(-Z\)), on which \(u\) jumps from 1 to 0. This is the seam: the place where the left and right edges of the image meet, as on the label of a can. Nothing special happens in the texture; the problem lies in the interpolation.

a = cylindrical_uv([0.1, 6.0, -1.0], 0.0, 12.0)        # just on one side of the seam
b = cylindrical_uv([-0.1, 6.0, -1.0], 0.0, 12.0)       # just on the other
print(np.round(a, 4), np.round(b, 4), np.round((a + b) / 2.0, 4),
      np.round(cylindrical_uv([0.0, 6.0, -1.0], 0.0, 12.0), 4))
[0.9841 0.5   ] [0.0159 0.5   ] [0.5 0.5] [1.  0.5]

Two vertices of the tower on either side of the seam have \(u = 0.984\) and \(u = 0.016\). The point in between should have \(u = 1\) (or 0, which is the same thing), but linear interpolation gives 0.5: between those two vertices the entire texture would be drawn, squeezed and backward. The solution is to duplicate the vertices of the seam: one copy with \(u = 0\) for the triangles on one side and another with \(u = 1\) for those on the other. It is just what tessellate_parametric did in the previous lesson, which seemed to us a flaw compared with sphere_mesh: for texturing, the grid with the duplicated column is the correct one.

At the poles of the spherical projection a whole row of the image is squeezed into a point, and the texture looks pinched: it is the same singularity as always.

UV unwrapping

For a complex shape—the whole ship, a character—no simple projection will do. Artists then perform a UV unwrapping: the mesh is cut along certain edges and flattened onto the square \([0, 1]^2\), like a dress pattern or the cut-out net of a paper cube. Each flattened piece is called an island. A good unwrap aims for:

  • Little distortion: the triangles should keep in the UV plane the shape and relative size they have in 3D, so that the texture is not stretched.
  • Discreet seams: placed where they are least visible.
  • Making good use of the space: the islands should fill the square, because the texels that no face uses are wasted.

Unwrapping with no distortion at all is, in general, impossible: a curved surface cannot be flattened without stretching it, and that is why all maps of the Earth distort something. Unwrapping is always a compromise. The ship's octahedral hull is a friendly case: its eight flat faces can be laid out in the UV plane with no deformation at all.

UV transformations with 3×3 matrices

UV coordinates are points of a plane, and they can be transformed just as we transformed points in space. In 2D, the homogeneous coordinates are \((u, v, 1)\) and the affine matrices are 3×3: the upper left 2×2 block does the linear part (the rotation_matrix_2d from Module 2, or a scaling) and the third column, the translation.

\[ \begin{pmatrix} u' \ v' \ 1 \end{pmatrix} = \begin{pmatrix} s_u \cos\theta & -s_v \sin\theta & t_u \ s_u \sin\theta & s_v \cos\theta & t_v \ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} u \ v \ 1 \end{pmatrix} \]

Everything we learned about composition applies as is: to rotate or scale about the center of the texture we use the pivot pattern, \(T(\mathbf{c}),R,S,T(-\mathbf{c})\), with \(\mathbf{c} = (0.5, 0.5)\).

There is one subtlety, that of the active and passive readings: what is transformed is the coordinates with which the image is read, not the image. The visual effect is the inverse:

Transformation of the UVs Visible effect on the surface
Scale by 2 The texture is seen at half size, repeated 2 times
Shift \(+0.25\) in \(u\) The texture slides toward \(-u\)
Rotate \(+90°\) The texture rotates \(-90°\)

Making the matrix depend on time produces animation without touching the geometry: a growing offset makes the text of an illuminated panel scroll, or the water of a river flow, or the stripes of light run along the lighthouse beam.

def uv_matrix(scale=(1.0, 1.0), angle=0.0, offset=(0.0, 0.0), pivot=(0.5, 0.5)):
    """3x3 matrix for UV coordinates: scale and rotation about the pivot, and then offset."""
    def translation(tu, tv):
        return np.array([[1.0, 0.0, tu], [0.0, 1.0, tv], [0.0, 0.0, 1.0]])
    c, s = np.cos(angle), np.sin(angle)
    rotation = np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
    scaling = np.diag([scale[0], scale[1], 1.0])
    return (translation(*offset) @ translation(*pivot) @ rotation @ scaling
            @ translation(-pivot[0], -pivot[1]))

def transform_uv(m, uv):
    """Applies the 3x3 matrix m to the point (u, v)."""
    return (m @ np.array([uv[0], uv[1], 1.0]))[:2]

print(np.round(uv_matrix(scale=(2.0, 2.0)), 4))
print(transform_uv(uv_matrix(scale=(2.0, 2.0)), (0.0, 0.0)),
      transform_uv(uv_matrix(scale=(2.0, 2.0)), (1.0, 1.0)),
      np.round(transform_uv(uv_matrix(angle=np.radians(90.0)), (0.75, 0.5)), 4))

# Illuminated panel: the texture shifts one texel (0.25) per second
for second in range(5):
    m = uv_matrix(offset=(0.25 * second, 0.0))
    print(second, [float(sample_nearest(panel, *transform_uv(m, (u, 0.375))))
                   for u in (0.125, 0.375, 0.625, 0.875)])
[[ 2.   0.  -0.5]
 [ 0.   2.  -0.5]
 [ 0.   0.   1. ]]
[-0.5 -0.5] [1.5 1.5] [0.5  0.75]
0 [0.2, 0.4, 0.6, 0.8]
1 [0.4, 0.6, 0.8, 0.2]
2 [0.6, 0.8, 0.2, 0.4]
3 [0.8, 0.2, 0.4, 0.6]
4 [0.2, 0.4, 0.6, 0.8]

Scaling by 2 about the center takes the corners \((0, 0)\) and \((1, 1)\) to \((-0.5, -0.5)\) and \((1.5, 1.5)\): the surface now spans a UV interval of length 2 and, with repeat mode, shows the texture twice in each direction. On the illuminated panel, the row of four texels slides one position per second to the left and, thanks to repeat mode, what leaves on one side comes in on the other; after 4 seconds the cycle repeats.

Normal maps and tangent space

A texture does not have to contain colors. The most important application after color is the normal map: an image in which each texel stores a normal. By lighting each pixel with the normal read from the texture, instead of the geometric normal, a flat surface is shaded as if it had relief: rivets, joints, scratches. The outline does not change—the relief is faked—but the effect is very convincing and does not cost a single triangle.

A unit normal has components between \(-1\) and \(1\), and a color, between 0 and 1. It is encoded and decoded with a change of scale (the same trick we recommended for debugging normals):

\[ \text{color} = \frac{\mathbf{n} + 1}{2} \qquad\Longleftrightarrow\qquad \mathbf{n} = 2 \cdot \text{color} - 1 \]

Tangent space

Which coordinate system are those normals in? If they were in the object's local space, the texture would only work for that mesh and that placement. They are stored in a system specific to each point of the surface, tangent space, whose axes are:

Axis Name Direction
\(\mathbf{T}\) Tangent On the surface, the way \(u\) grows
\(\mathbf{B}\) Bitangent On the surface, the way \(v\) grows
\(\mathbf{N}\) Normal Perpendicular to the surface

In this system, the "no relief" normal is always \((0, 0, 1)\), which encoded is the color \((0.5, 0.5, 1)\): that is why normal maps have that characteristic lavender-blue tone. A normal from the map is taken to the world with a change of basis, like those in "Inverse Transformations and Change of Coordinate System": the TBN matrix, which has \(\mathbf{T}\), \(\mathbf{B}\) and \(\mathbf{N}\) as columns.

\[ \mathbf{n}{\text{world}} = \begin{pmatrix} \mathbf{T} & \mathbf{B} & \mathbf{N} \end{pmatrix} \mathbf{n}{\text{tangent}} = n_x,\mathbf{T} + n_y,\mathbf{B} + n_z,\mathbf{N} \]

The tangent of a triangle

\(\mathbf{T}\) and \(\mathbf{B}\) are derived from the positions and the UVs of the vertices. Let \(\mathbf{E}_1 = P_1 - P_0\) and \(\mathbf{E}_2 = P_2 - P_0\) be two edges of the triangle, and \((\Delta u_1, \Delta v_1)\), \((\Delta u_2, \Delta v_2)\) the changes in UV along each one. Since the mapping is linear inside the triangle, advancing \(\Delta u\) and \(\Delta v\) in the texture is equivalent to advancing \(\Delta u,\mathbf{T} + \Delta v,\mathbf{B}\) in space:

\[ \begin{aligned} \mathbf{E}_1 &= \Delta u_1,\mathbf{T} + \Delta v_1,\mathbf{B} \\ \mathbf{E}_2 &= \Delta u_2,\mathbf{T} + \Delta v_2,\mathbf{B} \end{aligned} \]

It is a system of two equations in two (vector) unknowns, and it is solved with the inverse of a 2×2 matrix from Module 1:

\[ \mathbf{T} = \frac{\Delta v_2,\mathbf{E}_1 - \Delta v_1,\mathbf{E}_2}{\Delta u_1 \Delta v_2 - \Delta u_2 \Delta v_1} \qquad \mathbf{B} = \frac{\Delta u_1,\mathbf{E}_2 - \Delta u_2,\mathbf{E}_1}{\Delta u_1 \Delta v_2 - \Delta u_2 \Delta v_1} \]

The denominator is the determinant of the UVs: twice the signed area of the triangle in the texture. If it is zero, the triangle is degenerate in the UV plane and there is no tangent.

Example. The face of the hull lit by the lighthouse, with vertices right wing, tail and top, and UVs \((0, 0)\), \((1, 0)\) and \((0.5, 1)\). Then \(\mathbf{E}_1 = (-4, 0, 2)\), \(\mathbf{E}_2 = (-2.4, 1, 3.2)\), \((\Delta u_1, \Delta v_1) = (1, 0)\) and \((\Delta u_2, \Delta v_2) = (0.5, 1)\). The determinant equals 1, and:

\[ \mathbf{T} = 1 \cdot \mathbf{E}_1 - 0 \cdot \mathbf{E}_2 = (-4, 0, 2) \qquad \mathbf{B} = 1 \cdot \mathbf{E}_2 - 0.5 \cdot \mathbf{E}_1 = (-0.4, 1, 2.2) \]

The tangent is the edge from the wing to the tail, along which \(u\) goes from 0 to 1.

def triangle_tangent(p0, p1, p2, uv0, uv1, uv2):
    """Unit tangent and bitangent: directions in which u and v grow over the triangle."""
    p0, uv0 = np.asarray(p0, dtype=float), np.asarray(uv0, dtype=float)
    e1, e2 = np.asarray(p1, dtype=float) - p0, np.asarray(p2, dtype=float) - p0
    du1, dv1 = np.asarray(uv1, dtype=float) - uv0
    du2, dv2 = np.asarray(uv2, dtype=float) - uv0
    determinant = du1 * dv2 - du2 * dv1
    tangent = (dv2 * e1 - dv1 * e2) / determinant
    bitangent = (du1 * e2 - du2 * e1) / determinant
    return normalize(tangent), normalize(bitangent)

wing, tail, top = np.array([10.4, 3.0, 2.8]), np.array([6.4, 3.0, 4.8]), np.array([8.0, 4.0, 6.0])
t, b = triangle_tangent(wing, tail, top, [0.0, 0.0], [1.0, 0.0], [0.5, 1.0])
n = triangle_normal(wing, tail, top)
print(np.round(t, 4), np.round(b, 4), np.round(n, 4))
print(round(dot_product(t, n), 4) + 0.0, round(dot_product(b, n), 4) + 0.0,
      round(dot_product(t, b), 4))

b = np.cross(n, t)                                  # orthogonal bitangent
tbn = np.column_stack([t, b, n])
print(np.round(b, 4), round(float(np.linalg.det(tbn)), 4))

toward_light = np.array([-2.0, 2.0, -1.0]) / 3.0    # from the hit point to the lamp
for texel in ([0.5, 0.5, 1.0], [0.7, 0.5, 0.9], [0.3, 0.5, 0.9]):
    n_tangent = normalize(2.0 * np.array(texel) - 1.0)
    n_world = tbn @ n_tangent
    print(texel, np.round(n_tangent, 4), np.round(n_world, 4), round(diffuse_light(n_world, toward_light), 4))
[-0.8944  0.      0.4472] [-0.1633  0.4082  0.8981] [-0.2182  0.8729 -0.4364]
0.0 0.0 0.5477
[0.3904 0.488  0.7807] 1.0
[0.5, 0.5, 1.0] [0. 0. 1.] [-0.2182  0.8729 -0.4364] 0.8729
[0.7, 0.5, 0.9] [0.4472 0.     0.8944] [-0.5952  0.7807 -0.1904] 0.9807
[0.3, 0.5, 0.9] [-0.4472  0.      0.8944] [ 0.2048  0.7807 -0.5904] 0.5807
  • \(\mathbf{T}\) and \(\mathbf{B}\) are perpendicular to \(\mathbf{N}\), as they should be: they lie on the face. But they are not perpendicular to each other (\(\mathbf{T} \cdot \mathbf{B} = 0.55\)), because the triangle does not have the same shape in the texture as in space: the mapping distorts it.
  • To get an orthonormal basis, \(\mathbf{T}\) is kept and the bitangent is recomputed as \(\mathbf{N} \times \mathbf{T}\). The resulting TBN matrix has determinant 1: it is a rotation.
  • The texel \((0.5, 0.5, 1)\) returns the face normal unaltered and the diffuse lighting of the previous lesson, 0.873. The texel \((0.7, 0.5, 0.9)\) tilts the normal toward \(\mathbf{T}\) and, since the light arrives from that side, the lighting rises to 0.98; \((0.3, 0.5, 0.9)\) tilts it the opposite way and it drops to 0.58. A groove painted in the normal map will thus have one light edge and one dark edge, exactly like a real groove.

In a mesh, the tangents of the faces are averaged at each vertex, like the normals, and stored as one more attribute.

Environment maps

So far the texture has been looked up with a position on the surface. An environment map is looked up with a direction. It is an image of everything that surrounds the scene—the starry sky, a nebula—seen from one point, and it has two uses:

  • Background (skybox): for each pixel not covered by any object, we take the direction of the ray that passes through it and read the map in that direction. The background is thus infinitely far away: it rotates with the camera, but does not get closer as we advance.
  • Reflections: on a polished surface we compute the reflection of the view direction off the normal, with reflect, and read the map in that direction. The hull reflects the stars without a single ray having been traced.

Converting a direction into texture coordinates is precisely what spherical_uv does (such an image is called equirectangular, like a world map). Graphics cards prefer cube maps: six square images, one for each face of a cube, which avoid the squeezing at the poles; the face is chosen according to the component of the direction with the largest absolute value.

p = np.array([26.0, 10.0, 13.0]) / 3.0
normal = np.array([-1.0, 4.0, -2.0]) / np.sqrt(21.0)
toward_eye = direction_to(p, [12.0, 7.0, 4.0])
reflection = reflect(-toward_eye, normal)
print(np.round(reflection, 4), np.round(spherical_uv(reflection), 4), np.round(spherical_uv([0.0, 0.0, -1.0]), 4))
[-0.9013  0.1822 -0.3931] [0.1845 0.5583] [1.  0.5]

From beacon Alpha, the hit point on the hull reflects what lies in the direction \((-0.90, 0.18, -0.39)\), which corresponds to the texel \((0.18, 0.56)\) of the environment map. The last figure is a reminder of where the seam is: looking toward \(-Z\) corresponds to \(u = 1\), which is the same edge of the image as \(u = 0\).

Common Mistakes and Tips

  • Confusing the origin of \(v\). If the texture comes out upside down, you have to use \(1 - v\) or flip the image when loading it. Decide on one convention and convert everything to it at a single point in the code.
  • Forgetting the half texel. The centers of the texels are at \(i + 0.5\). Without subtracting 0.5 in bilinear filtering, the whole texture appears shifted by half a texel.
  • Interpolating the UVs without perspective correction. The checkerboard breaks along the diagonal of each quadrilateral.
  • Using repeat mode on textures that are not tilings. The color of the opposite side leaks in at the edges. For posters, interface and skies, use clamp mode.
  • Not generating mipmaps. Distant textures flicker and show moiré. The extra third of memory is almost always worth it.
  • Sharing the vertices of the seam. With a cylindrical or spherical projection, the triangles that cross the seam show the entire texture squeezed. Those vertices have to be duplicated.
  • Forgetting that transforming the UVs produces the inverse effect. Scaling the UVs by 2 does not enlarge the texture: it shrinks it and repeats it.
  • Treating a normal map as a color image. Its texels are vectors: they have to be decoded with \(2c - 1\), renormalized after filtering and not gamma-corrected.
  • Assuming that \(\mathbf{T}\) and \(\mathbf{B}\) are perpendicular. They only are if the mapping does not distort. Orthogonalize the basis with respect to \(\mathbf{N}\).
  • Tip. To debug a mapping, replace the texture with a checkerboard or a numbered grid, or paint the UVs directly as the color \((u, v, 0)\): stretching, seams and flips jump out at you.

Exercises

Exercise 1. A texture of 2 × 2 texels has the values 0.0 and 1.0 in the bottom row (columns 0 and 1) and 0.5 and 0.25 in the top one.

a) What value does nearest neighbor return at \((u, v) = (0.6, 0.3)\)? b) Compute by hand the bilinear filtering at \((0.5, 0.5)\). Why does it give that result? c) Compute by hand the bilinear filtering at \((0.4, 0.6)\).

Exercise 2. a) Compute by hand the spherical UV coordinates, relative to the center of the lighthouse asteroid \((0, -10, 0)\), of the surface point located at \((0, 0, 0)\) and of the one located at \((10, -10, 0)\). b) A point on the surface of the tower (radius 1, height 12) is at \((0.6, 9, 0.8)\). What are its cylindrical UVs? c) The tower is 12 m high and \(2\pi \approx 6.28\) m around. If a square brick texture is applied to it as is, what will the bricks look like? Which UV matrix fixes it?

Exercise 3. a) A texture 256 texels wide is seen on screen taking up 40 pixels in width. Which mipmap level corresponds to it and which levels does trilinear filtering blend? b) The floor of the strip has a triangle with vertices \((0, 0, 0)\), \((4, 0, 0)\) and \((0, 0, -4)\), with UVs \((0, 0)\), \((2, 0)\) and \((0, 2)\). Compute its tangent and its bitangent with triangle_tangent and interpret them. c) Where does a 90° UV rotation about the center take the point \((0.75, 0.5)\)?

Solutions

Solution 1.

a) \(x = 0.6 \cdot 2 = 1.2\), \(y = 0.3 \cdot 2 = 0.6\): column 1, row 0. Value 1.0.

b) \(x = 0.5 \cdot 2 - 0.5 = 0.5\), \(y = 0.5\): \(x_0 = y_0 = 0\), \(f_x = f_y = 0.5\). Bottom: \(0.5 \cdot 0 + 0.5 \cdot 1 = 0.5\). Top: \(0.5 \cdot 0.5 + 0.5 \cdot 0.25 = 0.375\). Result: \(0.5 \cdot 0.5 + 0.5 \cdot 0.375 = 0.4375\). It is the average of the four texels: the point is at the center of the image, at the same distance from the four centers.

c) \(x = 0.8 - 0.5 = 0.3\), \(y = 1.2 - 0.5 = 0.7\): \(x_0 = y_0 = 0\), \(f_x = 0.3\), \(f_y = 0.7\). Bottom: \(0.7 \cdot 0 + 0.3 \cdot 1 = 0.3\). Top: \(0.7 \cdot 0.5 + 0.3 \cdot 0.25 = 0.425\). Result: \(0.3 \cdot 0.3 + 0.7 \cdot 0.425 = 0.09 + 0.2975 = 0.3875\).

Solution 2.

a) Relative to the center, the first point is \((0, 10, 0)\): elevation 90°, it is the north pole; \(v = \tfrac{90}{180} + 0.5 = 1\), and the azimuth is undefined (the function returns 0, \(u = 0.5\)). The second is \((10, 0, 0)\): azimuth \(\operatorname{atan2}(10, 0) = 90°\), elevation 0: \(u = \tfrac{90}{360} + 0.5 = 0.75\), \(v = 0.5\).

b) Azimuth: \(\operatorname{atan2}(0.6, 0.8) = 36.87°\), so \(u = \tfrac{36.87}{360} + 0.5 = 0.6024\). Height: \(v = \tfrac{9}{12} = 0.75\).

c) The square texture is stretched over a rectangle of 6.28 × 12 m: the bricks will look almost twice as tall as they are wide. For each copy of the texture to cover a square of 1 × 1 m it has to be repeated about 6 times horizontally and 12 vertically: a UV scale of \((6, 12)\) (6 and not 6.28, so that the number of repetitions is an integer and the texture matches up at the seam), with repeat mode. The bricks will end up 5% wider than they are tall, which is imperceptible.

Solution 3.

a) \(\rho = 256/40 = 6.4\) texels per pixel; level \(\log_2 6.4 = 2.68\). Trilinear blends level 2 (64 texels) and level 3 (32 texels), with 68% of the latter.

b) and c)

mini = np.array([[0.0, 1.0], [0.5, 0.25]])
print(sample_nearest(mini, 0.6, 0.3), sample_bilinear(mini, 0.5, 0.5, "clamp"),
      round(sample_bilinear(mini, 0.4, 0.6, "clamp"), 4))
print(np.round(spherical_uv([0.0, 10.0, 0.0]), 4), np.round(spherical_uv([10.0, 0.0, 0.0]), 4),
      np.round(cylindrical_uv([0.6, 9.0, 0.8], 0.0, 12.0), 4))
print(np.round(transform_uv(uv_matrix(scale=(6.0, 12.0), pivot=(0.0, 0.0)), (1.0, 1.0)), 4))
print(round(np.log2(256.0 / 40.0), 2))
t, b = triangle_tangent([0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 0.0, -4.0],
                        [0.0, 0.0], [2.0, 0.0], [0.0, 2.0])
print(t, b + 0.0, np.cross(t, b) + 0.0)
print(np.round(transform_uv(uv_matrix(angle=np.radians(90.0)), (0.75, 0.5)), 4))
1.0 0.4375 0.3875
[0.5 1. ] [0.75 0.5 ] [0.6024 0.75  ]
[ 6. 12.]
2.68
[1. 0. 0.] [ 0.  0. -1.] [0. 1. 0.]
[0.5  0.75]

b) The tangent is \((1, 0, 0)\) and the bitangent \((0, 0, -1)\): on the floor, \(u\) grows toward \(+X\) and \(v\) toward \(-Z\) (toward the back, as seen from the initial camera). They are perpendicular, and \(\mathbf{T} \times \mathbf{B} = (0, 1, 0)\) is the normal of the floor: the TBN basis is right-handed. The UVs reach 2, so the texture is repeated twice over the 4 m: each copy measures 2 m. The function returns unit vectors, so that size is not reflected in them.

c) Relative to the center, \((0.75, 0.5)\) is the offset \((0.25, 0)\); rotated 90° counterclockwise it is \((0, 0.25)\), and back again, \((0.5, 0.75)\).

Conclusion

A texture is a grid of texels that is looked up with normalized coordinates \((u, v)\). The UVs travel as a vertex attribute and are interpolated with perspective correction; to read the image, the nearest texel is chosen or the four neighbors are blended with two chained linear interpolations, and the wrap mode decides what happens outside \([0, 1]\). When a pixel covers many texels, aliasing appears, which mipmaps avoid by averaging in advance and choosing the level with \(\log_2\) of the pixel's footprint. UVs are generated with planar, cylindrical or spherical projections—which are the coordinates from Module 3—or with a manual unwrap, taking care with the seams, and they are transformed and animated with 3×3 matrices. The same machinery makes it possible to store normals in tangent space, with the TBN basis derived from positions and UVs, or the environment of the scene, looked up by direction. mini3d gains checkerboard, wrap_index, sample_nearest, sample_bilinear, generate_mipmaps, sample_trilinear, planar_uv, cylindrical_uv, spherical_uv, uv_matrix, transform_uv and triangle_tangent.

This lesson brings Module 5 to a close. We have followed the complete journey of an object to the screen: we described it as a triangle mesh or as a mathematical surface that is tessellated; we took its vertices from local space to the world and to the camera with the model and view matrices; we projected them with an orthographic or perspective matrix and the division by \(w\); we clipped, went to pixels, rasterized each triangle and interpolated its attributes with barycentric coordinates, solving visibility with the z-buffer; and we decided the color of each point with a lighting model and with textures. We have built and tested each stage separately, as a loose piece of mini3d. What remains is to fit them together. That is the job of Module 6, "Practical Applications", which begins with the lesson "Computer Graphics": there we will assemble all these stages into a single pipeline that covers the journey from end to end and turns the scene of "Stellar Lighthouse" into an image.

© Copyright 2026. All rights reserved