Data structureadvanced
Geometry clipmaps
Also called terrain clipmaps.
Render terrain as nested regular grids centered on the viewer. Each coarser level has half the resolution of the level inside it, and the levels update incrementally as the viewer moves.
- Time
- Θ(L n^2) build · meshO(n d) move
- Space
- Θ(L n^2) total
- Where
- L = the number of levels; d = the number of cells by which the windows move, summed over the levels; n = the number of vertices along each side of a level
- Model
- Real RAM
- Properties
- not concurrentnot externalnot persistent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frank Losasso, Hugues Hoppe, 2004
A geometry clipmap keeps a terrain as a stack of regular grids of the same size , all centered on the viewer, where each level has twice the spacing of the level inside it. Each frame the renderer draws the finest grid and, for each coarser level, the ring that the finer level does not cover. As the viewer moves, each level writes only the new rows and columns into a wraparound array. ROAM and view-dependent refinement decide per triangle each frame; here the layout is fixed by the viewer position alone, and the GPU draws large regular blocks. The texture clipmap is the same structure for the levels of a texture.
In plain words
Lay a fine square net over the ground under the viewer. Around it lay a net with holes twice as large, which covers four times the area, and cut out its middle, where the fine net already is. Repeat this a few times. Near the viewer the ground has small triangles, and far away it has large ones, and a far triangle looks about as large on the screen as a near one.
When the viewer walks, every net moves with them, but only in whole steps of its own size. A move adds a strip of new points on one side and drops a strip on the other side. The new points go into the places of the old ones, so nothing else is copied.
Where two nets meet, the fine net bends its heights toward the coarse net, so the two fit without a gap or a step.
The abstract type
A geometry clipmap of a height function is a value that depends on the viewer position in the plane, with these operations.
- build(v): make the levels for the viewer , with the heights of at their vertices.
- move(v): change the viewer to , so that every level holds the heights of its new window.
- mesh(v): give the triangles and the heights that cover the window of the coarsest level, from fine near to coarse far from it, with no cracks.
- get(l, p): the stored height of the vertex of level .
After build or move, get for each vertex of the window of level .
Representation
Domain points are integer pairs in units of the finest grid. Level has the spacing and vertices with odd, so its window is a square of side . Its lower corner, the origin , is a multiple of , so that the vertices of level in the window are every other vertex of level . Each level stores its heights in an array with toroidal addressing: the vertex goes to the slot , as in a circular buffer in two dimensions. The slot of a vertex depends only on the vertex, not on the window, so a vertex that stays in the window keeps its slot.
Operations
ORIGIN(v, l)- 1
o_l ← the multiple of s_(l+1) nearest to v - (n - 1) s_l / 2, in each coordinate MOVE(l, o) ▷ the new origin o from line L1- 2
for each vertex p of the new window of level l that is not in the old window do - 3
T_l[(p_x / s_l) mod n, (p_y / s_l) mod n] ← h(p) - 4
o_l ← o MESH(v)- 5
for each level l and each cell of its window that is not inside the window of level l - 1 do emit its two triangles - 6
for each level l ≥ 1 and each edge (a, b) of level l on the border of the window of level l - 1 do emit the zero-area triangle (a, b, o) with o the midpoint - 7
each vertex p of level l < L - 1 gets z' = (1 - alpha) h(p) + alpha (h(a) + h(c))/2, with alpha = clamp(1 - b_p / w, 0, 1)
In line L7, and are the ends of the edge of level through ( when is a vertex of level ), and is the distance of from the border of its window in cells of level . So on the border and 0 at cells or more inside it, and the heights of the level blend into the coarser level over a transition region of width . This is the geomorph of the method. The coarsest level keeps .
Line L5 gives the ring of each level. In the GPU version of Asirvatham and Hoppe, with and , the ring is made of 12 blocks of vertices, 4 fix-ups of and an L-shaped trim, and the same few vertex buffers are drawn at every level with a scale and an offset. The trim is needed because the origin of line L1 is a multiple of , so the fine window is not at the exact center of the coarse one. The code emits the ring cell by cell, which gives the same surface.
Example
Take , levels, and the viewer at . Line L1 gives these windows.
| level | spacing | window to | side | ring width in cells, low and high side |
|---|---|---|---|---|
| 0 | 1 | to | 14 | all cells |
| 1 | 2 | to | 28 | 3 and 4 |
| 2 | 4 | to | 56 | 3 and 4 |
| 3 | 8 | to | 112 | 3 and 4 |
Each ring is at least cells wide by the bound of the proof, and here it is 3 or 4 because the origin is rounded to a multiple of the coarser spacing. Level 0 draws its cells, and each ring draws cells, so the mesh has triangles. Each finer window has 28 coarse edges on its border, so line L6 adds zero-area triangles. For the of the GPU version the bound is 62 cells.
A move. At level 1 the vertex columns have from to 8, in the slots 9 to 14 and 0 to 8. A move of the viewer that moves the origin by in gives the columns to 10. The two new columns 9 and 10 go into the slots 9 and 10, which held the dropped columns and . So the move writes heights and copies nothing.
The morph. With , a vertex on the border of its window has and takes the mean of the two coarse vertices around it, one cell inside has , and two cells inside has .
Correctness
The proof file gives the arguments, and the tests check them for 10 random viewers and 40 random moves.
- Nesting. If , each window lies strictly inside the next coarser one, its corners are vertices of the coarser level, and the ring is at least coarse cells wide on each side (a proved property).
- Tiling. The triangles of line L5 for all levels cover the coarsest window once, with disjoint interiors (a proved property; the test sums the areas).
- Closed edges. With the triangles of line L6, every directed edge is paired with its reverse, except on the outer border (a proved property; the test counts the directed edges).
- No cracks. If , a point shared by two levels has the same height in both, and the three corners of each zero-area triangle are collinear in space (a proved property). The width of Asirvatham and Hoppe meets the condition for ; the value is a tuning.
- The update. The toroidal slot is one to one on a window, and after line L4 the array equals a fresh fill of the new window; the move writes exactly the new vertices, of them for a move by cells (a proved property).
The proof covers the surface of one frame. It does not show that the surface is continuous in time when an origin moves, and the tests do not check it.
Proof: The clipmap windows nest, the rings and the zero-area triangles form a surface without cracks, and the toroidal update gives the same arrays as a fresh fillfull
We use the notation of the page. Domain points are integer pairs in units of the finest grid. Level has vertices with the spacing , so its window has the side . For the viewer , line L1 sets the origin (the lower corner of the window) to the multiple of nearest to , per coordinate. The levels are , and is the height of a domain point. The arithmetic is exact.
The windows nest
Lemma 1. If , then for each the window of level lies strictly inside the window of level , its corners are vertices of level , and on each side the ring between them is at least cells of level wide.
Proof. Per coordinate, and . So
The upper sides differ by , and the same two bounds give , so this gap has the same lower bound. The origin is a multiple of , and the side of the fine window is , an even multiple of because is odd, so all four corners of the fine window are vertices of level .
For the bound is 2 cells, and for the of Asirvatham and Hoppe it is 62. The test of the code asserts the strict nesting.
Because the corners of the fine window are vertices of level , each cell of level lies inside the fine window or meets it only on its boundary. Line L5 keeps the cells of the second kind: the ring.
The mesh tiles the domain
Lemma 2. The triangles of line L5 for all levels tile the window of level : the triangles have disjoint interiors and their union is the window.
Proof. By induction on . Level 0 has all its cells, so its triangles tile its window. The ring of level is the set of cells of the window of level that are not in the window of level , so by the remark after Lemma 1 the ring and the window of level tile the window of level .
No cracks
Lines L5 and L6 output triangles in the counterclockwise order of the domain. Two triangles are paired along an edge when one has it as the directed edge and the other as .
Lemma 3. Every directed edge of the mesh, with the zero-area triangles of line L6, is paired with exactly one other edge, except the edges on the border of the window of level .
Proof. Inside one level, an edge between two cells or across a diagonal is used once in each direction by the two counterclockwise triangles that share it. The only other edges are on the border of a window of level . Take a cell edge of level on this border, from to in the counterclockwise order around the fine window, and let be its midpoint, which is a vertex of level . The ring of level lies outside the fine window, so its counterclockwise triangle traverses this edge as . The fine triangles lie inside, so they traverse the two half edges as and . Line L6 adds the triangle with the directed edges , and . These are paired with , and , in this order.
So, as a set of triangles over the domain, the mesh is closed except on its outer border. A T-junction, where the vertex of the fine level lies inside the coarse edge , is closed by a triangle of zero area. It remains to show that the heights make this triangle flat in space, so that no gap shows.
Theorem 4. Let , with . With the heights of line L7, (a) a domain point that is a vertex of two levels has the same height in both, and (b) the three corners of each triangle of line L6 are collinear in space. So the surface has no cracks.
Proof. Line L7 gives a vertex of level the height , where and are the ends of the edge of level through (coarse_parents), and when is a vertex of level . The factor is 1 on the border of the window of level and 0 at or more cells of level from it. The coarsest level keeps .
(a) A vertex of level that is also a vertex of level has , so its height at level is for every . At level , a domain point that is shared with level and is drawn by a ring triangle of level lies on the border of the window of level . By Lemma 1 it is at least cells of level from the border of its own window, so there and its height is as well. (Vertices of level that lie strictly inside the window of level are not used by any triangle.)
(b) A triangle of line L6 has the corners and of level , with the height by (a), and the midpoint of level on the border of the window of level . There , and the edge of level through is itself, so has the height . The point is the midpoint of the segment between and .
The condition of the theorem holds for the transition width of Asirvatham and Hoppe when : is . The width itself is a tuning. Over the transition region the height of each vertex is affine in , and is continuous in the position of the viewer except where the origin moves, so the morph removes the jumps that a level switch would make inside the region; the proof that the surface does not jump when the origin moves is not given here, and the page only tests the static mesh.
The toroidal update
Proposition 5. The array index is one to one on the vertices of a window of level . After MOVE (lines L2 to L4) the array equals the array of a fresh fill of the new window, and the move writes exactly the vertices of the new window that are not in the old one.
Proof. The vertices of a window have in consecutive integers, and these have distinct residues mod ; the same holds for . So the index is one to one on a window. The index depends only on , so a vertex in both windows keeps its slot and its stored value . Line L3 writes into the slot of each new vertex, and line L4 sets the origin. So each vertex of the new window has in its slot, as in a fresh fill. Lines L2 and L3 write only when is not in the old window.
So a move of the origin by along one axis, the smallest move that line L1 makes, writes samples, and a move by cells writes samples when .
Complexity
| operation | time | note |
|---|---|---|
| build | one height per vertex of each level | |
| move | a level that moves by cells makes writes | |
| mesh | each ring has cells; on the GPU it is a fixed set of draws | |
| get | one slot |
The space is : arrays of heights, against the of a full grid at the finest spacing over the coarsest window. The code finds the new vertices with a set difference, which costs per move; the bound above is for writing the strips directly, as the paper does.
Variants
- GPU blocks. The footprints of Asirvatham and Hoppe draw each ring from a few shared vertex buffers, and the vertex shader reads the heights from the level texture and computes the morph.
- Compression and synthesis. Losasso and Hoppe keep the full terrain in a compressed pyramid and fill new strips by decompression, and they can add detail beyond the data for the finest levels.
- Morph from the viewer. The code computes from the distance to the window border. Computing it from the distance to the viewer, as a renderer would do in the vertex shader, makes change smoothly when the viewer moves, not in steps when an origin moves.
- Clipmaps for textures. The texture clipmap uses the same nested windows and toroidal update for the levels of a mipmap.
- Culling. Blocks of a ring that are outside the view frustum can be skipped, which frustum culling of the block bounds does at a small cost.
When to use it
Use geometry clipmaps for a large height field that is seen from a viewer near the ground, such as a flight or a driving simulator, when the GPU should draw large regular blocks and the CPU should do little work per frame. The error is not adapted to the shape of the terrain: a flat plain gets as many triangles as a mountain range, so for very uneven terrain ROAM or view-dependent refinement can need fewer triangles. For a mesh that is not a height field, the method does not apply.
Pitfalls
- An origin on the fine spacing. If line L1 rounds to a multiple of in place of , the corners of the window of level are not vertices of level , the ring of line L5 cuts through coarse cells, and the levels do not tile.
- A slot relative to the origin. If line L3 uses the slot , the slot of a vertex changes when the origin moves, and each move must copy all heights to their new slots.
- Rewriting the window. If line L2 runs over every vertex of the new window, the result is right, but each move writes heights in place of a strip.
- No zero-area triangles. Without line L6, the midpoint of each coarse edge on a level border is a T-junction. Even when the heights agree, rounding in the rasterizer can leave single-pixel holes along it.
- A transition region that is too wide. If in line L7 is larger than the ring, a vertex of the coarser level on the inner border of its ring has , its height differs from the height of the same point in the finer level, and a crack opens.
- A morph toward the wrong heights. If line L7 blends toward the mean of two fine neighbors in place of the two coarse vertices and , the border of the level does not match the coarse edge, and the zero-area triangles are no longer flat.
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/geometry-clipmaps/. The authors are listed in prov/03429S.jsonl.
"""Geometry clipmaps: nested square grids around the viewer.
Domain points are integer pairs (x, y) in units of the finest grid; the
height is a separate value. Level l has n x n vertices (n = 2^k - 1) with
spacing s_l = 2^l. Its window is the square of side (n - 1) s_l whose lower
corner, the origin, is a multiple of s_(l+1), so the grid of level l + 1 is
every other vertex of level l. Each level keeps its heights in an n x n
array with wraparound (toroidal) addressing.
"""
from fractions import Fraction
from math import floor
def origin(v, n, l):
"""The lower corner of the window of level l for the viewer v."""
s, s2 = 2 ** l, 2 ** (l + 1)
return tuple(s2 * floor(Fraction(c - Fraction((n - 1) * s, 2), s2) + Fraction(1, 2)) for c in v) # @line L1
def window(o, n, l):
s = 2 ** l
return (o[0], o[1], o[0] + (n - 1) * s, o[1] + (n - 1) * s)
def points(o, n, l):
s = 2 ** l
return [(o[0] + i * s, o[1] + j * s) for i in range(n) for j in range(n)]
class Level:
"""The height array of one level with toroidal addressing."""
def __init__(self, n, l, height, o):
self.n, self.l, self.height = n, l, height
self.o = o
self.t = [[None] * n for _ in range(n)]
for p in points(o, n, l):
self._store(p)
def _index(self, p):
s = 2 ** self.l
return (p[0] // s) % self.n, (p[1] // s) % self.n
def _store(self, p):
i, j = self._index(p)
self.t[i][j] = self.height(p) # @line L3
def get(self, p):
i, j = self._index(p)
return self.t[i][j]
def move(self, o):
"""Shift the window to origin o. Returns the number of samples written."""
old = set(points(self.o, self.n, self.l))
count = 0
for p in points(o, self.n, self.l): # @line L2
if p not in old:
self._store(p)
count += 1
self.o = o # @line L4
return count
def coarse_parents(p, l):
"""The ends of the level l + 1 edge whose midpoint is p, or (p, p) on the level l + 1 grid."""
s = 2 ** l
ox, oy = (p[0] // s) % 2, (p[1] // s) % 2
if ox and oy:
return (p[0] - s, p[1] - s), (p[0] + s, p[1] + s)
if ox:
return (p[0] - s, p[1]), (p[0] + s, p[1])
if oy:
return (p[0], p[1] - s), (p[0], p[1] + s)
return p, p
def morph_height(p, l, win, height, w, last):
"""z' = (1 - alpha) z_f + alpha z_c, alpha = 1 on the window border and 0 from w cells inward."""
s = 2 ** l
if last:
return Fraction(height(p))
b = Fraction(min(p[0] - win[0], win[2] - p[0], p[1] - win[1], win[3] - p[1]), s)
alpha = min(max(1 - b / w, Fraction(0)), Fraction(1))
a, c = coarse_parents(p, l)
zc = Fraction(height(a) + height(c), 2)
return (1 - alpha) * height(p) + alpha * zc # @line L7
def mesh(v, n, levels, height, w):
"""Triangles as ((level, point), ...) triples, counterclockwise, and the zero-area
triangles that close the T-junctions on the outer border of each finer level."""
wins = [window(origin(v, n, l), n, l) for l in range(levels)]
for l in range(1, levels):
f, c = wins[l - 1], wins[l]
assert c[0] < f[0] and c[1] < f[1] and f[2] < c[2] and f[3] < c[3]
tris, degenerate = [], []
for l in range(levels):
s = 2 ** l
x0, y0, x1, y1 = wins[l]
for x in range(x0, x1, s):
for y in range(y0, y1, s):
if l > 0:
f = wins[l - 1]
if f[0] <= x and x + s <= f[2] and f[1] <= y and y + s <= f[3]:
continue
a, b, c, d = (x, y), (x + s, y), (x + s, y + s), (x, y + s)
tris.append(((l, a), (l, b), (l, c))) # @line L5
tris.append(((l, a), (l, c), (l, d)))
if l > 0:
f0, g0, f1, g1 = wins[l - 1]
corners = [(f0, g0), (f1, g0), (f1, g1), (f0, g1)]
for k in range(4):
p, q = corners[k], corners[(k + 1) % 4]
steps = max(abs(q[0] - p[0]), abs(q[1] - p[1])) // s
dx, dy = (q[0] - p[0]) // steps, (q[1] - p[1]) // steps
for i in range(steps):
a = (p[0] + i * dx, p[1] + i * dy)
b = (a[0] + dx, a[1] + dy)
o = ((a[0] + b[0]) // 2, (a[1] + b[1]) // 2)
degenerate.append(((l, a), (l, b), (l - 1, o))) # @line L6
heights = {}
for l in range(levels):
for p in points(origin(v, n, l), n, l):
heights[(l, p)] = morph_height(p, l, wins[l], height, w, l == levels - 1)
return tris, degenerate, heights, wins
test_geometry_clipmaps.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geometry-clipmaps/. The authors are listed in prov/03429S.jsonl.
import random
from fractions import Fraction
from geometry_clipmaps import Level, mesh, origin, points
N, LEVELS = 15, 4
W = Fraction(N, 10)
def make_height(rng):
a, b, c = rng.randrange(1, 97), rng.randrange(1, 97), rng.randrange(1, 97)
return lambda p: (a * p[0] + b * p[1] + c * p[0] * p[1]) % 97
def viewers(rng, k):
return [(Fraction(rng.randint(-4000, 4000), 16), Fraction(rng.randint(-4000, 4000), 16)) for _ in range(k)]
def test_every_edge_is_shared_by_two_triangles():
rng = random.Random(1)
for v in viewers(rng, 10):
tris, degenerate, _, wins = mesh(v, N, LEVELS, make_height(rng), W)
x0, y0, x1, y1 = wins[-1]
directed = {}
for t in tris + degenerate:
for k in range(3):
e = (t[k][1], t[(k + 1) % 3][1])
directed[e] = directed.get(e, 0) + 1
assert max(directed.values()) == 1
for (p, q) in directed:
if (q, p) not in directed:
assert (p[0] == q[0] and p[0] in (x0, x1)) or (p[1] == q[1] and p[1] in (y0, y1))
def test_triangles_cover_the_coarsest_window_once():
rng = random.Random(2)
for v in viewers(rng, 10):
tris, _, _, wins = mesh(v, N, LEVELS, make_height(rng), W)
area2 = 0
for (_, a), (_, b), (_, c) in tris:
d = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
assert d > 0
area2 += d
x0, y0, x1, y1 = wins[-1]
assert area2 == 2 * (x1 - x0) * (y1 - y0)
def test_no_gaps_when_the_border_is_fully_morphed():
rng = random.Random(3)
for v in viewers(rng, 10):
tris, degenerate, z, _ = mesh(v, N, LEVELS, make_height(rng), W)
for (la, a), (lb, b), (lo, o) in degenerate:
assert z[(lo, o)] == (z[(la, a)] + z[(lb, b)]) / 2
seen = {}
for t in tris + degenerate:
for key in t:
p = key[1]
if p in seen:
assert seen[p] == z[key]
else:
seen[p] = z[key]
def test_toroidal_update_equals_a_fresh_fill():
rng = random.Random(4)
height = make_height(rng)
v = (Fraction(0), Fraction(0))
levels = [Level(N, l, height, origin(v, N, l)) for l in range(LEVELS)]
for _ in range(40):
v = (v[0] + Fraction(rng.randint(-40, 40), 8), v[1] + Fraction(rng.randint(-40, 40), 8))
for lev in levels:
o = origin(v, N, lev.l)
new = set(points(o, N, lev.l)) - set(points(lev.o, N, lev.l))
assert lev.move(o) == len(new)
fresh = Level(N, lev.l, height, o)
for p in points(o, N, lev.l):
assert lev.get(p) == height(p) == fresh.get(p)
def test_the_smallest_window_step_writes_two_columns():
height = make_height(random.Random(5))
lev = Level(N, 1, height, origin((0, 0), N, 1))
o = (lev.o[0] + 4, lev.o[1])
assert lev.move(o) == 2 * N
History
Tanner, Migdal and Jones introduced the clipmap for textures at SIGGRAPH 98: a mipmap whose fine levels are clipped to a window around a point of interest and updated with wraparound addressing. Losasso and Hoppe applied the same idea to terrain geometry at SIGGRAPH 2004, with nested grids around the viewer, transition regions between the levels, and a compressed terrain pyramid. A year later Asirvatham and Hoppe described a version for the GPU in GPU Gems 2, which draws the rings from a few shared blocks and keeps the levels in textures. The method became a common way to draw large terrains in real time.
References
- Frank Losasso and Hugues Hoppe, Geometry clipmaps, terrain rendering using nested regular grids, ACM Transactions on Graphics 23(3), SIGGRAPH 2004, 769 to 776, the nested grids centered on the viewer, the incremental update of the levels as the viewer moves, the transition regions and the zero-area triangles at the level borders (general locator)
- Arul Asirvatham and Hugues Hoppe, Terrain rendering using GPU-based geometry clipmaps, in Matt Pharr (editor), GPU Gems 2, Addison-Wesley, 2005, Chapter 2, the levels of n = 255 vertices with the block size m = 64, the 12 blocks of m x m, the 4 fix-ups of m x 3 and the L-shaped trim, the degenerate triangles to avoid T-junctions, the morph with w = n/10, and the toroidal update (general locator)
- Christopher C. Tanner, Christopher J. Migdal and Michael T. Jones, The clipmap, a virtual mipmap, SIGGRAPH 98, 151 to 158, the clipped levels of a mipmap centered on a point of interest, and their toroidal update (general locator)
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 03429S Edit this page History Report an error Markdown