Algorithm Search⌘K

Algorithmadvanced

View-dependent refinement of progressive meshes

Also called view-dependent LOD.

Refine or coarsen a progressive mesh locally by legal vertex splits and edge collapses, driven by the view frustum, the surface orientation and screen-space error.

Time
O(a + s N) worst
Space
Θ(n) extra
Where
N = the number of vsplits of the progressive mesh; a = the number of active vertices; n = the number of vertices of the full mesh; s = the number of vsplits and edge collapses in a pass
Properties
not adaptivenot comparison baseddeterministicin placeonlineiterativenot stable
Origin
Hugues Hoppe, 1997

View-dependent refinement keeps a progressive mesh at a different level of detail in different places: each frame it splits vertices where the surface is near, in view and facing the camera, and collapses edges elsewhere. A plain progressive mesh gives one sequence of meshes with a uniform level of detail, so the whole mesh is coarse or fine at once. The vertex splits here can happen in any order that a small set of conditions allows, and a split that is not yet allowed forces the splits it depends on first. ROAM does the same kind of work for a height field on a regular bintree; this method works on any mesh that a progressive mesh can describe.

In plain words

A detailed model is built by undoing many small simplification steps. Each step turns one point into two points and adds two small triangles. A normal progressive mesh undoes the steps in one fixed order, so the detail grows everywhere at the same time.

This method undoes a step only where the viewer needs it: where the surface is on the screen, faces the viewer and is close enough that the difference shows. It redoes steps where the viewer cannot see the detail. A step can only be undone when its neighbor triangles are there. If they are not, the method first undoes the older steps that make them, and then the step that it wanted.

Each frame it walks over the current points, tests each one, and makes the few changes that the new view needs.

The problem

The input is a progressive mesh: a base mesh M0M^0 and a sequence of NN vertex splits that gives the full mesh MNM^N with nn vertices. Each split vsplit(vs)\mathrm{vsplit}(v_s) replaces the vertex vsv_s by its children vtv_t and vuv_u and adds the faces flf_l and frf_r, and its record holds the four neighbor faces fn0,…,fn3f_{n0}, \ldots, f_{n3} across the outer edges of flf_l and frf_r. The splits form a binary forest, the vertex hierarchy. A selectively refined mesh is given by a front AA of active vertices that meets each root to leaf path once. The other input is a view, given by the eye ee, a view frustum and a screen-space tolerance τ\tau, and a test qrefine(v)\mathrm{qrefine}(v) that says whether the view needs the detail below vv. The output, each frame, is a front such that no active vertex has qrefine\mathrm{qrefine} true, and no legal collapse has qrefine\mathrm{qrefine} of its parent false. Every change is a legal vsplit or a legal edge collapse.

The algorithm

  1. VSPLIT-LEGAL(v) ▷ v is active and has children
  2. 1return true if f_n0, f_n1, f_n2 and f_n3 of v are all present
  3. ECOL-LEGAL(v_s) ▷ the children v_t and v_u are active
  4. 2for each outer edge of f_l and f_r do return false if the face across it is not its f_nj
  5. return true
  6. FORCE-VSPLIT(v0)
  7. 3stack ← [v0]
  8. 4while the stack is not empty do v ← the top of the stack
  9. 5if v is split then pop v
  10. 6else if v is not active then push parent(v)
  11. 7else if VSPLIT-LEGAL(v) then pop v and vsplit(v)
  12. 8else push the creator of each face f_nj of v that is not present
  13. ADAPT-REFINEMENT(qrefine) ▷ one pass per frame
  14. 9for each active vertex v do
  15. 10if v has children and qrefine(v) then FORCE-VSPLIT(v)
  16. 11else if v has a parent p, ECOL-LEGAL(p) and not qrefine(p) then ecol(p)
  17. QREFINE(v) ▷ w = p_v - e, d = |w|
  18. 12if the sphere of radius r_v around p_v is outside the view frustum then return false
  19. 13if w · n_v > 0 and (w · n_v)^2 > d^2 sin^2(alpha_v) then return false ▷ the normal cone faces away
  20. 14return mu_v^2 ≥ kappa^2 d^2 or delta_v^2 (d^2 - (w · nhat_v)^2) ≥ kappa^2 d^4

A face is present when the representatives of its three corners on the front are three distinct vertices. A vertex is split when it and all its ancestors are off the front, so it lies above the front. The creator of a face is the vertex whose vsplit adds it.

Lines L12 to L14 are the three parts of qrefine in Hoppe's Section 4. Line L12 uses a bounding sphere of the leaves below vv, as on the frustum culling page. Line L13 uses a cone of normals around nvn_v with the half angle αv\alpha_v: when every normal in the cone points away from the eye, the region below vv faces away. Line L14 is the screen-space test in squared form, with κ=τtan⁡(φ/2)/2\kappa = \tau \tan(\varphi/2)/2 for the field of view φ\varphi, that is κ2=(2cot⁡(φ/2))−2τ2\kappa^2 = (2 \cot(\varphi/2))^{-2} \tau^2. The deviation space of vv is given by μv\mu_v, a deviation in every direction, and δv\delta_v, a deviation along the unit normal n^v\hat n_v. The test needs no square root and no division.

In the code the mesh is a height field with yy up, built by half-edge collapses, and μv=0\mu_v = 0. The value δv\delta_v is the largest height jump of a split below vv, and rvr_v and the cone bound the leaves and the full-mesh faces below vv. These values are heuristics, not the fitted bounds of the paper.

Example

The test mesh is a 7×77 \times 7 grid of heights, with 49 vertices and 72 faces. With the seed 0 the simplification makes 18 half-edge collapses, so the base mesh has 31 vertices and 72−2⋅18=3672 - 2 \cdot 18 = 36 faces. The vertices of the full mesh are 0 to 48, and the inner vertices of the hierarchy are 49 to 66.

A forced split. From the base mesh, FORCE-VSPLIT(50) asks for the split of vertex 50, whose children are the leaves at the domain points (4,3)(4, 3) and (5,4)(5, 4).

step lines what happens stack after, top last
1 L6 50 is not active; push the parents 56, 58, 66 50, 56, 58, 66
2 L7 66 is a root and its split is legal 50, 56, 58
3 L7 split 58, then 56 50
4 L8 two neighbor faces of 50 are missing; push their creators 54 and 61 50, 54, 61
5 L6 61 is not active; push 62 and 64 50, 54, 61, 62, 64
6 L8 64 needs a face of 65; push 65 50, 54, 61, 62, 64, 65
7 L7 split 65, 64, 62, 61, 54 and 50 empty

The call makes 9 vsplits in the order 66, 58, 56, 65, 64, 62, 61, 54, 50. The mesh grows from 31 active vertices and 36 faces to 40 vertices and 54 faces. Of the 18 inner vertices of this hierarchy, 50 is the one whose forced split needs the most vsplits.

A sequence of views. With the seed 8, six random views and τ\tau between 0.05 and 0.4, repeated passes of ADAPT-REFINEMENT reach a fixed point. From the base mesh the first view takes 9 passes and 11 changes and ends with 44 active vertices and 62 faces. The next five views take 1, 1, 2, 2 and 2 passes, with 0, 0, 2, 2 and 1 changes. A small change of view needs a small number of changes, which is the reason to keep the front from frame to frame.

Correctness

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

  • Present faces. A face of the full mesh is present exactly when it is a base face or its creator is split. So the test of line L1 says that the creators of the four neighbor faces are split, and these creators come earlier in the vsplit order (a proved property).
  • force_vsplit ends. Each vertex that lines L6 and L8 push is not split and has a smaller index in the vsplit order than the vertex below it. Between two vsplits the indices on top strictly decrease, so the loop makes a vsplit after at most NN pushes. A vsplit moves the front down, so there are at most NN of them. At the end v0v_0 is split, and every vsplit was legal (a proved property).
  • A fixed point. If a pass of lines L9 to L11 makes no change, no active vertex asks for a split and no legal collapse is allowed. This is a fixed point, not an optimum: forced splits can leave vertices split that qrefine does not ask for (a proved property).
  • The screen-space test. The squared test of line L14 holds exactly when max⁡(μv, δv∣n^v×w∣/d)/d≥κ\max(\mu_v,\ \delta_v |\hat n_v \times w| / d) / d \ge \kappa, the angular size of the deviation space against κ\kappa (a proved property, by Lagrange's identity).
  • A valid mesh. On random sequences of legal vsplits and collapses, the tests check that each directed edge occurs once, that the border is a cycle and that the Euler characteristic is 1. This is a measurement, not a proof; the paper gives no proof of it. In 12 of 1200 such states one face of the height field was folded over in the domain, so the legality conditions do not keep the orientation of the faces.
Proof: Faces of a selectively refined mesh are present exactly when their creating vertex is split, force_vsplit ends with the vertex split, and the squared screen-space test equals the projected-length testfull

We use the notation of the page. The progressive mesh is built by NN half-edge collapses, and the vertex hierarchy is the binary forest of these collapses: a collapse of the edge (vt,vu)(v_t, v_u) creates the parent vsv_s. The vsplit order lists the inner vertices from coarse to fine, and idx(v)\mathrm{idx}(v) is the position of vv in it. A vsplit of vsv_s creates the two faces flf_l and frf_r; we call vsv_s their creator. The faces of the full mesh that are not created by any vsplit are the base faces. The record of vsv_s also holds the four neighbor faces fn0,…,fn3f_{n0}, \ldots, f_{n3}: the faces across the four outer edges of flf_l and frf_r in the mesh just after the vsplit of vsv_s in the vsplit order.

The front AA is the set of active vertices: a set that meets each root to leaf path of the forest exactly once. The representative rep(w)\mathrm{rep}(w) of a vertex ww is the unique member of AA on the path from ww to its root, if ww is below or at the front. A vertex vv is split when it lies strictly above the front: no ancestor of vv, and not vv itself, is in AA. A face of the full mesh with the corners (a,b,c)(a, b, c) is present in the selectively refined mesh when rep(a)\mathrm{rep}(a), rep(b)\mathrm{rep}(b) and rep(c)\mathrm{rep}(c) are distinct, and it then has these corners.

Which faces are present

Lemma 1. A face is present if and only if it is a base face or its creator is split.

Proof. Let ff be created by vsv_s with the children vtv_t and vuv_u, and let ff have the corners vt,vu,xv_t, v_u, x in the mesh just after the vsplit of vsv_s. Its corners in the full mesh are leaves aa, bb and cc below vtv_t, vuv_u and xx. The vertices vsv_s and xx are both vertices of the mesh at that moment, so their subtrees are disjoint, and xx is not an ancestor of vsv_s.

If vsv_s is not split, then vsv_s or one of its ancestors is in AA, and it is the representative of both aa and bb, so ff is not present.

If vsv_s is split, then no vertex on the path from vsv_s to its root is in AA. So rep(a)\mathrm{rep}(a) lies in the subtree of vtv_t and rep(b)\mathrm{rep}(b) in the subtree of vuv_u, and these are different. The representative of cc lies in the subtree of xx or is an ancestor of xx. An ancestor of xx that is also an ancestor of vsv_s is not in AA. So rep(c)\mathrm{rep}(c) is outside the subtree of vsv_s, and the three representatives are distinct.

For a base face, the three corners are below three distinct roots, so their representatives are in three disjoint subtrees. □\square

So the legality test of line L1, "all four neighbor faces are present", says that the creators of these faces are split. Each neighbor face exists in the mesh at the vsplit of vsv_s in the vsplit order, so it is a base face or its creator comes earlier: idx(creator(fnj))<idx(vs)\mathrm{idx}(\mathrm{creator}(f_{nj})) < \mathrm{idx}(v_s).

force_vsplit

Theorem 2. For an inner vertex v0v_0, FORCE-VSPLIT(v0)(v_0) (lines L3 to L8) ends, and at its end v0v_0 is split. Every vsplit that it makes is legal in the sense of line L1, and it makes no edge collapse.

Proof. Each pass looks at the top vv of the stack and does one of four things: it pops vv if vv is split (L5); it pushes the parent of vv if vv is neither split nor active (L6); it pops vv and makes a legal vsplit of vv (L7); or it pushes the creators of the neighbor faces of vv that are not present (L8).

A pushed vertex is never split at the moment it is pushed. In L6, vv is neither split nor active, so an ancestor of vv is in AA, and the parent of vv is that ancestor or lies below it; so it is not split. In L8, the pushed vertex is the creator of a face that is not present, and by Lemma 1 it is not split. Also each pushed vertex has a smaller index than vv: a parent is split before its child in the vsplit order, and the creators of the neighbor faces come before vv by the remark after Lemma 1.

Now suppose that from some pass on, no vsplit happens. Then the front does not change, a vertex that is not split stays not split, and no pass pops a pushed vertex (L5 pops only split vertices, and L7 makes a vsplit). So each pass after that pushes, and the top of the stack is always the last vertex pushed. Its index strictly decreases from pass to pass. This cannot go on forever, so a vsplit happens. A vsplit only moves the front down, so at most NN vsplits can happen, and the loop ends.

The vertex v0v_0 is at the bottom of the stack. It leaves the stack by L5, when it is split, or by L7, when it is split there. □\square

Hoppe's conditions make sure that a vsplit adds flf_l and frf_r between the right neighbor faces. They do not make sure that the faces keep their orientation: the test of the page found 12 of 1200 random states in which a face of the selectively refined height field is folded over in the domain. The tests check, on random sequences of legal vsplits and edge collapses, that the mesh stays an oriented manifold with boundary that covers the domain (each directed edge once, each border edge once, Euler characteristic 1). This is tested, not proved; the paper gives no proof of it.

adapt_refinement

Proposition 3. If a pass of ADAPT-REFINEMENT (lines L9 to L11) makes no change, then every active inner vertex vv has qrefine(v)\mathrm{qrefine}(v) false, and every legal edge collapse of an active pair has qrefine\mathrm{qrefine} of the parent true.

Proof. A pass visits each vertex that is active at the start. If it makes no change, it changes no state, so each test runs on the final front. A vertex with children and qrefine\mathrm{qrefine} true would cause a change at L10. A vertex with a parent pp for which the collapse is legal and qrefine(p)\mathrm{qrefine}(p) is false would cause a change at L11. Both children of pp are active when the collapse is legal, so the pass visits them. □\square

This is a fixed point, not an optimum: a forced vsplit can split vertices that qrefine\mathrm{qrefine} does not ask for, and such vertices stay split as long as the collapse is not legal. The paper runs one pass per frame and makes no claim of convergence; the test observes that repeated passes reach a fixed point on its examples.

The screen-space test

Let ee be the eye, vv a vertex at pp, w=p−ew = p - e and d=∣w∣d = |w|. The deviation space of vv is given by μv≥0\mu_v \ge 0 and δv≥0\delta_v \ge 0 with the unit normal n^v\hat n_v. The squared test of Hoppe (Section 4, with κ=τtan⁡(φ/2)/2\kappa = \tau \tan(\varphi / 2) / 2, that is κ2=(2cot⁡(φ/2))−2τ2\kappa^2 = (2 \cot(\varphi/2))^{-2} \tau^2) is

μv2≥κ2d2orδv2(d2−(w⋅n^v)2)≥κ2d4.\mu_v^2 \ge \kappa^2 d^2 \quad \text{or} \quad \delta_v^2 \left(d^2 - (w \cdot \hat n_v)^2\right) \ge \kappa^2 d^4.

Proposition 4. For d>0d > 0, the squared test holds if and only if max⁡(μv, δv∣n^v×w∣/d)/d≥κ\max(\mu_v,\ \delta_v |\hat n_v \times w| / d) / d \ge \kappa.

Proof. For a unit vector n^\hat n, ∣n^×w∣2=∣w∣2−(n^⋅w)2|\hat n \times w|^2 = |w|^2 - (\hat n \cdot w)^2 (Lagrange's identity). The first part is μv/d≥κ\mu_v / d \ge \kappa, because both sides are nonnegative. The second part is δv2∣n^v×w∣2≥κ2d4\delta_v^2 |\hat n_v \times w|^2 \ge \kappa^2 d^4, which is δv∣n^v×w∣/d2≥κ\delta_v |\hat n_v \times w| / d^2 \ge \kappa for the same reason. The maximum of two numbers is at least κ\kappa exactly when one of them is. □\square

The value δv∣n^×w∣/d\delta_v |\hat n \times w| / d is the largest length that a segment δvn^\delta_v \hat n shows across the line of sight, and dividing by dd gives its angular size, so the test compares the angular size of the deviation with κ\kappa. The values μv\mu_v and δv\delta_v that the code uses (μv=0\mu_v = 0, and δv\delta_v the largest height jump of a split below vv) are heuristics, not the bounds of the paper, which come from the fitted deviation of the surface. The bounding sphere radius rvr_v and the normal cone in lines L12 and L13 are bounds over the leaf positions and the full-mesh face normals below vv, which are a heuristic for the faces of the current mesh.

Complexity

A pass of ADAPT-REFINEMENT tests each of the aa active vertices once. Each vsplit or collapse costs O(1)O(1) with the face neighbor pointers of the paper, and force_vsplit makes at most NN pushes per vsplit, so a pass costs O(a+sN)O(a + s N) in the worst case. In practice a forced split needs few ancestors, as in the example. The paper keeps the active vertices in a list and the hierarchy in arrays, which take Θ(n)\Theta(n) space for the nn vertices of the full mesh, and it runs one pass per frame. The code is simpler: its collapse test scans the faces, so it shows the logic and not the speed.

Properties

  • Local. The mesh is fine only where qrefine asks for it, so the triangle count follows the view, not the size of the model.
  • Legal at every step. Every change keeps the faces of the mesh in the places that the vsplit records expect (a proved property of the legality tests).
  • Coherent. The front is kept from one frame to the next, and a small move of the camera gives few changes (a measurement on the example).
  • Not unique. The result depends on the order of the active vertices and on the history of forced splits, so two runs that reach the same view along different paths can give different meshes.
  • Pops. A vsplit changes the mesh at once. Hoppe hides this with geomorphs over a few frames, or with a small τ\tau.

Variants and improvements

  • Geomorphs. Each vsplit and each collapse can be made a geomorph over a short time, so that the change does not pop.
  • A face budget. In place of a fixed τ\tau, a renderer can change τ\tau from frame to frame so that the number of faces stays near a target (a tuning).
  • Terrain. Hoppe (1998) applies the same refinement to large terrains in blocks. Regular structures such as ROAM and geometry clipmaps trade the general hierarchy for simpler data.
  • Other hierarchies. Xia and Varshney, and Luebke and Erikson, gave view-dependent hierarchies of vertex merges at the same time; the general idea is the same, with other legality conditions.
  • On the GPU. Later systems refine clusters of triangles in place of single vertices, so that each change is a batch.

When to use it

Use view-dependent refinement for a single large mesh that is near and far at the same time, such as a terrain, a scanned object or a building seen from inside, when a few discrete levels of detail would be too coarse near the viewer or waste triangles far away. For many small objects, discrete levels of detail cost less. For a height field on a grid, ROAM or geometry clipmaps are simpler and need no vsplit records.

Pitfalls

  • Splitting without the neighbor test. If line L7 runs vsplit(v) without line L1, the new faces flf_l and frf_r attach to faces that are not there, and the mesh gets a hole or overlapping faces.
  • Collapsing without the edge test. If line L11 collapses pp without line L2, a face that a later split expects as a neighbor can be gone, and the next vsplit of a vertex next to it is never legal.
  • The tests in the wrong order. A split vertex is also not active. If line L6 comes before line L5, it pushes the parent of a split vertex, the loop climbs above the front, and at a split root there is no parent to push.
  • The wrong power of d. Line L14 compares squares. If the second part uses κ2d2\kappa^2 d^2 in place of κ2d4\kappa^2 d^4, it tests δv∣n^v×w∣/d≥κ\delta_v |\hat n_v \times w| / d \ge \kappa, which does not fall with the distance, so far regions are refined as much as near ones.
  • The wrong side of the cone. If line L13 tests w⋅nv<0w \cdot n_v < 0, it culls the regions that face the eye and keeps the ones that face away.
  • Bounds that are too small. If rvr_v in line L12 bounds only the vertex positions of the current mesh and not the leaves below vv, a region at the border of the frustum can be culled while some of its faces are still in view.

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.

view_dependent_refinement.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/view-dependent-refinement/. The authors are listed in prov/TRTDD8.jsonl.

"""View-dependent refinement of a progressive mesh, after Hoppe (1997).

The mesh is a height field: vertex positions are (x, y, z) with y up and the
domain plane is (x, z). A face (a, b, c) is counterclockwise seen from +y.

Build: a progressive mesh by half-edge collapses (v_t, v_u) -> v_s, where v_s
is a new vertex at the position of v_t. The vertex hierarchy is the binary
forest of these collapses; its leaves are the vertices of the full mesh M^n
and its roots are the vertices of the base mesh M^0.

Run time: the active vertices form a front of the forest. A face of M^n is in
the selectively refined mesh when the active ancestors of its three corners
are distinct, and its corners are those active ancestors. A vsplit replaces
v_s by v_t and v_u; an ecol does the reverse. Hoppe's legality conditions
decide which of these may happen.
"""

from math import sqrt


def orient(a, b, c):
    """Twice the signed area of (a, b, c) in the domain plane, positive if counterclockwise from +y."""
    return (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2])


def sub(a, b):
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def dot(a, b):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def grid_mesh(rng, g, amp=3):
    """A (g+1) x (g+1) height grid with integer heights. Returns positions, faces, border flags."""
    pos, border = [], []
    for i in range(g + 1):
        for j in range(g + 1):
            pos.append((i, rng.randint(0, amp), j))
            border.append(i in (0, g) or j in (0, g))
    faces = []
    for i in range(g):
        for j in range(g):
            a, b, c, d = i * (g + 1) + j, i * (g + 1) + j + 1, (i + 1) * (g + 1) + j + 1, (i + 1) * (g + 1) + j
            faces.append((a, b, c))
            faces.append((a, c, d))
    return pos, faces, border


class ProgressiveMesh:
    """The vertex hierarchy and the vsplit records, built by half-edge collapses."""

    def __init__(self, rng, pos, faces, border):
        self.pos = list(pos)
        self.faces = list(faces)
        self.n_leaves = len(pos)
        self.parent = {}
        self.children = {}
        self.rec = {}
        self.creator = {}
        bord = list(border)
        cur = {f: list(c) for f, c in enumerate(faces)}
        star = {v: set() for v in range(len(pos))}
        for f, c in cur.items():
            for v in c:
                star[v].add(f)
        order = []
        while True:
            cands = []
            for f, c in cur.items():
                for k in range(3):
                    t, u = c[k], c[(k + 1) % 3]
                    if not bord[u]:
                        rec = self._check(cur, star, t, u)
                        if rec is not None:
                            cands.append(rec)
            if not cands:
                break
            cands.sort()
            t, u, fl, fr, vl, vr, fn = rng.choice(cands)
            s = len(self.pos)
            self.pos.append(self.pos[t])
            bord.append(bord[t])
            self.parent[t] = self.parent[u] = s
            self.children[s] = (t, u)
            self.rec[s] = (fl, fr, fn)
            self.creator[fl] = self.creator[fr] = s
            star[s] = set()
            for f in star[t] | star[u]:
                if f in (fl, fr):
                    continue
                cur[f] = [s if v in (t, u) else v for v in cur[f]]
                star[s].add(f)
            for f in (fl, fr):
                for v in cur[f]:
                    star[v].discard(f)
                del cur[f]
            del star[t], star[u]
            order.append(s)
        self.order = order[::-1]  # vsplit order: coarse to fine
        self.index = {s: i for i, s in enumerate(self.order)}
        self.roots = sorted(star)
        self.base_faces = {f: tuple(c) for f, c in cur.items()}

    def _check(self, cur, star, t, u):
        both = [f for f in star[t] & star[u]]
        if len(both) != 2:
            return None
        fl = fr = None
        for f in both:
            c = cur[f]
            k = c.index(t)
            if c[(k + 1) % 3] == u:
                fl, vl = f, c[(k + 2) % 3]
            else:
                fr, vr = f, c[(k + 1) % 3]
        if fl is None or fr is None:
            return None
        nt = {v for f in star[t] for v in cur[f]} - {t}
        nu = {v for f in star[u] for v in cur[f]} - {u}
        if nt & nu != {vl, vr}:
            return None

        def across(a, b, skip):
            for f in star[a] & star[b]:
                if f != skip:
                    return f
            return None

        fn = (across(vl, t, fl), across(u, vl, fl), across(t, vr, fr), across(vr, u, fr))
        if None in fn or len(set(fn)) != 4:
            return None
        pt = self.pos[t]
        for f in star[u]:
            if f in (fl, fr):
                continue
            q = [pt if v == u else self.pos[v] for v in cur[f]]
            if orient(*q) <= 0:
                return None
        return (t, u, fl, fr, vl, vr, fn)

    def leaves(self, v):
        out, stack = [], [v]
        while stack:
            w = stack.pop()
            if w in self.children:
                stack.extend(self.children[w])
            else:
                out.append(w)
        return out


class SelectiveMesh:
    def __init__(self, pm):
        self.pm = pm
        self.active = set(pm.roots)

    def rep(self, w):
        while w not in self.active:
            w = self.pm.parent[w]
        return w

    def face(self, f):
        c = tuple(self.rep(w) for w in self.pm.faces[f])
        return c if len(set(c)) == 3 else None

    def faces(self):
        out = {}
        for f in range(len(self.pm.faces)):
            c = self.face(f)
            if c is not None:
                out[f] = c
        return out

    def is_split(self, v):
        w = v
        while True:
            if w in self.active:
                return False
            if w not in self.pm.parent:
                return True
            w = self.pm.parent[w]

    def vsplit_legal(self, v):
        if v not in self.active or v not in self.pm.children:
            return False
        return all(self.face(f) is not None for f in self.pm.rec[v][2])  # @line L1

    def ecol_legal(self, v):
        pm = self.pm
        if v not in pm.children:
            return False
        t, u = pm.children[v]
        if t not in self.active or u not in self.active:
            return False
        fl, fr, fn = pm.rec[v]
        cl, cr = self.face(fl), self.face(fr)
        x = next(w for w in cl if w not in (t, u))
        y = next(w for w in cr if w not in (t, u))
        want = (((x, t), fl, fn[0]), ((u, x), fl, fn[1]), ((t, y), fr, fn[2]), ((y, u), fr, fn[3]))
        for (a, b), own, other in want:  # @line L2
            got = [f for f in range(len(pm.faces)) if f != own and self._has_edge(f, a, b)]
            if got != [other]:
                return False
        return True

    def _has_edge(self, f, a, b):
        c = self.face(f)
        return c is not None and a in c and b in c

    def vsplit(self, v):
        self.active.remove(v)
        self.active.update(self.pm.children[v])

    def ecol(self, v):
        for w in self.pm.children[v]:
            self.active.remove(w)
        self.active.add(v)

    def force_vsplit(self, v0):
        pm = self.pm
        stack = [v0]  # @line L3
        while stack:  # @line L4
            v = stack[-1]
            if self.is_split(v):
                stack.pop()  # @line L5
            elif v not in self.active:
                stack.append(pm.parent[v])  # @line L6
            elif self.vsplit_legal(v):
                stack.pop()  # @line L7
                self.vsplit(v)
            else:
                for f in pm.rec[v][2]:  # @line L8
                    if self.face(f) is None:
                        stack.append(pm.creator[f])

    def adapt_refinement(self, qrefine):
        """One pass over the active vertices. Returns the number of changes."""
        pm = self.pm
        changes = 0
        for v in sorted(self.active):  # @line L9
            if v not in self.active:
                continue
            if v in pm.children and qrefine(v):
                self.force_vsplit(v)  # @line L10
                changes += 1
            elif v in pm.parent:
                p = pm.parent[v]
                if self.ecol_legal(p) and not qrefine(p):
                    self.ecol(p)  # @line L11
                    changes += 1
        return changes


def screen_error_exceeds(mu, delta, nhat, p, e, kappa):
    """Hoppe's test in squared form: does the deviation space project larger than kappa?"""
    w = sub(p, e)
    d2 = dot(w, w)
    return mu * mu >= kappa * kappa * d2 or delta * delta * (d2 - dot(w, nhat) ** 2) >= kappa * kappa * d2 * d2


def vertex_bounds(pm, delta_split):
    """Per vertex: bounding sphere radius, normal cone and deviation.

    r_v bounds the leaf positions below v (a heuristic). The cone covers the
    normals of the full-mesh faces that touch those leaves. delta_v is the
    largest height jump of a split below v (a heuristic, not a proved bound).
    """
    touch = {}
    for f, c in enumerate(pm.faces):
        for w in c:
            touch.setdefault(w, []).append(f)
    normals = []
    for c in pm.faces:
        a, b, d = (pm.pos[w] for w in c)
        n = cross(sub(b, a), sub(d, a))
        ln = sqrt(dot(n, n))
        normals.append((n[0] / ln, n[1] / ln, n[2] / ln))
    out = {}
    for v in range(len(pm.pos)):
        lv = pm.leaves(v)
        pv = pm.pos[v]
        r = max(sqrt(dot(sub(pm.pos[w], pv), sub(pm.pos[w], pv))) for w in lv)
        fs = {f for w in lv for f in touch[w]}
        s = [sum(normals[f][k] for f in fs) for k in range(3)]
        ls = sqrt(dot(s, s))
        nv = (s[0] / ls, s[1] / ls, s[2] / ls)
        cos_min = min(min(1.0, dot(nv, normals[f])) for f in fs)
        sin2 = 1.0 - cos_min * cos_min
        out[v] = (r, nv, sin2, delta_split.get(v, 0.0))
    return out


def deltas(pm):
    """delta_v = max(delta_t, delta_u, |y(v_u) - y(v_s)|), leaves have 0."""
    d = {}
    for s in reversed(pm.order):
        t, u = pm.children[s]
        d[s] = max(d.get(t, 0.0), d.get(u, 0.0), abs(pm.pos[u][1] - pm.pos[s][1]))
    return d


def make_qrefine(pm, bounds, eye, forward, fov, tau):
    """qrefine(v) for a square viewport with vertical field of view fov."""
    from math import tan

    lf = sqrt(dot(forward, forward))
    fw = (forward[0] / lf, forward[1] / lf, forward[2] / lf)
    up = (0.0, 1.0, 0.0)
    right = cross(fw, up)
    lr = sqrt(dot(right, right))
    right = (right[0] / lr, right[1] / lr, right[2] / lr)
    upv = cross(right, fw)
    t = tan(fov / 2)
    planes = []
    for axis in (right, upv):
        for sgn in (1.0, -1.0):
            n = tuple(fw[k] * t - sgn * axis[k] for k in range(3))
            ln = sqrt(dot(n, n))
            planes.append((n[0] / ln, n[1] / ln, n[2] / ln))
    kappa = tau * t / 2  # kappa^2 = (2 cot(fov/2))^-2 tau^2
    nhat = (0.0, 1.0, 0.0)

    def qrefine(v):
        r, nv, sin2, delta = bounds[v]
        w = sub(pm.pos[v], eye)
        if any(dot(w, n) < -r for n in planes) or dot(w, fw) < -r:  # @line L12
            return False
        a = dot(w, nv)
        if a > 0 and a * a > dot(w, w) * sin2:  # @line L13
            return False
        return screen_error_exceeds(0.0, delta, nhat, pm.pos[v], eye, kappa)  # @line L14

    return qrefine
test_view_dependent_refinement.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/view-dependent-refinement/. The authors are listed in prov/TRTDD8.jsonl.

import random
from math import pi, sqrt

from view_dependent_refinement import (
    ProgressiveMesh,
    SelectiveMesh,
    cross,
    deltas,
    dot,
    grid_mesh,
    make_qrefine,
    orient,
    screen_error_exceeds,
    sub,
    vertex_bounds,
)

G = 6


def build(seed):
    rng = random.Random(seed)
    pos, faces, border = grid_mesh(rng, G)
    return ProgressiveMesh(rng, pos, faces, border)


def valid(sm):
    pm = sm.pm
    fs = sm.faces()
    directed = set()
    undirected = {}
    area2 = 0
    for c in fs.values():
        area2 += orient(*(pm.pos[v] for v in c))
        for k in range(3):
            a, b = c[k], c[(k + 1) % 3]
            if (a, b) in directed:
                return False
            directed.add((a, b))
            undirected[frozenset((a, b))] = undirected.get(frozenset((a, b)), 0) + 1
    for e, n in undirected.items():
        if n == 1:
            p, q = (pm.pos[v] for v in e)
            on_border = (p[0] == q[0] and p[0] in (0, G)) or (p[2] == q[2] and p[2] in (0, G))
            if not on_border:
                return False
    used = {v for c in fs.values() for v in c}
    if used != sm.active:
        return False
    return len(used) - len(undirected) + len(fs) == 1 and area2 == 2 * G * G


def test_full_refinement_and_full_coarsening():
    for seed in range(3):
        pm = build(seed)
        assert len(pm.order) >= 15
        sm = SelectiveMesh(pm)
        assert sm.faces() == pm.base_faces
        for v in pm.order:
            assert sm.vsplit_legal(v)
            sm.vsplit(v)
        assert sm.faces() == {f: c for f, c in enumerate(pm.faces)}
        for v in reversed(pm.order):
            assert sm.ecol_legal(v)
            sm.ecol(v)
        assert sm.faces() == pm.base_faces


def test_dependencies_come_earlier_in_the_vsplit_order():
    pm = build(4)
    for v in pm.order:
        i = pm.index[v]
        if v in pm.parent:
            assert pm.index[pm.parent[v]] < i
        for f in pm.rec[v][2]:
            if f in pm.creator:
                assert pm.index[pm.creator[f]] < i


def test_random_legal_operations_keep_the_mesh_valid():
    rng = random.Random(5)
    for seed in range(3):
        pm = build(seed)
        sm = SelectiveMesh(pm)
        done = 0
        for _ in range(400):
            ops = [("s", v) for v in sm.active if sm.vsplit_legal(v)]
            ops += [("c", v) for v in {pm.parent[w] for w in sm.active if w in pm.parent} if sm.ecol_legal(v)]
            kind, v = rng.choice(sorted(ops))
            if kind == "s":
                sm.vsplit(v)
            else:
                sm.ecol(v)
            done += 1
            assert valid(sm)
        assert done == 400


def test_force_vsplit_splits_the_vertex_and_keeps_the_mesh_valid():
    rng = random.Random(6)
    pm = build(7)
    for _ in range(40):
        sm = SelectiveMesh(pm)
        for _ in range(rng.randrange(0, 20)):
            ops = [v for v in sm.active if sm.vsplit_legal(v)]
            if ops:
                sm.vsplit(rng.choice(sorted(ops)))
        v = rng.choice(pm.order)
        sm.force_vsplit(v)
        assert sm.is_split(v)
        assert valid(sm)


def test_adapt_refinement_reaches_a_fixed_point():
    pm = build(8)
    bounds = vertex_bounds(pm, deltas(pm))
    rng = random.Random(9)
    sm = SelectiveMesh(pm)
    for _ in range(6):
        eye = (rng.uniform(-2, G + 2), rng.uniform(4, 8), rng.uniform(G + 1, G + 5))
        target = (rng.uniform(1, G - 1), 0.0, rng.uniform(1, G - 1))
        q = make_qrefine(pm, bounds, eye, sub(target, eye), pi / 3, rng.uniform(0.05, 0.4))
        for _ in range(50):
            if sm.adapt_refinement(q) == 0:
                break
        assert sm.adapt_refinement(q) == 0
        assert valid(sm)
        for v in sm.active:
            assert not (v in pm.children and q(v))
            if v in pm.parent:
                p = pm.parent[v]
                assert not (sm.ecol_legal(p) and not q(p))


def test_squared_screen_error_test_equals_the_projected_radius_form():
    rng = random.Random(10)
    checked = 0
    for _ in range(5000):
        mu, delta = rng.uniform(0, 0.2), rng.uniform(0, 1)
        n = tuple(rng.uniform(-1, 1) for _ in range(3))
        ln = sqrt(dot(n, n))
        n = tuple(x / ln for x in n)
        p = tuple(rng.uniform(-5, 5) for _ in range(3))
        e = tuple(rng.uniform(-5, 5) for _ in range(3))
        kappa = rng.uniform(0.001, 0.2)
        w = sub(p, e)
        d = sqrt(dot(w, w))
        c = cross(n, w)
        radius = max(mu, delta * sqrt(dot(c, c)) / d) / d
        if abs(radius - kappa) < 1e-9:
            continue
        assert screen_error_exceeds(mu, delta, n, p, e, kappa) == (radius >= kappa)
        checked += 1
    assert checked > 4900

History

Hoppe introduced progressive meshes in 1996 and their view-dependent refinement at SIGGRAPH 97. The second paper added the vertex hierarchy, the neighbor faces in each vsplit record that make the legality test local, force_vsplit for splits whose neighbors are missing, and a screen-space test that projects a deviation space with no division. At about the same time Xia and Varshney and Luebke and Erikson published other view-dependent simplification schemes. Hoppe applied the method to large terrains in 1998, and later work moved the refinement to clusters of triangles that suit the GPU.

References

  1. Hugues Hoppe, View-dependent refinement of progressive meshes, SIGGRAPH 97, 189 to 198, Section 3 (the vertex hierarchy, vsplit and ecol and their legality), Section 4 (qrefine, the view frustum, the surface orientation and the screen-space geometric error) and Section 5 (adapt_refinement and force_vsplit)
  2. Hugues Hoppe, Progressive meshes, SIGGRAPH 1996, 99 to 108, the vertex split and the edge collapse, and the construction of the sequence by simplification
  3. David Luebke, Martin Reddy, Jonathan D. Cohen, Amitabh Varshney, Benjamin Watson and Robert Huebner, Level of Detail for 3D Graphics, Morgan Kaufmann, 2003, the chapters on view-dependent level of detail and on the vertex hierarchy (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
  • a scene preset for the example