Algorithm Search⌘K

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
Properties
not concurrentnot externalnot persistent
Origin
Frank Losasso, Hugues Hoppe, 2004

A geometry clipmap keeps a terrain as a stack of LL regular grids of the same size n×nn \times n, 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 hh is a value that depends on the viewer position vv in the plane, with these operations.

  • build(v): make the LL levels for the viewer vv, with the heights of hh at their vertices.
  • move(v): change the viewer to vv, 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 vv to coarse far from it, with no cracks.
  • get(l, p): the stored height of the vertex pp of level ll.

After build or move, get(l,p)=h(p)(l, p) = h(p) for each vertex pp of the window of level ll.

Representation

Domain points are integer pairs in units of the finest grid. Level ll has the spacing sl=2ls_l = 2^l and n×nn \times n vertices with nn odd, so its window is a square of side (n−1)sl(n - 1) s_l. Its lower corner, the origin olo_l, is a multiple of sl+1s_{l+1}, so that the vertices of level l+1l + 1 in the window are every other vertex of level ll. Each level stores its heights in an n×nn \times n array TlT_l with toroidal addressing: the vertex pp goes to the slot (⌊px/sl⌋ mod n,⌊py/sl⌋ mod n)(\lfloor p_x / s_l \rfloor \bmod n, \lfloor p_y / s_l \rfloor \bmod n), 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

  1. ORIGIN(v, l)
  2. 1o_l ← the multiple of s_(l+1) nearest to v - (n - 1) s_l / 2, in each coordinate
  3. MOVE(l, o) ▷ the new origin o from line L1
  4. 2for each vertex p of the new window of level l that is not in the old window do
  5. 3T_l[(p_x / s_l) mod n, (p_y / s_l) mod n] ← h(p)
  6. 4o_l ← o
  7. MESH(v)
  8. 5for each level l and each cell of its window that is not inside the window of level l - 1 do emit its two triangles
  9. 6for 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
  10. 7each 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, aa and cc are the ends of the edge of level l+1l + 1 through pp (a=c=pa = c = p when pp is a vertex of level l+1l + 1), and bpb_p is the distance of pp from the border of its window in cells of level ll. So α=1\alpha = 1 on the border and 0 at ww cells or more inside it, and the heights of the level blend into the coarser level over a transition region of width ww. This is the geomorph of the method. The coarsest level keeps hh.

Line L5 gives the ring of each level. In the GPU version of Asirvatham and Hoppe, with n=255n = 255 and m=(n+1)/4=64m = (n + 1)/4 = 64, the ring is made of 12 blocks of m×mm \times m vertices, 4 fix-ups of m×3m \times 3 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 sl+1s_{l+1}, 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 n=15n = 15, L=4L = 4 levels, w=1.5w = 1.5 and the viewer at (0,0)(0, 0). Line L1 gives these windows.

level spacing window (x0,y0)(x_0, y_0) to (x1,y1)(x_1, y_1) side ring width in cells, low and high side
0 1 (−6,−6)(-6, -6) to (8,8)(8, 8) 14 all cells
1 2 (−12,−12)(-12, -12) to (16,16)(16, 16) 28 3 and 4
2 4 (−24,−24)(-24, -24) to (32,32)(32, 32) 56 3 and 4
3 8 (−48,−48)(-48, -48) to (64,64)(64, 64) 112 3 and 4

Each ring is at least (n−1)/4−3/2=2(n - 1)/4 - 3/2 = 2 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 14×14=19614 \times 14 = 196 cells, and each ring draws 196−7×7=147196 - 7 \times 7 = 147 cells, so the mesh has 2(196+3⋅147)=12742 (196 + 3 \cdot 147) = 1274 triangles. Each finer window has 28 coarse edges on its border, so line L6 adds 3⋅28=843 \cdot 28 = 84 zero-area triangles. For the n=255n = 255 of the GPU version the bound is 62 cells.

A move. At level 1 the vertex columns have px/s1p_x / s_1 from −6-6 to 8, in the slots 9 to 14 and 0 to 8. A move of the viewer that moves the origin by s2=4s_2 = 4 in xx gives the columns −4-4 to 10. The two new columns 9 and 10 go into the slots 9 and 10, which held the dropped columns −6-6 and −5-5. So the move writes 2n=302n = 30 heights and copies nothing.

The morph. With w=1.5w = 1.5, a vertex on the border of its window has α=1\alpha = 1 and takes the mean of the two coarse vertices around it, one cell inside has α=1−1/1.5=1/3\alpha = 1 - 1/1.5 = 1/3, and two cells inside has α=0\alpha = 0.

Correctness

The proof file gives the arguments, and the tests check them for 10 random viewers and 40 random moves.

  • Nesting. If (n−1)/4>3/2(n - 1)/4 > 3/2, each window lies strictly inside the next coarser one, its corners are vertices of the coarser level, and the ring is at least (n−1)/4−3/2(n - 1)/4 - 3/2 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 0<w≤(n−1)/4−3/20 < w \le (n - 1)/4 - 3/2, 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 w=n/10w = n/10 of Asirvatham and Hoppe meets the condition for n≥35/3n \ge 35/3; the value n/10n/10 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, n2−(n−∣dx∣)(n−∣dy∣)n^2 - (n - |d_x|)(n - |d_y|) of them for a move by (dx,dy)(d_x, d_y) 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 ll has n×nn \times n vertices with the spacing sl=2ls_l = 2^l, so its window has the side (n−1)sl(n - 1) s_l. For the viewer vv, line L1 sets the origin olo_l (the lower corner of the window) to the multiple of sl+1s_{l+1} nearest to v−(n−1)sl/2v - (n - 1) s_l / 2, per coordinate. The levels are 0,…,L−10, \ldots, L - 1, and hh is the height of a domain point. The arithmetic is exact.

The windows nest

Lemma 1. If (n−1)/4>3/2(n - 1)/4 > 3/2, then for each l≥1l \ge 1 the window of level l−1l - 1 lies strictly inside the window of level ll, its corners are vertices of level ll, and on each side the ring between them is at least (n−1)/4−3/2(n - 1)/4 - 3/2 cells of level ll wide.

Proof. Per coordinate, ∣ol−(v−(n−1)sl/2)∣≤sl+1/2=sl|o_l - (v - (n - 1) s_l / 2)| \le s_{l+1}/2 = s_l and ∣ol−1−(v−(n−1)sl−1/2)∣≤sl−1=sl/2|o_{l-1} - (v - (n - 1) s_{l-1} / 2)| \le s_{l-1} = s_l / 2. So

ol−1−ol≥(n−1)(sl−sl−1)2−sl−sl2=sl(n−14−32).o_{l-1} - o_l \ge \frac{(n - 1)(s_l - s_{l-1})}{2} - s_l - \frac{s_l}{2} = s_l \left(\frac{n - 1}{4} - \frac{3}{2}\right).

The upper sides differ by (ol+(n−1)sl)−(ol−1+(n−1)sl−1)=(n−1)sl/2−(ol−1−ol)(o_l + (n - 1) s_l) - (o_{l-1} + (n - 1) s_{l-1}) = (n - 1) s_l / 2 - (o_{l-1} - o_l), and the same two bounds give ol−1−ol≤sl((n−1)/4+3/2)o_{l-1} - o_l \le s_l ((n - 1)/4 + 3/2), so this gap has the same lower bound. The origin ol−1o_{l-1} is a multiple of sls_l, and the side of the fine window is (n−1)sl−1(n - 1) s_{l-1}, an even multiple of sl−1s_{l-1} because nn is odd, so all four corners of the fine window are vertices of level ll. □\square

For n=15n = 15 the bound is 2 cells, and for the n=255n = 255 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 ll, each cell of level ll 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 L−1L - 1: the triangles have disjoint interiors and their union is the window.

Proof. By induction on ll. Level 0 has all its cells, so its triangles tile its window. The ring of level ll is the set of cells of the window of level ll that are not in the window of level l−1l - 1, so by the remark after Lemma 1 the ring and the window of level l−1l - 1 tile the window of level ll. □\square

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 p→qp \to q and the other as q→pq \to p.

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 L−1L - 1.

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 l−1<L−1l - 1 < L - 1. Take a cell edge of level ll on this border, from aa to bb in the counterclockwise order around the fine window, and let oo be its midpoint, which is a vertex of level l−1l - 1. The ring of level ll lies outside the fine window, so its counterclockwise triangle traverses this edge as b→ab \to a. The fine triangles lie inside, so they traverse the two half edges as a→oa \to o and o→bo \to b. Line L6 adds the triangle (a,b,o)(a, b, o) with the directed edges a→ba \to b, b→ob \to o and o→ao \to a. These are paired with b→ab \to a, o→bo \to b and a→oa \to o, in this order. □\square

So, as a set of triangles over the domain, the mesh is closed except on its outer border. A T-junction, where the vertex oo of the fine level lies inside the coarse edge aba b, 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 w≤(n−1)/4−3/2w \le (n - 1)/4 - 3/2, with w>0w > 0. 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 pp of level l<L−1l < L - 1 the height (1−α)h(p)+α(h(a)+h(c))/2(1 - \alpha) h(p) + \alpha (h(a) + h(c))/2, where aa and cc are the ends of the edge of level l+1l + 1 through pp (coarse_parents), and a=c=pa = c = p when pp is a vertex of level l+1l + 1. The factor α\alpha is 1 on the border of the window of level ll and 0 at ww or more cells of level ll from it. The coarsest level keeps hh.

(a) A vertex pp of level ll that is also a vertex of level l+1l + 1 has a=c=pa = c = p, so its height at level ll is h(p)h(p) for every α\alpha. At level l+1l + 1, a domain point that is shared with level ll and is drawn by a ring triangle of level l+1l + 1 lies on the border of the window of level ll. By Lemma 1 it is at least (n−1)/4−3/2≥w(n - 1)/4 - 3/2 \ge w cells of level l+1l + 1 from the border of its own window, so α=0\alpha = 0 there and its height is h(p)h(p) as well. (Vertices of level l+1l + 1 that lie strictly inside the window of level ll are not used by any triangle.)

(b) A triangle of line L6 has the corners aa and bb of level ll, with the height hh by (a), and the midpoint oo of level l−1l - 1 on the border of the window of level l−1l - 1. There α=1\alpha = 1, and the edge of level ll through oo is aba b itself, so oo has the height (h(a)+h(b))/2(h(a) + h(b))/2. The point (o,(h(a)+h(b))/2)(o, (h(a) + h(b))/2) is the midpoint of the segment between (a,h(a))(a, h(a)) and (b,h(b))(b, h(b)). □\square

The condition of the theorem holds for the transition width w=n/10w = n/10 of Asirvatham and Hoppe when n≥15n \ge 15: n/10≤(n−1)/4−3/2n/10 \le (n - 1)/4 - 3/2 is n≥35/3n \ge 35/3. The width n/10n/10 itself is a tuning. Over the transition region the height of each vertex is affine in α\alpha, and α\alpha 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 (⌊px/sl⌋ mod n,⌊py/sl⌋ mod n)(\lfloor p_x / s_l \rfloor \bmod n, \lfloor p_y / s_l \rfloor \bmod n) is one to one on the vertices of a window of level ll. 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 px/slp_x / s_l in nn consecutive integers, and these have nn distinct residues mod nn; the same holds for pyp_y. So the index is one to one on a window. The index depends only on pp, so a vertex in both windows keeps its slot and its stored value h(p)h(p). Line L3 writes h(p)h(p) into the slot of each new vertex, and line L4 sets the origin. So each vertex pp of the new window has h(p)h(p) in its slot, as in a fresh fill. Lines L2 and L3 write only when pp is not in the old window. □\square

So a move of the origin by sl+1=2sls_{l+1} = 2 s_l along one axis, the smallest move that line L1 makes, writes 2n2n samples, and a move by (dx,dy)(d_x, d_y) cells writes n2−(n−∣dx∣)(n−∣dy∣)n^2 - (n - |d_x|)(n - |d_y|) samples when ∣dx∣,∣dy∣≤n|d_x|, |d_y| \le n.

Complexity

operation time note
build Θ(Ln2)\Theta(L n^2) one height per vertex of each level
move O(nd)O(n d) a level that moves by (dx,dy)(d_x, d_y) cells makes n2−(n−dx)(n−dy)≤n(dx+dy)n^2 - (n - d_x)(n - d_y) \le n(d_x + d_y) writes
mesh Θ(Ln2)\Theta(L n^2) each ring has O(n2)O(n^2) cells; on the GPU it is a fixed set of draws
get O(1)O(1) one slot

The space is Θ(Ln2)\Theta(L n^2): LL arrays of n2n^2 heights, against the Θ(4Ln2)\Theta(4^L n^2) of a full grid at the finest spacing over the coarsest window. The code finds the new vertices with a set difference, which costs Θ(n2)\Theta(n^2) 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 α\alpha 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 α\alpha 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 sls_l in place of sl+1s_{l+1}, the corners of the window of level ll are not vertices of level l+1l + 1, 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 ((px−ox)/sl,(py−oy)/sl)((p_x - o_x) / s_l, (p_y - o_y) / s_l), the slot of a vertex changes when the origin moves, and each move must copy all n2n^2 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 n2n^2 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 ww in line L7 is larger than the ring, a vertex of the coarser level on the inner border of its ring has α>0\alpha > 0, 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 aa and cc, 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.

geometry_clipmaps.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build
  • a full proof of time.mesh
  • a full proof of time.move
  • 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/03429S/text.yaml