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
- Model
- Real RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- 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 texels. To read the value for a direction , the lookup picks the face of the axis where 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 (only the direction matters, not the length) to values, with a fixed resolution. Its operations:
lookup(d): the value stored for the direction , with nearest or bilinear filtering.store(f, i, j, v): set the value of texel of face .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 at the center direction of every texel.
Representation
The cube map holds six arrays of values, one per face, in the OpenGL order . Texel of a face covers the face coordinates and and is stored in row , column . The face coordinates come from this table, which the page takes from the OpenGL specification:
| face | major axis | ||
|---|---|---|---|
with and . 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 values, and texel is the region above. The page uses a right handed frame with up, as in OpenGL.
Operations
CUBE-LOOKUP(C, d)- 1
face ← the axis of the largest |d_k|, with its sign ▷ ties: x, then y, then z - 2
(sc, tc, ma) ← the row of face in the table - 3
s ← (sc / |ma| + 1) / 2; t ← (tc / |ma| + 1) / 2 - 4
i ← min(⌊s · n⌋, n - 1); j ← min(⌊t · n⌋, n - 1) - 5
return 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 to . Line L4 picks the texel for the nearest filter; the minimum keeps inside the last texel. The direction need not be normalized, because line L3 divides by . Cost: . A bilinear lookup replaces lines L4 and L5 by the weighted mean of the four texels around , see bilinear filtering.
TEXEL-DIRECTION(C, f, i, j)- 1
s ← (i + 1/2) / n; t ← (j + 1/2) / n - 2
sc ← 2s - 1; tc ← 2t - 1 - 3
p ← the point of face f with these sc and tc, for example (1, -tc, -sc) on +x - 4
return p / |p|
Texel direction. This inverts lines L2 and L3: the face fixes one coordinate of at , and the table, read backwards, gives the other two. Cost: . fill calls it for each texel, calls per face.
Store. Write the value at row , column of the face. Cost: .
Solid angle. A point of the face plane, with , sees the center at distance , so . Its integral over a texel is with (a proved formula). Cost: .
Example
A cube map with starts with every texel at 0.
| step | operation | work | result |
|---|---|---|---|
| 1 | store(-y, 2, 0, 5.0) |
write row 0, column 2 of face | face has one texel with 5 |
| 2 | lookup((0.3, -0.8, 0.5)) |
L1: $ | d_y |
| 3 | lookup((1, 0, 0)) |
face , , | 0.0 |
| 4 | lookup((0.5, 0.5, 0.5)) |
a tie of all three axes, so face by the tie order; , | 0.0, from texel of |
| 5 | texel_direction(-y, 2, 0) |
, , , , | |
| 6 | texel_solid_angle(-y, 2, 0) |
the formula above with , | 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 . A uniform split would give sr to each.
Correctness
The invariant is that the six arrays have entries and that texel 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 and are in , 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 . 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 and the faces are the six squares where one coordinate is . A cube map of size stores one value per texel with (the OpenGL order ) and . The invariant of the representation is: there are six arrays of values, and texel is the part of face with and , where 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 .
Claim 1 (the face). Let be the axis of the largest (line L1) and the sign of . The ray leaves the cube through face , at the point .
Proof. The ray is inside the cube while , so it leaves at . At that point and for the other axes, so is on face . If two components tie, is on the common edge of two faces, and both faces contain it; the fixed tie order picks one of them.
Claim 2 (the face coordinates). Lines L2 and L3 give , and they are the coordinates of in the square of the face, an affine map of its two other components.
Proof. In each row of the table, and are the two components of other than , each with a fixed sign, and . So and are for the two other axes , and they are in by Claim 1. Then and are in .
Claim 3 (round trip). face_direction(f, s, t) returns for face_coords(d).
Proof. face_direction sets and . For each face it builds the vector with in coordinate and the other two coordinates from and with the inverse signs of the table. For example on , the table gives , , and the inverse is . The other five rows are checked the same way. So the vector is , and its normalization is .
Claim 4 (the texel). Line L4 returns the texel that contains : satisfies , and the same for . The center of texel maps back to .
Proof. For , ; for , the minimum gives and . For the center, , so has , and the same for . The direction of the center then has , so line L1 selects with no tie, Claim 3 returns the same and , and .
Claim 5 (store and lookup). After any sequence of store operations, lookup(d) returns the value of the last store to the texel of 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 of line L4. Each entry holds the last value written to it.
Claim 6 (solid angle). The solid angle of the rectangle of a face is with , and the texels have a total solid angle of .
Proof. A point of the face plane at distance 1 from the center is at distance , and the plane makes the angle with with the ray. So . With , the derivative is , and then . The double integral of over the rectangle is the alternating sum of at the corners. A whole face has , and the texels of a face partition it, so the total over six faces is .
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 . fill evaluates the function once per texel, per face. The memory is values.
Complexity
The model is the real RAM.
| operation | time | note |
|---|---|---|
lookup (nearest) |
3 comparisons, 2 divisions, 1 read | |
lookup (bilinear, one face) |
4 reads | |
store |
1 write | |
texel_direction |
1 square root | |
texel_solid_angle |
4 arctangents | |
fill |
one function call per texel | |
| space | values; a full mipmap chain adds a third |
The cost of a lookup does not depend on , 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 and 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 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 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_angleoverweights 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 is at . Using 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 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M0T5ZN Edit this page History Report an error Markdown