Algorithm Search⌘K

Data structureintro

Cube map

Also called cubemap, cube environment map.

Six square textures on the faces of a cube that store a function of direction. A lookup picks the face of the largest component of the direction and divides the other two by it.

Time
Θ(n^2) fillΘ(1) lookup · store · texel_direction
Space
Θ(n^2) total
Where
n = the number of texels along one edge of a face
Properties
not concurrentnot externalnot persistent
Origin
Ned Greene, 1986

A cube map stores a function of direction, for example the radiance of the environment seen from one point, on the six faces of a cube centered at that point. Each face is a square texture of n×nn \times n texels. To read the value for a direction dd, the lookup picks the face of the axis where ∣d∣|d| is largest, divides the other two components by that largest one, and maps them to texture coordinates on the face. The mapping costs a few comparisons and one division, needs no trigonometry, and has no singular point like the poles of a latitude and longitude map. Greene proposed it in 1986, and every graphics API supports it in hardware. A cube map is the usual storage for environment mapping, image-based lighting and point light shadows; those pages describe what is stored, and this page describes the storage.

In plain words

Stand in the middle of a room shaped like a cube, and paint on each of its six sides (four walls, the floor and the ceiling) what you see through it. Every direction you can look in hits one side, at one point. To find the color for a direction, find the side it points at most, then find the spot on that side. The sides are flat pictures, so the hardware can store and filter them like any other texture. The price is that texels near the corners of a side cover a smaller part of the view than texels in the middle, and the edges between sides need extra care when you blend nearby texels.

The abstract type

A cube map is a map from directions in R3∖{0}\mathbb{R}^3 \setminus \{0\} (only the direction matters, not the length) to values, with a fixed resolution. Its operations:

  • lookup(d): the value stored for the direction dd, with nearest or bilinear filtering.
  • store(f, i, j, v): set the value of texel (i,j)(i, j) of face ff.
  • texel_direction(f, i, j): the unit direction of the center of a texel, which is the inverse of the lookup.
  • texel_solid_angle(f, i, j): the solid angle that the texel covers, needed for integrals over the sphere.
  • fill(g): store g(d)g(d) at the center direction of every texel.

Representation

The cube map holds six arrays of n×nn \times n values, one per face, in the OpenGL order +x,−x,+y,−y,+z,−z+x, -x, +y, -y, +z, -z. Texel (i,j)(i, j) of a face covers the face coordinates s∈[i/n,(i+1)/n]s \in [i/n, (i+1)/n] and t∈[j/n,(j+1)/n]t \in [j/n, (j+1)/n] and is stored in row jj, column ii. The face coordinates come from this table, which the page takes from the OpenGL specification:

face major axis mama scsc tctc
+x+x dxd_x −dz-d_z −dy-d_y
−x-x dxd_x +dz+d_z −dy-d_y
+y+y dyd_y +dx+d_x +dz+d_z
−y-y dyd_y +dx+d_x −dz-d_z
+z+z dzd_z +dx+d_x −dy-d_y
−z-z dzd_z −dx-d_x −dy-d_y

with s=(sc/∣ma∣+1)/2s = (sc / |ma| + 1)/2 and t=(tc/∣ma∣+1)/2t = (tc / |ma| + 1)/2. Other APIs flip some of these signs or order the faces differently, so code that moves cube maps between APIs has to remap the faces. The invariant is simple: six faces of n×nn \times n values, and texel (f,i,j)(f, i, j) is the region above. The page uses a right handed frame with yy up, as in OpenGL.

Operations

  1. CUBE-LOOKUP(C, d)
  2. 1face ← the axis of the largest |d_k|, with its sign ▷ ties: x, then y, then z
  3. 2(sc, tc, ma) ← the row of face in the table
  4. 3s ← (sc / |ma| + 1) / 2; t ← (tc / |ma| + 1) / 2
  5. 4i ← min(⌊s · n⌋, n - 1); j ← min(⌊t · n⌋, n - 1)
  6. 5return C.face[face][j][i]

Lookup. Line L1 finds the face that the ray from the center crosses: it leaves the cube where its largest component reaches 1. Line L2 takes the other two components with the signs of the table. Line L3 is a central projection onto the face plane, followed by the map from [−1,1][-1, 1] to [0,1][0, 1]. Line L4 picks the texel for the nearest filter; the minimum keeps s=1s = 1 inside the last texel. The direction need not be normalized, because line L3 divides by ∣ma∣|ma|. Cost: O(1)O(1). A bilinear lookup replaces lines L4 and L5 by the weighted mean of the four texels around (sn−1/2,tn−1/2)(s n - 1/2, t n - 1/2), see bilinear filtering.

  1. TEXEL-DIRECTION(C, f, i, j)
  2. 1s ← (i + 1/2) / n; t ← (j + 1/2) / n
  3. 2sc ← 2s - 1; tc ← 2t - 1
  4. 3p ← the point of face f with these sc and tc, for example (1, -tc, -sc) on +x
  5. 4return p / |p|

Texel direction. This inverts lines L2 and L3: the face fixes one coordinate of pp at ±1\pm 1, and the table, read backwards, gives the other two. Cost: O(1)O(1). fill calls it for each texel, Θ(n2)\Theta(n^2) calls per face.

Store. Write the value at row jj, column ii of the face. Cost: O(1)O(1).

Solid angle. A point (x,y)(x, y) of the face plane, with x,y∈[−1,1]x, y \in [-1, 1], sees the center at distance r=1+x2+y2r = \sqrt{1 + x^2 + y^2}, so dω=dA/r3d\omega = dA / r^3. Its integral over a texel [x0,x1]×[y0,y1][x_0, x_1] \times [y_0, y_1] is F(x1,y1)−F(x0,y1)−F(x1,y0)+F(x0,y0)F(x_1, y_1) - F(x_0, y_1) - F(x_1, y_0) + F(x_0, y_0) with F(x,y)=arctan⁡(xy/1+x2+y2)F(x, y) = \arctan(xy / \sqrt{1 + x^2 + y^2}) (a proved formula). Cost: O(1)O(1).

Example

A cube map with n=4n = 4 starts with every texel at 0.

step operation work result
1 store(-y, 2, 0, 5.0) write row 0, column 2 of face −y-y face −y-y has one texel with 5
2 lookup((0.3, -0.8, 0.5)) L1: $ d_y
3 lookup((1, 0, 0)) face +x+x, s=t=0.5s = t = 0.5, i=j=2i = j = 2 0.0
4 lookup((0.5, 0.5, 0.5)) a tie of all three axes, so face +x+x by the tie order; s=0s = 0, t=0t = 0 0.0, from texel (0,0)(0, 0) of +x+x
5 texel_direction(-y, 2, 0) s=0.625s = 0.625, t=0.125t = 0.125, sc=0.25sc = 0.25, tc=−0.75tc = -0.75, p=(0.25,−1,0.75)p = (0.25, -1, 0.75) (0.1961,−0.7845,0.5883)(0.1961, -0.7845, 0.5883)
6 texel_solid_angle(-y, 2, 0) the formula above with x∈[0,0.5]x \in [0, 0.5], y∈[−1,−0.5]y \in [-1, -0.5] 0.1204 sr

Step 5 returns a direction that step 2 would map to the same texel. In step 6, the four center texels of a face have 0.2014 sr, the edge texels 0.1204 sr and the corner texels 0.0815 sr; the 96 texels add up to 4π4\pi. A uniform split would give 4π/96=0.13094\pi / 96 = 0.1309 sr to each.

Correctness

The invariant is that the six arrays have n×nn \times n entries and that texel (f,i,j)(f, i, j) is the region of the face given by the table; only store changes an entry, and it changes one. The proof shows that line L1 selects the face where the ray leaves the cube, that ss and tt are in [0,1][0, 1], that texel_direction inverts lines L2 and L3, that the center of a texel maps back to that texel, that a lookup returns the last value stored in its texel, and that the solid angle formula holds and sums to 4π4\pi. All of these are proved properties. The tests compare the face with a brute force intersection of the ray with the six face planes, and the operations with a dict model.

Proof: Correctness of the cube map operationsfull

Setting. The cube is [−1,1]3[-1, 1]^3 and the faces are the six squares where one coordinate is ±1\pm 1. A cube map of size NN stores one value per texel (f,i,j)(f, i, j) with f∈{0,…,5}f \in \{0, \dots, 5\} (the OpenGL order +x,−x,+y,−y,+z,−z+x, -x, +y, -y, +z, -z) and 0≤i,j<N0 \le i, j < N. The invariant of the representation is: there are six arrays of N×NN \times N values, and texel (f,i,j)(f, i, j) is the part of face ff with s∈[i/N,(i+1)/N]s \in [i/N, (i+1)/N] and t∈[j/N,(j+1)/N]t \in [j/N, (j+1)/N], where (s,t)(s, t) are the face coordinates of the OpenGL table. No operation except store changes the arrays, and store changes one entry, so the invariant always holds. The claims are in exact arithmetic, for a direction d≠0d \ne 0.

Claim 1 (the face). Let aa be the axis of the largest ∣da∣|d_a| (line L1) and σ\sigma the sign of dad_a. The ray {λd:λ>0}\{\lambda d : \lambda > 0\} leaves the cube through face (a,σ)(a, \sigma), at the point p=d/∣da∣p = d / |d_a|.

Proof. The ray is inside the cube while λmax⁡k∣dk∣≤1\lambda \max_k |d_k| \le 1, so it leaves at λ=1/∣da∣\lambda = 1 / |d_a|. At that point pa=σp_a = \sigma and ∣pk∣=∣dk∣/∣da∣≤1|p_k| = |d_k| / |d_a| \le 1 for the other axes, so pp is on face (a,σ)(a, \sigma). If two components tie, pp is on the common edge of two faces, and both faces contain it; the fixed tie order picks one of them. □\square

Claim 2 (the face coordinates). Lines L2 and L3 give s,t∈[0,1]s, t \in [0, 1], and they are the coordinates of pp in the square of the face, an affine map of its two other components.

Proof. In each row of the table, scsc and tctc are the two components of dd other than dad_a, each with a fixed sign, and ma=dama = d_a. So sc/∣ma∣sc / |ma| and tc/∣ma∣tc / |ma| are ±pk\pm p_k for the two other axes kk, and they are in [−1,1][-1, 1] by Claim 1. Then s=(sc/∣ma∣+1)/2s = (sc / |ma| + 1)/2 and t=(tc/∣ma∣+1)/2t = (tc / |ma| + 1)/2 are in [0,1][0, 1]. □\square

Claim 3 (round trip). face_direction(f, s, t) returns d/∣d∣d / |d| for (f,s,t)=(f, s, t) = face_coords(d).

Proof. face_direction sets sc′=2s−1=sc/∣ma∣sc' = 2s - 1 = sc / |ma| and tc′=2t−1=tc/∣ma∣tc' = 2t - 1 = tc / |ma|. For each face it builds the vector with σ\sigma in coordinate aa and the other two coordinates from sc′sc' and tc′tc' with the inverse signs of the table. For example on +x+x, the table gives sc=−zsc = -z, tc=−ytc = -y, and the inverse is (1,−tc′,−sc′)=(1,y/∣x∣,z/∣x∣)=d/∣x∣(1, -tc', -sc') = (1, y/|x|, z/|x|) = d / |x|. The other five rows are checked the same way. So the vector is p=d/∣da∣p = d / |d_a|, and its normalization is d/∣d∣d / |d|. □\square

Claim 4 (the texel). Line L4 returns the texel that contains (s,t)(s, t): i=min⁡(⌊sN⌋,N−1)i = \min(\lfloor sN \rfloor, N - 1) satisfies i/N≤s≤(i+1)/Ni/N \le s \le (i+1)/N, and the same for jj. The center of texel (f,i,j)(f, i, j) maps back to (f,i,j)(f, i, j).

Proof. For s<1s < 1, ⌊sN⌋≤sN<⌊sN⌋+1\lfloor sN \rfloor \le sN < \lfloor sN \rfloor + 1; for s=1s = 1, the minimum gives i=N−1i = N - 1 and s=(i+1)/Ns = (i+1)/N. For the center, s=(i+1/2)/Ns = (i + 1/2)/N, so sc′=2s−1sc' = 2s - 1 has ∣sc′∣<1|sc'| < 1, and the same for tc′tc'. The direction of the center then has ∣pa∣=1>∣pk∣|p_a| = 1 > |p_k|, so line L1 selects ff with no tie, Claim 3 returns the same ss and tt, and ⌊(i+1/2)⌋=i\lfloor (i + 1/2) \rfloor = i. □\square

Claim 5 (store and lookup). After any sequence of store operations, lookup(d) returns the value of the last store to the texel of dd given by Claims 1 to 4, or the initial value 0 if there was none.

Proof. store(f, i, j, v) writes faces[f][j][i], and line L5 reads faces[f][j][i] for the (f,i,j)(f, i, j) of line L4. Each entry holds the last value written to it. □\square

Claim 6 (solid angle). The solid angle of the rectangle [x0,x1]×[y0,y1][x_0, x_1] \times [y_0, y_1] of a face is F(x1,y1)−F(x0,y1)−F(x1,y0)+F(x0,y0)F(x_1, y_1) - F(x_0, y_1) - F(x_1, y_0) + F(x_0, y_0) with F(x,y)=arctan⁡(xy/1+x2+y2)F(x, y) = \arctan\big(xy / \sqrt{1 + x^2 + y^2}\big), and the 6N26 N^2 texels have a total solid angle of 4π4\pi.

Proof. A point (x,y)(x, y) of the face plane at distance 1 from the center is at distance r=1+x2+y2r = \sqrt{1 + x^2 + y^2}, and the plane makes the angle with cos⁡=1/r\cos = 1/r with the ray. So dω=cos⁡/r2 dA=dA/r3d\omega = \cos / r^2\, dA = dA / r^3. With r2+x2y2=(1+x2)(1+y2)r^2 + x^2 y^2 = (1 + x^2)(1 + y^2), the derivative is ∂F/∂x=y/((1+x2)r)\partial F / \partial x = y / ((1 + x^2) r), and then ∂2F/∂x∂y=11+x2⋅r2−y2r3=1/r3\partial^2 F / \partial x \partial y = \frac{1}{1 + x^2} \cdot \frac{r^2 - y^2}{r^3} = 1 / r^3. The double integral of 1/r31/r^3 over the rectangle is the alternating sum of FF at the corners. A whole face has 4F(1,1)=4arctan⁡(1/3)=4π/64 F(1, 1) = 4 \arctan(1/\sqrt 3) = 4\pi/6, and the texels of a face partition it, so the total over six faces is 4π4\pi. □\square

Cost. Lines L1 to L5 do a constant number of comparisons, one division per coordinate and two array reads, so lookup, store and texel_direction cost O(1)O(1). fill evaluates the function once per texel, Θ(N2)\Theta(N^2) per face. The memory is 6N26 N^2 values. ■\blacksquare

Complexity

The model is the real RAM.

operation time note
lookup (nearest) Θ(1)\Theta(1) 3 comparisons, 2 divisions, 1 read
lookup (bilinear, one face) Θ(1)\Theta(1) 4 reads
store Θ(1)\Theta(1) 1 write
texel_direction Θ(1)\Theta(1) 1 square root
texel_solid_angle Θ(1)\Theta(1) 4 arctangents
fill Θ(n2)\Theta(n^2) one function call per texel
space Θ(n2)\Theta(n^2) 6n26 n^2 values; a full mipmap chain adds a third

The cost of a lookup does not depend on nn, because the face and the texel are computed, not searched.

Variants

  • Mipmapped cube maps. A mipmap chain per face gives filtered lookups. For prefiltered environments, each level stores a blur for one roughness, as in the split sum approximation.
  • Seamless filtering. Bilinear filtering inside one face, as in the code of this page, clamps at the edges and leaves a visible seam. Seamless filtering takes the texels across the edge from the neighbor face. OpenGL has it as the seamless cube map mode, and newer APIs such as Vulkan always filter this way.
  • Cube map arrays. Several cube maps in one texture, indexed by a layer, for many light probes.
  • Other parameterizations. A latitude and longitude map is easy to paint but wastes texels near the poles. A sphere map, the first form of environment mapping, depends on the view. Octahedral maps fold the sphere onto one square with less distortion than the cube. Dual paraboloid maps use two textures.
  • Equal area or warped cubes. A remap of ss and tt on each face makes the texel solid angles more even, at the cost of a little arithmetic per lookup.
  • Depth cube maps. For a point light, each face stores the distance to the nearest surface, for omnidirectional shadow mapping.

When to use it

Use a cube map whenever a value depends on a direction from one point: environment reflection, sky and irradiance maps, light probes and point light shadows. It is native to the hardware, it has no singularities, and its texels differ in solid angle by a factor of only about 33≈5.23\sqrt 3 \approx 5.2 between the center and the corners in the limit of fine texels. Choose a latitude and longitude map for storage and editing of captured panoramas, and convert to a cube map for rendering. Choose an octahedral map when six faces are inconvenient, for example in an atlas of many small probes.

Pitfalls

  • Wrong face table. Using the table of another API, or a yy down image convention, mirrors or rotates faces. Line L2 must match the table of the API that samples the texture, and the test of the round trip should run on the real data.
  • Equal weights in integrals. A sum over texels that ignores texel_solid_angle overweights the corners. The projection of an irradiance environment map needs the solid angle at each texel.
  • Seams. A per face bilinear filter, or a blur that runs on each face alone, gives a visible line at the edges, worst in prefiltered maps at high roughness. Use seamless filtering, or filter in direction space across faces.
  • Texel centers. The center of texel ii is at s=(i+1/2)/ns = (i + 1/2)/n. Using i/ni/n in line L6 shifts every texel by half a texel and breaks the round trip.
  • Ties at edges and corners. On an edge, two faces hold the same direction. Line L1 must use one fixed tie rule; mixing >> and ≥\ge between code paths gives two different texels for the same direction.
  • Gamma. Store linear values for lighting, or decode sRGB faces before any filtering, see gamma correction.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cube_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cube-map/. The authors are listed in prov/M0T5ZN.jsonl.

"""A cube map: six square textures that store a function of direction.

The faces are in the OpenGL order +x, -x, +y, -y, +z, -z (indices 0 to 5).
A direction selects the face of its major axis, the axis of the largest
absolute component; ties go to x before y before z. The face coordinates
(sc, tc) come from the OpenGL table, and s = (sc / |ma| + 1) / 2,
t = (tc / |ma| + 1) / 2 are in [0, 1]. Texel (i, j) of a face of size N
covers s in [i / N, (i + 1) / N] and t in [j / N, (j + 1) / N], and it is
stored at faces[f][j][i].

Precondition: directions are not the zero vector; they need not be unit.
Cost: O(1) for lookup, store and the direction of a texel; Theta(N^2) memory
per face, 6 N^2 texels in all.
"""

import math

Vec = tuple[float, float, float]

POS_X, NEG_X, POS_Y, NEG_Y, POS_Z, NEG_Z = range(6)


def major_axis(d: Vec) -> int:
    """The face of the largest |component|, with ties to x, then y, then z."""
    x, y, z = d
    ax, ay, az = abs(x), abs(y), abs(z)
    if ax >= ay and ax >= az:
        return POS_X if x > 0 else NEG_X
    if ay >= az:
        return POS_Y if y > 0 else NEG_Y
    return POS_Z if z > 0 else NEG_Z


def face_coords(d: Vec) -> tuple[int, float, float]:
    """The face and the coordinates s, t in [0, 1] of a direction (OpenGL table)."""
    x, y, z = d
    face = major_axis(d)  # @line L1
    if face == POS_X:  # @line L2
        sc, tc, ma = -z, -y, x
    elif face == NEG_X:
        sc, tc, ma = z, -y, x
    elif face == POS_Y:
        sc, tc, ma = x, z, y
    elif face == NEG_Y:
        sc, tc, ma = x, -z, y
    elif face == POS_Z:
        sc, tc, ma = x, -y, z
    else:
        sc, tc, ma = -x, -y, z
    s = (sc / abs(ma) + 1.0) / 2.0  # @line L3
    t = (tc / abs(ma) + 1.0) / 2.0
    return face, s, t


def face_direction(face: int, s: float, t: float) -> Vec:
    """The inverse of face_coords: the unit direction of a point (s, t) of a face."""
    sc, tc = 2.0 * s - 1.0, 2.0 * t - 1.0  # @line L7
    if face == POS_X:  # @line L8
        d = (1.0, -tc, -sc)
    elif face == NEG_X:
        d = (-1.0, -tc, sc)
    elif face == POS_Y:
        d = (sc, 1.0, tc)
    elif face == NEG_Y:
        d = (sc, -1.0, -tc)
    elif face == POS_Z:
        d = (sc, -tc, 1.0)
    else:
        d = (-sc, -tc, -1.0)
    r = math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2])
    return (d[0] / r, d[1] / r, d[2] / r)  # @line L9


def _area(x: float, y: float) -> float:
    """The solid angle of the part of a face from its center to (x, y), x, y in [-1, 1]."""
    return math.atan2(x * y, math.sqrt(x * x + y * y + 1.0))


class CubeMap:
    """Six faces of size by size texels, each texel holding one float."""

    def __init__(self, size: int = 1) -> None:
        if size < 1:
            raise ValueError("size must be at least 1")
        self.size = size
        self.faces = [[[0.0] * size for _ in range(size)] for _ in range(6)]

    def texel_of(self, d: Vec) -> tuple[int, int, int]:
        """The face and the texel (i, j) that contain the direction d."""
        face, s, t = face_coords(d)
        n = self.size
        i = min(int(s * n), n - 1)  # @line L4
        j = min(int(t * n), n - 1)
        return face, i, j

    def lookup(self, d: Vec) -> float:
        """CUBE-LOOKUP: the value of the texel that contains d (nearest filter)."""
        face, i, j = self.texel_of(d)
        return self.faces[face][j][i]  # @line L5

    def store(self, face: int, i: int, j: int, value: float) -> None:
        """Set the value of texel (i, j) of a face."""
        self.faces[face][j][i] = value

    def texel_direction(self, face: int, i: int, j: int) -> Vec:
        """The unit direction of the center of texel (i, j)."""
        n = self.size
        return face_direction(face, (i + 0.5) / n, (j + 0.5) / n)  # @line L6

    def texel_solid_angle(self, face: int, i: int, j: int) -> float:
        """The exact solid angle of texel (i, j); it does not depend on the face."""
        n = self.size
        x0, x1 = 2.0 * i / n - 1.0, 2.0 * (i + 1) / n - 1.0
        y0, y1 = 2.0 * j / n - 1.0, 2.0 * (j + 1) / n - 1.0
        return _area(x1, y1) - _area(x0, y1) - _area(x1, y0) + _area(x0, y0)

    def fill(self, f) -> None:
        """Store f(direction) at the center of every texel."""
        n = self.size
        for face in range(6):
            for j in range(n):
                for i in range(n):
                    self.faces[face][j][i] = f(self.texel_direction(face, i, j))

    def lookup_bilinear(self, d: Vec) -> float:
        """Bilinear filter inside the face of d, clamped at the face edges.

        This is the simple filter that ignores the neighbour faces, so it
        shows a seam at the edges; see the page for seamless filtering.
        """
        face, s, t = face_coords(d)
        n = self.size
        u = min(max(s * n - 0.5, 0.0), n - 1.0)
        v = min(max(t * n - 0.5, 0.0), n - 1.0)
        i0, j0 = min(int(u), n - 1), min(int(v), n - 1)
        i1, j1 = min(i0 + 1, n - 1), min(j0 + 1, n - 1)
        fu, fv = u - i0, v - j0
        a = self.faces[face]
        top = a[j0][i0] * (1 - fu) + a[j0][i1] * fu
        bot = a[j1][i0] * (1 - fu) + a[j1][i1] * fu
        return top * (1 - fv) + bot * fv

    def check_invariant(self) -> None:
        """Six faces, each size by size, of floats."""
        assert len(self.faces) == 6
        for face in self.faces:
            assert len(face) == self.size
            for row in face:
                assert len(row) == self.size
                assert all(isinstance(x, float) for x in row)
test_cube_map.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cube-map/. The authors are listed in prov/M0T5ZN.jsonl.

"""Tests of the cube map against ray-plane intersection, a dict model and quadrature.

The face selection is compared with a brute force intersection of the ray
with the six face planes, direction to face and back is a round trip, the
texel of a texel center is that texel, random stores and lookups agree with
a dict model, and the texel solid angles match a direct quadrature and add
up to 4 pi.
"""

import math
import random

from cube_map import CubeMap, face_coords, face_direction, major_axis

AXES = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]


def rand_dir(rng: random.Random) -> tuple[float, float, float]:
    while True:
        v = (rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1))
        r = math.sqrt(sum(c * c for c in v))
        if r > 1e-6:
            return (v[0] / r, v[1] / r, v[2] / r)


def face_by_ray_planes(d) -> int:
    """Brute force: the face plane the ray from the center hits inside the square."""
    best, best_t = -1, math.inf
    for f, a in enumerate(AXES):
        dn = sum(x * y for x, y in zip(d, a))
        if dn <= 0:
            continue
        t = 1.0 / dn
        p = [t * c for c in d]
        others = [p[k] for k in range(3) if a[k] == 0]
        if all(abs(c) <= 1.0 + 1e-12 for c in others) and t < best_t:
            best, best_t = f, t
    return best


def test_face_matches_ray_plane_intersection() -> None:
    rng = random.Random(1)
    for _ in range(3000):
        d = rand_dir(rng)
        assert major_axis(d) == face_by_ray_planes(d)


def test_check_value_of_the_page() -> None:
    face, s, t = face_coords((0.3, -0.8, 0.5))
    assert face == 3 and abs(s - 0.6875) < 1e-15 and abs(t - 0.1875) < 1e-15
    c = CubeMap(4)
    assert c.texel_of((0.3, -0.8, 0.5)) == (3, 2, 0)


def test_direction_round_trip() -> None:
    rng = random.Random(2)
    for _ in range(3000):
        d = rand_dir(rng)
        face, s, t = face_coords(d)
        assert 0.0 <= s <= 1.0 and 0.0 <= t <= 1.0
        back = face_direction(face, s, t)
        assert all(abs(a - b) < 1e-12 for a, b in zip(back, d))
        # Scaling the direction changes nothing.
        assert face_coords((3 * d[0], 3 * d[1], 3 * d[2]))[0] == face


def test_face_centers_and_edges() -> None:
    for f, a in enumerate(AXES):
        assert all(abs(x - y) < 1e-15 for x, y in zip(face_direction(f, 0.5, 0.5), a))
    rng = random.Random(3)
    # A point on the edge of one face lies on the edge of a neighbor face.
    for _ in range(500):
        f = rng.randrange(6)
        u = rng.random()
        for s, t in ((0.0, u), (1.0, u), (u, 0.0), (u, 1.0)):
            d = face_direction(f, s, t)
            g, s2, t2 = face_coords(d)
            assert all(abs(x - y) < 1e-12 for x, y in zip(face_direction(g, s2, t2), d))
            if g != f:
                assert min(s2, 1 - s2, t2, 1 - t2) < 1e-12


def test_texel_center_round_trip() -> None:
    for n in (1, 2, 3, 8):
        c = CubeMap(n)
        for f in range(6):
            for j in range(n):
                for i in range(n):
                    assert c.texel_of(c.texel_direction(f, i, j)) == (f, i, j)


def test_random_operations_against_a_dict() -> None:
    rng = random.Random(4)
    n = 5
    c = CubeMap(n)
    model = {}
    for _ in range(3000):
        if rng.random() < 0.5:
            key = (rng.randrange(6), rng.randrange(n), rng.randrange(n))
            v = rng.uniform(-10, 10)
            c.store(*key, v)
            model[key] = v
        else:
            d = rand_dir(rng)
            assert c.lookup(d) == model.get(c.texel_of(d), 0.0)
            key = (rng.randrange(6), rng.randrange(n), rng.randrange(n))
            assert c.lookup(c.texel_direction(*key)) == model.get(key, 0.0)
        c.check_invariant()


def test_solid_angles() -> None:
    n = 6
    c = CubeMap(n)
    total = sum(c.texel_solid_angle(f, i, j) for f in range(6) for i in range(n) for j in range(n))
    assert abs(total - 4 * math.pi) < 1e-12
    # Direct quadrature of dA / (1 + x^2 + y^2)^(3/2) on the face plane.
    k = 40
    for i, j in ((0, 0), (2, 3), (5, 1)):
        x0, y0, h = 2 * i / n - 1, 2 * j / n - 1, 2 / n
        q = 0.0
        for a in range(k):
            for b in range(k):
                x = x0 + (a + 0.5) * h / k
                y = y0 + (b + 0.5) * h / k
                q += (h / k) ** 2 / (1 + x * x + y * y) ** 1.5
        assert abs(q - c.texel_solid_angle(0, i, j)) < 1e-4 * q
    # A corner texel is smaller than a center texel.
    assert c.texel_solid_angle(0, 0, 0) < c.texel_solid_angle(0, 2, 2)


def test_fill_and_bilinear() -> None:
    c = CubeMap(8)
    c.fill(lambda d: d[0] + 2 * d[1] - d[2])
    for f in range(6):
        for j in range(8):
            for i in range(8):
                d = c.texel_direction(f, i, j)
                assert abs(c.lookup(d) - (d[0] + 2 * d[1] - d[2])) < 1e-12
                assert abs(c.lookup_bilinear(d) - c.lookup(d)) < 1e-12

History

Blinn and Newell (1976) indexed a reflection map by the two angles of the reflected direction. Miller and Hoffman (1984) noted that a map can be stored as six perspective views, and Greene (1986) worked out the cube as a projection of the world, with its sampling and filtering, and used it for environment mapping. Hardware cube map textures arrived around 1999 and became part of OpenGL 1.3 and Direct3D 7. Since then the cube map has been the common way to store environments, prefiltered reflections and probes in real-time rendering.

References

  1. Ned Greene, Environment mapping and other applications of world projections, IEEE Computer Graphics and Applications 6(11), 1986, 21 to 29, the cube projection of the environment, its six perspective faces, and its comparison with other world projections
  2. Mark Segal and Kurt Akeley, The OpenGL Graphics System, A Specification, version 4.6 (core profile), Khronos Group, the section on cube map texture selection (the table of the major axis and of sc, tc and ma for each face) and the seamless cube map filtering rule
  3. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 10, Local Illumination (the part on cube mapping and environment map projections)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.fill
  • a full proof of time.lookup
  • a full proof of time.store
  • a full proof of time.texel_direction
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M0T5ZN/text.yaml