Algorithm Search⌘K

Algorithmadvanced

ROAM

Also called real-time optimally adapting meshes.

Keep a terrain triangulation as a binary triangle tree and split and merge triangles with two priority queues to meet an error bound each frame.

Time
O((L + s) log(L + s)) worst
Space
Θ(M^2) extra
Where
L = the number of leaves at the start and at the end of the frame; M = the grid size in cells along each side; s = the number of splits and merges in the frame
Properties
not adaptivenot comparison baseddeterministicin placeonlineiterativenot stable
Origin
Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich, Mark B. Mineev Weinstein, 1997

ROAM keeps a terrain as the leaves of a binary tree of right triangles, and each frame it splits the leaves with the largest error and merges the pairs with the smallest error, with one priority queue for each. A split that would leave a crack first splits the coarser neighbor across the base, so the mesh has no T-junctions at any time. View-dependent refinement does the same kind of local work on any progressive mesh with stored records, and geometry clipmaps use fixed nested grids in place of a tree. ROAM needs only the height grid and a bound per triangle, which it computes once.

In plain words

Cut a square of terrain along a diagonal into two triangles. Any triangle of this kind can be cut again, from its right angle to the middle of its long side, into two smaller triangles of the same shape. Repeating this gives finer and finer meshes.

ROAM keeps a mesh made of such triangles. For each one it knows, from a table made at the start, how far the flat triangle can be from the true ground below it. Each frame it cuts the triangles whose error looks large from where the viewer is, and joins pairs of triangles whose error looks small. If a cut would make a gap with a larger neighbor, it cuts that neighbor first. The mesh of one frame is the start for the next, so a small move of the viewer gives few changes.

The problem

The input is a height grid hh on the points (x,y)(x, y) with 0≤x,y≤M0 \le x, y \le M and M=2kM = 2^k, the position of the eye, a priority p(T)p(T) for each triangle and an error bound ε\varepsilon. A bintree triangle T=(a,v0,v1)T = (a, v_0, v_1) has its right angle at the apex aa and the base v0v1v_0 v_1. Its children are (c,a,v0)(c, a, v_0) and (c,v1,a)(c, v_1, a) with cc the midpoint of the base. The two roots split the square along a diagonal. The partner of TT is the triangle of the same level across its base; together they form a diamond. A mesh is the set of leaves of a cut of the tree. It is conforming when no vertex of a leaf lies inside an edge of another leaf. The output, each frame, is a conforming mesh in which every leaf has p(T)≤ε2p(T) \le \varepsilon^2, with as few triangles as possible. The paper writes the height as zz; this page uses hh.

The algorithm

  1. FORCE-SPLIT(mesh, t) ▷ t is a leaf with children
  2. 1stack ← [t]
  3. 2while the stack is not empty do u ← the top; if u is not a leaf then pop u and go on
  4. 3b ← the leaf with the base of u as an edge, or nil on the border
  5. 4if b ≠ nil and the base of b is not the base of u then push b and go on
  6. 5split u, and split b if b ≠ nil; pop u
  7. UPDATE(mesh, p, ε) ▷ one frame
  8. 6Qs ← a max-heap of the leaves by p
  9. 7while p(top of Qs) > ε^2 do pop T; if T is a leaf then FORCE-SPLIT(mesh, T) and push the new leaves
  10. 8Qm ← a min-heap of the mergeable diamonds by the larger p of the two; while p(top of Qm) ≤ ε^2 do merge it and push the parent diamonds that become mergeable
  11. 9return mesh
  12. WEDGIES(tree) ▷ once, before the first frame
  13. 10for each triangle T of the full tree, finest first do
  14. 11e_T ← 0 for a leaf, else max(e_T0, e_T1) + |h(c) - (h(v0) + h(v1))/2|
  15. 12p(T) = e_T^2 / max(dist(eye, T)^2, d0^2) ▷ the priority

Line L4 is the forced split of Section 4.2 of the paper. In a conforming mesh, the leaf across the base of uu is either the partner of uu, or a triangle one level coarser whose leg is the base of uu. In the second case bb must be split first; the split of bb makes the partner of uu, and the next pass splits the diamond.

Lines L10 and L11 compute the wedgie thickness of Section 6.1, Equation 1: the true surface lies within eTe_T of the plane of TT above or below each point of TT. A mergeable diamond is a split triangle and its partner whose four children are all leaves.

Line L12 is the priority of the code: the squared wedgie over the squared distance in the domain from the eye to the triangle, with a floor d0d_0 against a division by zero. It is a heuristic in place of the screen distortion of Section 6.2, which projects the wedgie with the camera. It is squared so that it stays rational, and it is monotone: a child never has a larger priority than its parent. The value of d0d_0 is a tuning.

Example

A forced split. Take M=4M = 4, all heights 0 except h(3,3)=4h(3, 3) = 4. The five triangles with a nonzero wedgie have eT=4e_T = 4. Asking for the leaf that holds the point (3.5,3.25)(3.5, 3.25) at each step gives these calls of FORCE-SPLIT.

step the leaf that is asked for triangles split leaves after
1 the root ((4,4),(0,4),(4,0))((4, 4), (0, 4), (4, 0)) 2, a diamond of the two roots 4
2 ((2,2),(4,0),(4,4))((2, 2), (4, 0), (4, 4)) 1, its base is on the border 5
3 ((4,2),(4,4),(2,2))((4, 2), (4, 4), (2, 2)) 3 8
4 ((3,3),(4,2),(4,4))((3, 3), (4, 2), (4, 4)) 1, its base is on the border 9

At step 3 the base of the leaf goes from (4,4)(4, 4) to (2,2)(2, 2), and the leaf across it is the coarser ((2,2),(4,4),(0,4))((2, 2), (4, 4), (0, 4)), for which this base is a leg. Line L4 pushes it, line L5 splits it, which makes the partner ((2,4),(2,2),(4,4))((2, 4), (2, 2), (4, 4)), and the next pass splits the diamond. So 3 triangles are split, and the point (3,3)(3, 3) enters the mesh without a T-junction. Step 4 is not needed for accuracy: its triangle has eT=0e_T = 0. UPDATE with ε=0\varepsilon = 0 from any eye gives the 8 leaves after step 3, the smallest conforming mesh that shows the surface exactly.

Error bounds. On an 8×88 \times 8 grid with random heights from 0 to 10 (the seed 1), the full tree has 254 triangles, and 126 of them have children. The two roots have the wedgies 55/255/2 and 33. With the eye over the point (1,1)(1, 1) and d0=1d_0 = 1, UPDATE from the two roots gives these meshes.

ε\varepsilon 1/4 1/2 1 2
leaves 116 110 88 56

With ε=1/2\varepsilon = 1/2, moving the eye from (1,1)(1, 1) to (2,1)(2, 1) and running UPDATE on the old mesh splits 2 triangles and merges none, so the mesh goes from 110 to 112 leaves. The result equals the mesh that a fresh run from the two roots gives for the new eye.

Correctness

The proof file gives the full arguments, and the tests check them on random grids.

  • The wedgies. For every triangle TT and point qq in it, the surface of the full grid differs from the plane of TT by at most eTe_T, and eT0,eT1≤eTe_{T_0}, e_{T_1} \le e_T (a proved property, by induction from the finest level).
  • Forced splits. From a conforming mesh, FORCE-SPLIT ends, splits tt, keeps the mesh conforming after each split, and splits at most 2(ℓ+1)2(\ell + 1) triangles for a leaf of level ℓ\ell (a proved property).
  • One frame. With the monotone priority of line L12, UPDATE from any conforming mesh ends with the split set equal to the smallest set that holds every triangle with p>ε2p > \varepsilon^2 and is closed under parents and partners. So the result does not depend on the mesh of the last frame (a proved property).
  • Optimality. That mesh has the fewest leaves among all conforming meshes whose leaves have p≤ε2p \le \varepsilon^2, and it is the only one with that number. This is the optimality claim of Section 5.1 in a precise form (a proved property). The test checks it by enumerating all 5489 conforming meshes of the 4×44 \times 4 grid.

The claim needs a monotone priority. A priority that can grow from a parent to a child can hide a child with a large error below a parent with a small one, and the split phase then stops before the child is reached. Any other priority, such as the screen distortion of the paper, must be checked for this property before the optimality claim is used.

Proof: The ROAM wedgies bound the surface, forced splits keep the mesh conforming, and with monotone priorities a frame ends at the unique smallest conforming triangulation whose leaves all meet the error boundfull

We use the notation of the page. The domain is the square [0,M]2[0, M]^2 with M=2kM = 2^k, and hh gives a height to each grid point. A bintree triangle T=(a,v0,v1)T = (a, v_0, v_1) has the apex aa at its right angle and the base v0v1v_0 v_1. Its children are T0=(c,a,v0)T_0 = (c, a, v_0) and T1=(c,v1,a)T_1 = (c, v_1, a), where cc is the midpoint of the base. The two roots have level 0, and a child has the level of its parent plus 1. A triangle of level ℓ\ell has legs of length sℓ=M/2ℓ/2s_\ell = M / 2^{\ell/2} and a base of length 2 sℓ\sqrt2\, s_\ell. The partner of TT is the triangle of the same level that shares its base, if the base is not on the border of the square. Heights and priorities are exact rationals.

A mesh is the set of leaves of a cut of the bintree: a set SS of split triangles that holds the parent of each of its members, and whose leaves are the triangles not in SS whose parent is in SS (or the roots, when they are not in SS). The leaves tile the square. Two bintree triangles are either nested or have disjoint interiors. A mesh is conforming when no vertex of a leaf lies inside an edge of another leaf; then each edge of a leaf is an edge of exactly one other leaf, or lies on the border.

We use one fact of the construction. For each level ℓ\ell, the triangles of level ℓ\ell form a conforming triangulation of the square, and its vertex set VℓV_\ell grows with ℓ\ell. (Even levels are square grids of spacing M/2ℓ/2M / 2^{\ell/2} cut by diagonals; odd levels are the grids of diamonds between them.) The midpoint of a base of a level ℓ\ell triangle is in Vℓ+1V_{\ell + 1} but not in VℓV_\ell.

The wedgies

Let HH be the surface over the finest level: on each leaf of the full bintree, the plane through its three corners. Let PTP_T be the plane over TT through its three corners. Lines L10 and L11 compute eT=0e_T = 0 for a leaf of the full bintree and eT=max⁡(eT0,eT1)+∣h(c)−(h(v0)+h(v1))/2∣e_T = \max(e_{T_0}, e_{T_1}) + |h(c) - (h(v_0) + h(v_1))/2| otherwise. This is Equation (1) of Duchaineau et al., with the height written hh in place of their zz.

Lemma 1. For every bintree triangle TT and every domain point p∈Tp \in T, ∣H(p)−PT(p)∣≤eT|H(p) - P_T(p)| \le e_T. Also eT0,eT1≤eTe_{T_0}, e_{T_1} \le e_T.

Proof. The second claim holds because the gap term is nonnegative. The first is by induction from the finest level. On a leaf of the full bintree, H=PTH = P_T. For an inner TT, let p∈Tjp \in T_j. Then ∣H(p)−PT(p)∣≤∣H(p)−PTj(p)∣+∣PTj(p)−PT(p)∣|H(p) - P_T(p)| \le |H(p) - P_{T_j}(p)| + |P_{T_j}(p) - P_T(p)|. The first term is at most eTje_{T_j} by induction. The difference PTj−PTP_{T_j} - P_T is affine on TjT_j, so its largest absolute value on TjT_j is at a corner. It is 0 at the corners aa and vjv_j, which TjT_j shares with TT. At cc it is h(c)−PT(c)=h(c)−(h(v0)+h(v1))/2h(c) - P_T(c) = h(c) - (h(v_0) + h(v_1))/2, because cc is the midpoint of the base and PTP_T is affine. So the sum is at most eTj+gap≤eTe_{T_j} + \mathrm{gap} \le e_T. □\square

Lemma 2. The priority of line L12, p(T)=eT2/max⁡(dist(eye,T)2,d02)p(T) = e_T^2 / \max(\mathrm{dist}(\mathrm{eye}, T)^2, d_0^2), is monotone: p(Tj)≤p(T)p(T_j) \le p(T).

Proof. eTj≤eTe_{T_j} \le e_T by Lemma 1, and Tj⊆TT_j \subseteq T, so the distance from the eye to TjT_j is at least the distance to TT. □\square

The priority is the square of the bound of the page, so that it stays rational; the order is the same. It is a heuristic for the screen error: it bounds the error of the height as seen from the eye up to the factor of the projection, but not the error of the line of sight as in Section 6.2 of the paper.

Forced splits

Lemma 3. In a conforming mesh, let tt be a leaf and bb the leaf that has the base of tt as an edge. Either bb is the partner of tt (the same level, the same base), or the base of tt is a leg of bb and bb has the level of tt minus 1.

Proof. The shared edge has the length 2 sℓ\sqrt2\, s_\ell for the level ℓ\ell of tt. If it is the base of bb, then bb has level ℓ\ell and shares its base with tt, so bb is the partner. If it is a leg of bb, then sℓ(b)=2 sℓ=sℓ−1s_{\ell(b)} = \sqrt2\, s_\ell = s_{\ell - 1}. □\square

Lemma 4. If the mesh is conforming and tt is a leaf with children, FORCE-SPLIT(t)(t) (lines L1 to L5) ends, tt is split at the end, the mesh is conforming after each split, and at most 2(ℓ(t)+1)2(\ell(t) + 1) triangles are split.

Proof. A split of a leaf uu with no base neighbor (base on the border) keeps the mesh conforming: the legs of uu become the bases of its children with the same neighbors, the new edge aca c is shared by the two children, and the two halves of the base are on the border. A split of a diamond, a leaf uu and its partner, also keeps it: the two halves of the common base are each shared by one child of uu and one child of the partner.

The stack holds triangles whose levels decrease by 1 from each entry to the next one above it. This holds at the start. Line L4 pushes bb only when the base of the top uu is a leg of bb, and then bb has the level of uu minus 1 by Lemma 3. Line L5 splits the top uu and its partner, or uu alone on the border, and these are the two cases that keep the mesh conforming. A split removes only the top entry and its partner, which have the level of the top. All entries below are finer, so they stay leaves. After the split of bb, its child whose base is the old leg is a leaf, and it is the new base neighbor of the entry below, with the same base. So the next pass splits that entry with it as a diamond.

The stack has at most ℓ(t)+1\ell(t) + 1 entries. Each pass pops, pushes, or splits and pops. Each push puts a strictly coarser triangle on top, so there are at most ℓ(t)\ell(t) pushes in a row, and each split pops one entry. So the loop ends. The bottom entry tt is popped only after it is split, because it stays a leaf until line L5 splits it. Each level gives at most one diamond, so at most 2(ℓ(t)+1)2(\ell(t) + 1) splits happen. □\square

A conforming mesh is closed under partners

Lemma 5. If a mesh with split set SS is conforming, then SS holds the partner of each of its members.

Proof. Let T∈ST \in S with partner T′T', and suppose T′∉ST' \notin S. Then T′T' lies in a leaf LL: L=T′L = T' or a proper ancestor of T′T'. The midpoint cc of the common base is a vertex of a child of TT, so of a leaf inside TT. The leaf LL is not an ancestor of TT (it is not split) and not inside TT (it holds T′T'), so it does not overlap the interior of TT, and cc, which lies on the boundary of TT, is not in the interior of LL. So cc is on the boundary of LL. The level of LL is at most ℓ(T)\ell(T), so the vertices of LL are in Vℓ(T)V_{\ell(T)}, and cc is not. So cc is inside an edge of LL, and the mesh is not conforming. □\square

One frame

Let ε≥0\varepsilon \ge 0, let P={T:p(T)>ε2}P = \{T : p(T) > \varepsilon^2\}, and let CC be the smallest set that holds PP and the parent and the partner of each of its members. This is the set that target builds. A triangle in PP has eT>0e_T > 0, so it has children.

Theorem 6. Start from any conforming mesh. After UPDATE (lines L6 to L9), the split set is exactly CC. So the mesh is the set of leaves of CC, whatever mesh the frame started from.

Proof. The split phase (lines L6 and L7). The heap holds an entry for each leaf: all leaves at the start, and each leaf that a split adds. The phase pops entries in the order of priority, skips those that are no longer leaves, and force-splits a leaf with p>ε2p > \varepsilon^2. It stops at a leaf with p≤ε2p \le \varepsilon^2, and all remaining entries have a priority no larger. Each force split adds new leaves, so the phase ends after a finite number of splits (the bintree is finite). At its end every leaf has p≤ε2p \le \varepsilon^2, and the mesh is conforming by Lemma 4. Now let T∈PT \in P. If TT were not split, then a leaf LL would be TT or an ancestor of TT, and p(L)≥p(T)>ε2p(L) \ge p(T) > \varepsilon^2 by Lemma 2. So S⊇PS \supseteq P. By Lemma 5 and the parent rule, S⊇CS \supseteq C.

The merge phase (line L8). A diamond TT (with its partner T′T', or alone on the border) is mergeable when TT is split and all children of TT and of T′T' are leaves. A merge removes TT and T′T' from SS. The new leaves TT and T′T' have as legs the bases of the old children, with the same neighbors, and the common base is shared by TT and T′T', so the mesh stays conforming. The phase merges only diamonds with max⁡(p(T),p(T′))≤ε2\max(p(T), p(T')) \le \varepsilon^2, so it never removes a member of PP, and S⊇CS \supseteq C stays true. A diamond becomes mergeable only when a merge makes the last of its children a leaf, and then its parent diamond is pushed. So when the phase stops, every mergeable diamond has a priority above ε2\varepsilon^2.

No extra split remains. Suppose S∖CS \setminus C is not empty, and let TT be a member of the greatest level. A child of TT in SS would be in CC by the choice of TT, and then its parent TT would be in CC. So both children of TT are leaves. The partner T′T', if any, is in SS by Lemma 5, and not in CC, because CC holds the partners of its members and the partner of T′T' is TT. So the children of T′T' are leaves too. The diamond of TT is mergeable, and its priority is at most ε2\varepsilon^2, because T,T′∉C⊇PT, T' \notin C \supseteq P. This contradicts the end of the merge phase. So S=CS = C. □\square

Corollary 7. Among the conforming meshes whose leaves all have p≤ε2p \le \varepsilon^2, the mesh of Theorem 6 has the fewest triangles, and it is the only one with that number.

Proof. Such a mesh has a split set that holds PP (the argument of the split phase) and is closed under parents and partners (Lemma 5), so it holds CC. A mesh with the split set SS has 2+∣S∣2 + |S| leaves, because each split adds one leaf. So it has at least 2+∣C∣2 + |C| leaves, with equality only when its split set is CC. □\square

This is the optimality statement of Section 5.1 of the paper in a precise form, and it needs the monotone priority of Lemma 2: with a priority that can grow from a parent to a child, the split phase can keep a leaf with a priority of at most ε2\varepsilon^2 that hides a descendant above ε2\varepsilon^2, and the result is then not accurate. The test checks Theorem 6 against target and Corollary 7 by enumeration of all 5489 conforming meshes of the 4×44 \times 4 grid.

Complexity

Lines L10 and L11 visit each of the 4M2−24M^2 - 2 triangles of the full tree once, so the wedgies take Θ(M2)\Theta(M^2) time and space. For a frame that starts and ends with at most LL leaves and makes ss splits and merges, the code puts O(L+s)O(L + s) entries in the two heaps, each at O(log⁡(L+s))O(\log(L + s)), so a frame costs O((L+s)log⁡(L+s))O((L + s) \log(L + s)) in the worst case. The paper keeps both queues from frame to frame and recomputes only the priorities that change, so the work of a frame is about proportional to the number of changes (Section 5.2). In the code the split heap is built from all leaves each frame, which is simpler and shows the result, not the speed.

Properties

  • Conforming at every step. No split or merge makes a crack or a T-junction (a proved property).
  • Independent of history. With a monotone priority and a fixed ε\varepsilon, the mesh of a frame depends only on the view, not on the mesh before it (a proved property).
  • Smallest. No conforming mesh with fewer triangles meets the bound at every leaf (a proved property).
  • Coherent. A small move of the eye gives few splits and merges; the example moves the eye by one cell and splits 2 triangles (a measurement).
  • Pops. A split changes the surface at once. The change is at most the wedgie of the triangle, so a small ε\varepsilon keeps it small on the screen, but it is still a jump.

Variants and improvements

  • Screen distortion. The paper projects the wedgie with the camera, so the error is in pixels and a wedgie seen along the line of sight counts little (Section 6.2, Equations 2 and 3).
  • Frustum culling. Each triangle keeps a label for each plane of the view frustum: inside, outside or across. The children of a triangle that is inside a plane are inside it too, so only the labels across a plane need a new test (Section 7.1). See frustum culling.
  • A triangle budget. The queues can stop at a target number of triangles in place of an error bound, so that the cost of a frame stays about fixed (a tuning).
  • Morphs. Each split and merge can blend the new vertex from the midpoint of the base to its height over a few frames, as in geomorphing.
  • Patches. Later systems refine patches of many triangles in place of single triangles, so that the GPU gets large batches. Geometry clipmaps take this further with fixed grids.

When to use it

ROAM fits a height field on a regular grid that is seen from near and far at the same time, as in a flight simulator, when the CPU builds the mesh each frame and a fixed error bound or a fixed triangle count is wanted. On current GPUs, the work per triangle and the many small changes make it slower than methods that draw large fixed grids, such as geometry clipmaps. For meshes that are not height fields, use view-dependent refinement.

Pitfalls

  • Splitting one side of a diamond. If line L5 splits uu and not its partner bb, the midpoint of the shared base is a vertex of uu's children inside an edge of bb, and the mesh has a T-junction that can show a crack.
  • No forced split. If line L4 is left out and line L5 splits uu when bb is coarser, the new vertex cc lies inside a leg of bb, and the mesh has a T-junction there.
  • A wedgie that is not nested. If line L11 uses only the gap ∣h(c)−(h(v0)+h(v1))/2∣|h(c) - (h(v_0) + h(v_1))/2| without the children, the value is not a bound: a parent with a gap of 0 hides children with a large error, and the split phase stops too early.
  • The wrong order. Line L10 must visit the finest triangles first; from coarse to fine, line L11 reads wedgies of the children that are not yet computed.
  • No floor in the priority. Line L12 with d0=0d_0 = 0 divides by zero when the eye is above the triangle.
  • A distance to one point. If line L12 uses the distance to the center of TT in place of the nearest point of TT, a child can be nearer to the eye than its parent's center, the priority is not monotone, and the result of a frame is no longer the smallest accurate mesh.
  • Merging a half diamond. If line L8 merges a triangle without its partner, the result has a T-junction at the midpoint of their base.

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.

roam_terrain.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roam-terrain/. The authors are listed in prov/5KAMME.jsonl.

"""ROAM: a triangle bintree over a height grid, kept as a conforming mesh
by forced splits and diamond merges, with split and merge queues.

The domain is the square [0, M] x [0, M] with M = 2^k. A domain point is a
pair (x, y) of integers; the height of a grid vertex is h[(x, y)]. (The world
of this site is y up; here the pair names a point of the ground plane and the
height is a separate value, as in Duchaineau et al., who call it z.)

A triangle is a tuple (a, v0, v1): the apex a is the right-angle vertex and
(v0, v1) is the base (the hypotenuse). All triangles are counterclockwise.
The children of T = (a, v0, v1) with base midpoint c are T0 = (c, a, v0) and
T1 = (c, v1, a). All arithmetic on heights and priorities is exact.
"""

import heapq
from fractions import Fraction


def midpoint(T):
    _, v0, v1 = T
    sx, sy = v0[0] + v1[0], v0[1] + v1[1]
    if sx % 2 or sy % 2:
        return None
    return (sx // 2, sy // 2)


def base(T):
    return frozenset((T[1], T[2]))


def edges_of(T):
    a, v0, v1 = T
    return (frozenset((a, v0)), frozenset((v0, v1)), frozenset((v1, a)))


class Bintree:
    """The full triangle bintree of the grid and the wedgie thickness of every triangle."""

    def __init__(self, k, h):
        m = 2 ** k
        self.m = m
        self.h = h
        self.roots = (((0, 0), (m, 0), (0, m)), ((m, m), (0, m), (m, 0)))
        self.children = {}
        self.parent = {}
        self.all = []
        stack = list(self.roots)
        while stack:
            t = stack.pop()
            self.all.append(t)
            c = midpoint(t)
            if c is None:
                continue
            a, v0, v1 = t
            kids = ((c, a, v0), (c, v1, a))
            self.children[t] = kids
            for u in kids:
                self.parent[u] = t
                stack.append(u)
        self.err = {}
        for t in reversed(self.all):  # @line L10
            if t in self.children:
                t0, t1 = self.children[t]
                _, v0, v1 = t
                c = midpoint(t)
                gap = abs(h[c] - Fraction(h[v0] + h[v1], 2))
                self.err[t] = max(self.err[t0], self.err[t1]) + gap  # @line L11
            else:
                self.err[t] = Fraction(0)

    def partner(self, t):
        """The triangle of the same level that shares the base of t, or None on the border."""
        a, v0, v1 = t
        b = (v0[0] + v1[0] - a[0], v0[1] + v1[1] - a[1])
        if 0 <= b[0] <= self.m and 0 <= b[1] <= self.m:
            return (b, v1, v0)
        return None


def dist2_point_triangle(p, t):
    """Exact squared distance from the point p to the closed triangle t."""
    a, b, c = t

    def cross(o, u, v):
        return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])

    if cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0:
        return Fraction(0)
    best = None
    for u, v in ((a, b), (b, c), (c, a)):
        dx, dy = v[0] - u[0], v[1] - u[1]
        s = Fraction((p[0] - u[0]) * dx + (p[1] - u[1]) * dy, dx * dx + dy * dy)
        s = min(max(s, Fraction(0)), Fraction(1))
        qx, qy = u[0] + s * dx - p[0], u[1] + s * dy - p[1]
        d = qx * qx + qy * qy
        best = d if best is None else min(best, d)
    return best


def make_priority(tree, eye, d0):
    """The squared priority (e_T / max(dist(eye, T), d0))^2 of each triangle."""
    cache = {}

    def prio(t):
        if t not in cache:
            e = tree.err[t]
            cache[t] = e * e / max(dist2_point_triangle(eye, t), Fraction(d0) ** 2)  # @line L12
        return cache[t]

    return prio


class Mesh:
    """A conforming triangulation made of bintree triangles, with an edge map."""

    def __init__(self, tree, active=None):
        self.tree = tree
        self.active = set()
        self.edges = {}
        self.added = []
        for t in (tree.roots if active is None else active):
            self._add(t)

    def _add(self, t):
        self.active.add(t)
        self.added.append(t)
        for e in edges_of(t):
            self.edges.setdefault(e, set()).add(t)

    def _remove(self, t):
        self.active.remove(t)
        for e in edges_of(t):
            s = self.edges[e]
            s.discard(t)
            if not s:
                del self.edges[e]

    def split(self, t):
        self._remove(t)
        for u in self.tree.children[t]:
            self._add(u)

    def base_neighbor(self, t):
        others = self.edges.get(base(t), set()) - {t}
        return next(iter(others)) if others else None

    def force_split(self, t):
        stack = [t]  # @line L1
        while stack:  # @line L2
            t = stack[-1]
            if t not in self.active:
                stack.pop()
                continue
            b = self.base_neighbor(t)  # @line L3
            if b is not None and base(b) != base(t):
                stack.append(b)  # @line L4
                continue
            self.split(t)  # @line L5
            if b is not None:
                self.split(b)
            stack.pop()

    def mergeable(self, t):
        tree = self.tree
        if t not in tree.children or t in self.active:
            return False
        for u in (t, tree.partner(t)):
            if u is not None and not all(k in self.active for k in tree.children[u]):
                return False
        return True

    def merge(self, t):
        for u in (t, self.tree.partner(t)):
            if u is None:
                continue
            for k in self.tree.children[u]:
                self._remove(k)
            self._add(u)


def update(mesh, prio, eps):
    """One frame: split every leaf whose priority is above eps, then merge
    every diamond whose priority is at most eps. Returns the mesh."""
    tree = mesh.tree
    eps2 = Fraction(eps) ** 2
    qs = [(-prio(t), t) for t in mesh.active]  # @line L6
    heapq.heapify(qs)
    while qs:  # @line L7
        p, t = heapq.heappop(qs)
        if t not in mesh.active:
            continue
        if -p <= eps2:
            break
        mesh.added = []
        mesh.force_split(t)
        for u in mesh.added:
            heapq.heappush(qs, (-prio(u), u))

    def diamond(t):
        u = tree.partner(t)
        key = min(t, u) if u is not None else t
        return (max(prio(t), prio(u)) if u is not None else prio(t), key)

    qm = []
    for t in {tree.parent[u] for u in mesh.active if u in tree.parent}:
        if mesh.mergeable(t):
            heapq.heappush(qm, diamond(t))
    while qm:  # @line L8
        mp, t = heapq.heappop(qm)
        if not mesh.mergeable(t):
            continue
        if mp > eps2:
            break
        mesh.merge(t)
        for u in (t, tree.partner(t)):
            if u is not None and u in tree.parent and mesh.mergeable(tree.parent[u]):
                heapq.heappush(qm, diamond(tree.parent[u]))
    return mesh  # @line L9


def target(tree, prio, eps):
    """A second method: the leaves of the closure of {T : priority > eps}
    under the parent and same-level partner relations."""
    eps2 = Fraction(eps) ** 2
    stack = [t for t in tree.children if prio(t) > eps2]
    closed = set()
    while stack:
        t = stack.pop()
        if t in closed:
            continue
        closed.add(t)
        for u in (tree.parent.get(t), tree.partner(t)):
            if u is not None:
                stack.append(u)
    return {t for t in tree.all if t not in closed and (t not in tree.parent or tree.parent[t] in closed)}


def interpolate(t, h, p):
    """The height at domain point p of the plane through the corners of t."""
    a, b, c = t
    det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
    wb = Fraction((p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1]), det)
    wc = Fraction((b[0] - a[0]) * (p[1] - a[1]) - (p[0] - a[0]) * (b[1] - a[1]), det)
    return (1 - wb - wc) * h[a] + wb * h[b] + wc * h[c]


def contains(t, p):
    a, b, c = t

    def cross(o, u, v):
        return (u[0] - o[0]) * (v[1] - o[1]) - (u[1] - o[1]) * (v[0] - o[0])

    return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0


def random_heights(rng, m, amp=10):
    return {(x, y): rng.randint(0, amp) for x in range(m + 1) for y in range(m + 1)}
test_roam_terrain.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/roam-terrain/. The authors are listed in prov/5KAMME.jsonl.

import random
from fractions import Fraction

from roam_terrain import (
    Bintree,
    Mesh,
    base,
    contains,
    edges_of,
    interpolate,
    make_priority,
    random_heights,
    target,
    update,
)


def conforming(mesh):
    m = mesh.tree.m
    verts = {v for t in mesh.active for v in t}
    area2 = 0
    for t in mesh.active:
        a, b, c = t
        area2 += (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])
    if area2 != 2 * m * m:
        return False
    for e, ts in mesh.edges.items():
        p, q = tuple(e)
        border = (p[0] == q[0] and p[0] in (0, m)) or (p[1] == q[1] and p[1] in (0, m))
        if len(ts) != (1 if border else 2):
            return False
        for v in verts:
            if v in (p, q):
                continue
            cr = (q[0] - p[0]) * (v[1] - p[1]) - (q[1] - p[1]) * (v[0] - p[0])
            if cr == 0 and min(p[0], q[0]) <= v[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= v[1] <= max(p[1], q[1]):
                return False
    return True


def setup(rng, k):
    m = 2 ** k
    tree = Bintree(k, random_heights(rng, m))
    eye = (Fraction(rng.randint(0, 4 * m), 4), Fraction(rng.randint(0, 4 * m), 4))
    return tree, eye


def test_wedgie_bounds_the_true_surface():
    rng = random.Random(1)
    tree, _ = setup(rng, 3)
    pts = list(tree.h)
    for t in tree.all:
        worst = max(abs(tree.h[p] - interpolate(t, tree.h, p)) for p in pts if contains(t, p))
        assert worst <= tree.err[t]
        if t in tree.children:
            assert all(tree.err[u] <= tree.err[t] for u in tree.children[t])


def test_partner_is_in_the_tree_and_priorities_are_monotone():
    rng = random.Random(2)
    tree, eye = setup(rng, 4)
    prio = make_priority(tree, eye, 1)
    known = set(tree.all)
    for t in tree.all:
        u = tree.partner(t)
        if u is not None:
            assert u in known and base(u) == base(t) and tree.partner(u) == t
        for c in tree.children.get(t, ()):
            assert prio(c) <= prio(t)


def test_force_split_keeps_the_mesh_conforming():
    rng = random.Random(3)
    tree, _ = setup(rng, 4)
    mesh = Mesh(tree)
    for _ in range(60):
        t = rng.choice(sorted(t for t in mesh.active if t in tree.children))
        mesh.force_split(t)
        assert t not in mesh.active
        assert conforming(mesh)


def test_frame_reaches_the_closure_and_every_leaf_is_accurate():
    rng = random.Random(4)
    for _ in range(6):
        tree, eye = setup(rng, 4)
        eps = Fraction(rng.randint(1, 12), 8)
        prio = make_priority(tree, eye, 1)
        mesh = update(Mesh(tree), prio, eps)
        assert mesh.active == target(tree, prio, eps)
        assert conforming(mesh)
        assert all(prio(t) <= eps * eps for t in mesh.active)


def test_incremental_frames_equal_a_fresh_build():
    rng = random.Random(5)
    tree, eye = setup(rng, 4)
    mesh = Mesh(tree)
    eps = Fraction(1, 2)
    for _ in range(8):
        eye = (min(max(eye[0] + Fraction(rng.randint(-8, 8), 4), 0), 16),
               min(max(eye[1] + Fraction(rng.randint(-8, 8), 4), 0), 16))
        eps = min(max(eps + Fraction(rng.randint(-2, 2), 8), Fraction(1, 8)), Fraction(2))
        prio = make_priority(tree, eye, 1)
        update(mesh, prio, eps)
        fresh = update(Mesh(tree), prio, eps)
        assert mesh.active == fresh.active
        assert conforming(mesh)


def test_result_is_the_smallest_accurate_triangulation_by_enumeration():
    rng = random.Random(6)
    tree, eye = setup(rng, 2)
    start = frozenset(tree.roots)
    seen = {start}
    todo = [start]
    while todo:
        s = todo.pop()
        for t in s:
            if t in tree.children:
                mesh = Mesh(tree, s)
                mesh.force_split(t)
                n = frozenset(mesh.active)
                if n not in seen:
                    seen.add(n)
                    todo.append(n)
    assert len(seen) == 5489
    assert all(conforming(Mesh(tree, s)) for s in sorted(seen, key=sorted)[::25])
    for eps in (Fraction(1, 4), Fraction(1, 2), Fraction(1), Fraction(2)):
        prio = make_priority(tree, eye, 1)
        ok = [s for s in seen if all(prio(t) <= eps * eps for t in s)]
        best = min(len(s) for s in ok)
        winners = [s for s in ok if len(s) == best]
        got = frozenset(update(Mesh(tree), prio, eps).active)
        assert winners == [got]

History

Lindstrom and others had shown continuous terrain level of detail on regular grids at SIGGRAPH 96. Duchaineau, Wolinsky, Sigeti, Miller, Aldrich and Mineev-Weinstein presented ROAM at IEEE Visualization 97. The paper put the forced splits of the triangle bintree, the nested wedgie bounds and the two queues together, and it gave the optimality of the split queue for monotone priorities. Many terrain engines of the following years used ROAM or variants of it. As GPUs grew, methods that send large fixed blocks of triangles, such as geometry clipmaps in 2004, took its place in many systems.

References

  1. Mark Duchaineau, Murray Wolinsky, David E. Sigeti, Mark C. Miller, Charles Aldrich and Mark B. Mineev-Weinstein, ROAMing terrain, real-time optimally adapting meshes, Proceedings of IEEE Visualization 97, 81 to 88, Section 4.1 (the triangle bintree), Section 4.2 (forced splits, Figure 5), Section 5.1 (the split queue and the optimality), Section 5.2 (the merge queue), Section 6.1 (the wedgie thickness, Equation 1), Section 6.2 (the screen distortion, Equations 2 and 3) and Section 7.1 (frustum culling)
  2. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, the part on terrain level of detail in the chapter on acceleration algorithms (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.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • at least three sources
  • a scene preset for the example