Data structureadvanced
Progressive mesh
Also called Hoppe progressive mesh.
Hoppe's representation of a mesh as a coarse base mesh and a sequence of vertex splits that undo edge collapses, for smooth level of detail and streaming.
- Time
- O(n^2 d) build_codeO(n d log n) build_heapO(d) expected ecolO(k d) refineO(d) vsplit
- Space
- Θ(n) extra
- Where
- d = the largest number of faces at the two vertices of an edge; k = the number of splits applied; n = the number of vertices
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
A progressive mesh stores a triangle mesh as a coarse base mesh and a list of vertex splits. Each vertex split adds one vertex and, inside the surface, two triangles, and the splits in order rebuild the meshes exactly. It comes from mesh simplification run backwards: simplification removes vertices by edge collapses, each collapse is recorded as the vertex split that undoes it, and the records are kept in reverse order. Hugues Hoppe introduced the structure in 1996. Any prefix of the list gives a valid mesh, so a program can stream the mesh coarse to fine, stop at any level of detail, and move between levels one vertex at a time.
In plain words
Start with a detailed surface made of triangles. Shrink one short edge to a single point: the two triangles on that edge disappear, and the surface has one point fewer. Repeat until the surface is very coarse.
Each time, write down a small note that says exactly how to pull the point apart again: which point, where its two halves go, and which of its neighbours mark the two triangles that come back.
Keep the coarse surface and the notes in reverse order. Reading the notes one by one grows the surface back, step by step, to the original. You can stop after any note and still have a proper surface, so a viewer can show a rough shape at once and refine it while the rest arrives.
The abstract type
The structure holds an oriented manifold mesh of triangles, with faces oriented by the right-hand rule. The operations are:
- : collapse the edge into the vertex at the position , and return the vertex split that undoes it. It fails if the collapse would make the mesh stop being a manifold.
- : apply the vertex split , the inverse of the collapse that made it.
- : whether the collapse of is legal.
- : collapse edges until vertices remain, and return the base mesh and the splits in the order of refinement.
- : the mesh after the first splits.
The main law is for every legal collapse: the same vertices with the same positions, and the same faces with the same corners in the same order.
Representation
Let be the face with the directed edge and the face with . On a boundary edge one of them is missing. A vertex split is a record
| field | meaning |
|---|---|
| , | the vertex that stays and the vertex that comes back |
| , | the third vertices of and , or none |
| , | the positions of and before the collapse |
| , | the ids and the corners of the two removed faces |
The record does not list the faces that go back from to . They are found from and alone: they are the faces around counterclockwise from the edge to up to the edge to . So a record has a fixed size, whatever the degree of the vertex.
The mesh of the code keeps stable ids: a map from vertex ids to positions, a map from face ids to oriented triangles, and for each vertex the set of its faces, its star. In Hoppe's stream the ids are implicit: the vertices of are numbered to , the split creates the vertex , and the new faces are appended. Then and the face ids need no storage, needs about bits, and and can be named by their place among the neighbours of .
Operations
ECOL(M, v_s, v_t, p)- 1
f_l ← the face with v_s → v_t, v_l its third vertex; f_r ← the face with v_t → v_s, v_r its third vertex - 2
if v_l = v_r or not LINK(M, v_s, v_t) then fail - 3
s ← (v_s, v_t, v_l, v_r, p(v_s), p(v_t), f_l with its corners, f_r with its corners) - 4
remove f_l and f_r - 5
in every other face of v_t, replace v_t by v_s - 6
p(v_s) ← p; remove v_t - 7
return s VSPLIT(M, s)- 8
F ← the faces around v_s counterclockwise from the edge to v_r up to the edge to v_l - 9
in every face of F, replace v_s by v_t - 10
p(v_s) ← s.p_s; p(v_t) ← s.p_t - 11
put back f_l and f_r with their ids and corners LINK(M, v_s, v_t)- 12
close the boundary with one extra vertex ω; Lk(v) ← the vertices and edges opposite v - 13
return Lk(v_s) ∩ Lk(v_t) = Lk(v_s v_t) ▷ Lk of the edge: v_l, v_r, and ω on a boundary edge BUILD(M, n_0)- 14
while M has more than n_0 vertices and some edge passes LINK: v_s v_t ← the cheapest such edge; push ECOL(M, v_s, v_t, p) - 15
return M as M^0, and the pushed records in reverse order
Line L8 in detail. Around counterclockwise, turns from to and from to , so the other faces of run from to . Around , turns from to and from to , so the other faces of run from to . After the collapse both runs are around , and the run from to is exactly the old faces of . When is on the boundary, its run has a gap: the walk goes from to the end of the fan of , then from the start of the fan to . When is missing, the walk starts at the start of the fan, and when is missing it ends at the end of the fan.
The link condition. The link of a vertex is the cycle (or path) of vertices and edges opposite it in its faces. Closing the boundary with one extra vertex , joined to every boundary edge by a triangle, turns a mesh with boundary into a closed one. Line L13 is the condition of Dey, Edelsbrunner, Guha and Nekhayev. It forbids, for example, collapsing an edge of a tetrahedron (the two links share an edge), collapsing an inner edge whose two ends are both on the boundary (they share , which would pinch the surface), and collapsing an edge whose ends have a third common neighbour (two edges would merge into one).
Placement and cost. The position and the order of the collapses are not part of the structure. The code of this page takes the shortest legal edge and its midpoint, with exact rational arithmetic. Quadric error metrics give a much better cost and position. Hoppe's construction minimized an energy of the distance to the original surface.
Example
Take the octahedron with the vertices , , , , , , and the faces , , , , , , , . Collapse into at .
- Line L1: face 3 is , which contains , so is face 3 and . Face 0 is , which contains , so is face 0 and .
- Line L2: the neighbours of 0 are and those of 4 are . They share only , and the links share no edge, so the collapse is legal.
- Lines L3 to L6: the record is . Faces 1 and 2 become and . The result has 5 vertices, 9 edges and 6 faces, so is unchanged.
Now the split. Around vertex 0 the faces turn (face 1), (face 2), (face 7) and (face 4). Line L8 walks from : face 1 to 1, face 2 to 3, and stops at . So faces 1 and 2 get vertex 4 back, lines L10 and L11 restore the positions and faces 0 and 3, and the mesh is the octahedron again, equal in every entry.
Measured. The tests ran BUILD with the shortest edge first down to 4 vertices, and then all the splits, on these meshes (the coordinates jittered by rationals with seeds 1, 2 and 3):
| mesh | , | legal edges at the start | base mesh | splits | splits with one face |
|---|---|---|---|---|---|
| octahedron | 6, 8 | 12 of 12 | 4 vertices, 4 faces | 2 | 0 |
| octahedron subdivided twice | 66, 128 | 192 of 192 | 4 vertices, 4 faces | 62 | 0 |
| torus grid | 30, 60 | 90 of 90 | 7 vertices, 14 faces | 23 | 0 |
| grid disk | 30, 40 | 67 of 69 | 4 vertices, 2 faces | 26 | 14 |
Every level rebuilt by REFINE was equal to the mesh after the matching collapse, and was equal to the input. The spheres end as a tetrahedron and the torus at 7 vertices; in both, every edge fails the link condition, so no further collapse is possible. The torus result agrees with the known fact that a triangulated torus needs at least 7 vertices; that fact is cited, not tested. These are measurements on these meshes, not bounds.
Correctness
Invariant. After any sequence of legal collapses, the stack of records holds, for each collapse, everything it removed or changed except the faces that it moved from to , and those faces are exactly the run of line L8 at the moment the split is applied.
The proof in proofs/correctness.md shows:
- A legal collapse keeps : it removes one vertex, three edges and two faces inside the surface, or one vertex, two edges and one face on a boundary edge, and it creates no repeated or degenerate face.
- The run of line L8 is exactly the set of faces of other than and , in all four cases (both faces present, on the boundary, missing, missing).
- So exactly, and by induction on the stack, applying the first splits to gives , for every .
That a legal collapse keeps the mesh a manifold of the same topological type is the theorem of Dey, Edelsbrunner, Guha and Nekhayev; it is cited, not proved. The tests check it on every legal collapse of the meshes above.
Proof: A legal edge collapse keeps the Euler characteristic and is undone exactly by its vertex split, so every level of a progressive mesh is rebuilt exactlyfull
Setting. is an oriented manifold mesh of triangles with stable vertex and face ids, faces oriented by the right-hand rule. For a vertex let be the map over the faces of , written with first in their cyclic order. Being an oriented manifold mesh means: every directed edge is in at most one face, so is a function and is one to one; no face repeats a vertex; and for each the arcs form one cycle (an inner vertex) or one path (a boundary vertex). The start of a path is the vertex that is a key but not a value, and its end is the value that is not a key. ECOL, VSPLIT and LINK are lines L1 to L13 of the page. A collapse of is legal if line L2 does not fail: the edge exists, , and the link condition holds.
Claim.
- A legal collapse leaves no face with a repeated vertex and no two faces on the same three vertices, and it keeps .
- Let be the set of faces of other than and before a legal collapse. After the collapse, the walk of line L8 visits exactly the faces of .
- VSPLIT applied right after the ECOL that returned the record restores the mesh exactly. Hence if are the records of BUILD in refinement order, applying to gives the mesh that BUILD had after collapses, for every .
- ECOL, VSPLIT and BUILD terminate.
Facts from the link condition. In a manifold mesh the vertices of the link of are the neighbours of , plus when is on the boundary, and its edges are the pairs , plus for each boundary edge . The link of the edge has the vertices and that exist, plus if the edge is on the boundary, and no edges. So the link condition says:
- (a) the common neighbours of and are exactly the vertices , that exist;
- (b) no edge is in a face of and in a face of opposite to them, and no boundary edge goes with a boundary edge ;
- (c) if is an inner edge, and are not both on the boundary, since then would be a common link vertex that is not in the link of the edge.
Proof of 1. A face that contains both and contains the edge in one direction, and each direction is in at most one face, so these faces are and , which line L4 removes. So the faces of do not contain , and renaming to in them, in line L5, makes no face with a repeated vertex. Suppose a face of after the renaming has the same vertex set as another face. That face is not in (two faces of with the same vertices would have been equal before), so it is an old face of . Then the edge is opposite and opposite , which (b) forbids.
Counting: one vertex goes away. An edge with becomes , and it merges with an old edge exactly when is a common neighbour, which by (a) is or . So the edges lost are and one per face among , , and the faces lost are and . Inside the surface the change of is , and on a boundary edge it is .
Proof of 2. Write and for the maps before the collapse. Since and , the map has the arcs (from ) and (from ), and has the arcs and . Let be without its arcs from and ; its arcs are the faces of . Let be without the arcs from and . After the collapse the map of has the arcs of and of , since the renamed faces of have in the place of and contain neither nor otherwise (proof of 1).
The keys of and are disjoint. A common key is a common neighbour, so it is or by (a). In the key belongs to the arc , which is not in , and has one arc per key, so is not a key of . In the key belongs to , so is not a key of . In the same way the values are disjoint. So is a function, and the walk of line L8 is well defined.
Case 1: both faces exist, inner. is the cycle , so is a path from to . The walk starts at , follows , since is a key of only, and the path never meets before its last vertex. It stops at after the faces of , which are .
Case 2: both faces exist, on the boundary. By (c), is inner, so is a path from to . is a path that contains , so is two paths, from to the end of and from the start of to , either of which may have no arcs. Then is the single path , , . The walk goes from along to the end of , where the vertex is not a key, jumps to the start of , which is the start of (or if is empty), and follows to . It visits and nothing of .
Case 3: is missing. Then is a boundary edge, and both ends are on the boundary. The arc is the last arc of the path and is the first arc of , so is a path from the start of to and a path from to the end of . is the path , . It is not a cycle: the start of and the end of are neighbours of and ; if they were equal, this vertex would be a common neighbour other than , against (a), or both paths would be empty and the link edge would be common, against (b). The walk starts at the start of and stops at , after exactly the arcs of .
Case 4: is missing. This is case 3 with the directions reversed: is a path from the start of to and a path from to the end of . The walk starts at and stops at the end of , after exactly the arcs of .
Proof of 3. Line L3 stores the old positions and the ids and corner tuples of and . Lines L4 to L6 change only , , the faces of , the position of and the vertex . By claim 2, line L9 renames to in exactly the faces of , at the same place in each tuple where line L5 renamed to , and these tuples contained no before, so they get back their old tuples. Line L10 restores both positions, and line L11 puts and back with their old ids and tuples. No other entry was changed by either operation, so the mesh is equal to the one before the collapse, entry by entry, and the stars, which are computed from the faces, are equal as well.
For the levels, BUILD makes meshes by collapses , and returns and = the record of . By induction on , applying to gives : for it is , and if the first splits gave , then is the record of , which turned into , so applied right after it gives by the first part. So , and .
Proof of 4. ECOL and LINK do a fixed amount of work for each face of and . Each step of the walk of line L8 visits a new arc of (the arcs form a cycle or a path and the walk stops at or at the end, and jumps to the start at most once), so it takes at most as many steps as has faces. Each round of BUILD either removes one vertex or stops, so it runs at most rounds.
The link condition also keeps the mesh a manifold of the same topological type; this is the theorem of Dey, Edelsbrunner, Guha and Nekhayev, cited and not proved here. Claims 1 to 4 give what the page states: legal collapses keep , and the stored splits rebuild every level and the input exactly.
Complexity
With a hash set for each star, ECOL and VSPLIT look only at the faces of and , and LINK builds two links of the same size, so each takes time, expected for the hash sets, where is the number of faces at and . REFINE to level costs the sum of these over the splits, which is for meshes of bounded degree. The structure uses space: the base mesh and one record of fixed size per split.
BUILD as in the code scans all edges for each collapse, which is in total. With a priority queue of edge costs that is updated after each collapse, as in quadric simplification, it takes for bounded degree .
Variants
- Geomorphs. Instead of jumping from to , move from to over a few frames, so that changes of level are not visible. Hoppe's paper describes this.
- View-dependent refinement. Hoppe in 1997 arranged the splits in a forest, so that each region of the mesh can be refined on its own, depending on the view. A split then needs its neighbours to be present, which adds dependency rules.
- Half-edge collapse. With always equal to the old position of , no new positions are needed, and stays at a vertex of the input. This suits progressive transmission, because the coarse meshes use only input vertices.
- Vertex removal and other operators. Removing a vertex and filling the hole, or merging vertices that are not joined by an edge (vertex pair contraction, as in quadric simplification), give other progressive formats. Vertex pair contraction can change the topology, which a progressive mesh with the link condition never does.
- Compression. Progressive mesh compression codes the splits in batches with few bits each. Single-rate coders such as Edgebreaker use fewer bits in total but cannot show coarse levels.
When to use it
Use a progressive mesh when a mesh must be shown or sent at many levels of detail: streaming over a network, level of detail in games and viewers, or a coarse proxy for simulation. Every level is a valid manifold mesh, and moving between neighbouring levels costs per vertex. If only one coarse level is needed, plain mesh simplification is simpler. If the mesh is only stored or sent once at full detail, a single-rate coder is smaller.
Pitfalls
- Skipping the link condition. A collapse that fails it can glue two sheets, pinch the surface at a vertex, or make two faces with the same three vertices, as on a tetrahedron. The mesh then stops being a manifold, and later splits may not find their faces.
- Fold-overs. The link condition is about connectivity only. Moving to can still turn a face over, so that its normal points inward. Test the normals before and after, or in a flat parameter domain the sign of ORIENT2D, the orientation test. In floating point that sign can be wrong for thin faces because of catastrophic cancellation; exact arithmetic avoids it. This is the robustness problem of geometry.
- Storing the moved faces. Recording the list of faces moved from to makes the record size depend on the degree. Deriving them from and keeps it fixed, but the walk must then handle the boundary gap of line L8, which a first version of the code of this page did not do: it failed on a corner vertex of a grid with only two faces.
- Order of the splits. A split is valid only on the mesh made by the earlier splits. Applying the splits out of order, or after an edit of the mesh, gives wrong faces without an error.
- Attributes. Normals, colours and texture coordinates on the corners also need to be restored. A record that stores only positions loses the seams of a texture atlas.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the mx2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mx2 pages.
Points are tuples of int, fractions.Fraction or float. ORIENT2D is exact
when the coordinates are int or Fraction. A mesh is a list of faces, each a
tuple of three vertex indices, oriented so that the outward normal follows
the right-hand rule (counterclockwise seen from outside).
"""
import math
from fractions import Fraction
def orient2d(a, b, c):
"""Twice the signed area of triangle abc: > 0 if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def exact_orient2d(a, b, c):
"""ORIENT2D with the float coordinates converted to rationals first, so the sign is exact."""
return orient2d(*[tuple(Fraction(x) for x in p) for p in (a, b, c)])
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a list of n rows of length n, b is a list of n rows of length m
(m right-hand sides). Entries are Fraction (exact), float or complex.
Raises ValueError if a pivot has absolute value <= tol.
"""
n = len(a)
m = len(b[0]) if n else 0
rows = [list(a[i]) + list(b[i]) for i in range(n)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
if abs(rows[piv][col]) <= tol:
raise ValueError("singular matrix")
rows[col], rows[piv] = rows[piv], rows[col]
pr = rows[col]
for r in range(col + 1, n):
f = rows[r][col]
if f:
f = Fraction(f) / pr[col] if isinstance(f, int) and isinstance(pr[col], int) else f / pr[col]
row = rows[r]
for k in range(col, n + m):
if pr[k]:
row[k] -= f * pr[k]
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
row = rows[i]
for k in range(m):
s = row[n + k]
for j in range(i + 1, n):
if row[j]:
s -= row[j] * x[j][k]
x[i][k] = Fraction(s) / row[i] if isinstance(s, int) and isinstance(row[i], int) else s / row[i]
return x
def cholesky(a):
"""The lower triangular factor l with a = l l^T of a symmetric positive definite float matrix."""
n = len(a)
l = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
if i == j:
if s <= 0:
raise ValueError("matrix is not positive definite")
l[i][i] = math.sqrt(s)
else:
l[i][j] = s / l[j][j]
return l
def cholesky_solve(l, b):
"""Solve l l^T x = b for one right-hand side b, a list of floats."""
n = len(l)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(l[i][k] * y[k] for k in range(i))) / l[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
return x
def directed_edges(faces):
"""Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
out = {}
for f, tri in enumerate(faces):
for k in range(3):
e = (tri[k], tri[(k + 1) % 3])
if e in out:
raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
out[e] = (f, k)
return out
def undirected_edges(faces):
"""The sorted list of edges, each a sorted pair of vertex indices."""
return sorted({tuple(sorted((tri[k], tri[(k + 1) % 3]))) for tri in faces for k in range(3)})
def boundary_loop(faces):
"""The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
de = directed_edges(faces)
nxt = {}
for i, j in de:
if (j, i) not in de:
if i in nxt:
raise ValueError("boundary vertex %r is not manifold" % (i,))
nxt[i] = j
if not nxt:
raise ValueError("the mesh has no boundary")
start = min(nxt)
loop = [start]
while True:
v = nxt[loop[-1]]
if v == start:
break
loop.append(v)
if len(loop) != len(nxt):
raise ValueError("the boundary has more than one loop")
return loop
def euler_characteristic(faces):
"""V - E + F of the mesh, counting only the vertices used by faces."""
verts = {v for tri in faces for v in tri}
return len(verts) - len(undirected_edges(faces)) + len(faces)
def length(p, q):
return math.sqrt(sum((float(a) - float(b)) ** 2 for a, b in zip(p, q)))
def corner_angle(a, b, c):
"""The angle opposite the side of length a in a triangle with sides a, b, c (law of cosines)."""
x = (b * b + c * c - a * a) / (2 * b * c)
return math.acos(max(-1.0, min(1.0, x)))
def triangle_frame(p0, p1, p2):
"""Corners of a congruent counterclockwise 2D triangle: p0 at 0, p1 on the positive x-axis."""
l01, l12, l20 = length(p0, p1), length(p1, p2), length(p2, p0)
a0 = corner_angle(l12, l01, l20)
return (0.0, 0.0), (l01, 0.0), (l20 * math.cos(a0), l20 * math.sin(a0))
progressive_mesh.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/progressive-mesh/. The authors are listed in prov/WJ1E5T.jsonl.
"""A progressive mesh (after Hoppe 1996): a base mesh and a list of vertex splits.
The mesh keeps stable ids: pos maps a vertex id to its position, faces maps a
face id to an oriented triangle (right-hand rule), and star maps a vertex id
to the ids of its faces. An edge collapse ecol(vs, vt, p) removes the faces
fl = (vs, vt, vl) and fr = (vt, vs, vr) (one of them may be missing on the
boundary), renames vt to vs in the other faces of vt, and moves vs to p. It
returns the record of the vertex split that undoes it: the ids vs, vt, vl, vr,
the old positions of vs and vt, and the ids and corners of fl and fr. The
split does not store which faces go back to vt: they are the faces around vs
counterclockwise from the edge to vr up to the edge to vl.
"""
from collections import namedtuple
from fractions import Fraction
OMEGA = -1 # the extra vertex that closes the boundary in the link condition
VSplit = namedtuple("VSplit", "vs vt vl vr ps pt fl fr")
class Mesh:
def __init__(self, vertices, faces):
self.pos = {v: tuple(p) for v, p in enumerate(vertices)}
self.faces = {f: tuple(t) for f, t in enumerate(faces)}
self.star = {v: set() for v in self.pos}
for f, t in self.faces.items():
if len(set(t)) != 3:
raise ValueError("face %r repeats a vertex" % (f,))
for v in t:
self.star[v].add(f)
def copy(self):
m = Mesh([], [])
m.pos = dict(self.pos)
m.faces = dict(self.faces)
m.star = {v: set(s) for v, s in self.star.items()}
return m
def state(self):
"""Everything that defines the mesh, for exact comparisons."""
return dict(self.pos), dict(self.faces)
def rotate(tri, v):
"""The triangle tri as (v, a, b), keeping its orientation."""
k = tri.index(v)
return tri[k], tri[(k + 1) % 3], tri[(k + 2) % 3]
def fan(mesh, v):
"""Around v counterclockwise: a -> (b, face id) for each face (v, a, b)."""
out = {}
for f in mesh.star[v]:
_, a, b = rotate(mesh.faces[f], v)
out[a] = (b, f)
return out
def edge_faces(mesh, vs, vt):
"""((id, vl) of the face with the directed edge vs -> vt, (id, vr) of the face with vt -> vs); None if absent."""
fl = fr = None
for f in mesh.star[vs] & mesh.star[vt]:
v, a, b = rotate(mesh.faces[f], vs)
if a == vt:
fl = (f, b)
else:
fr = (f, a)
return fl, fr
def link(mesh, v):
"""The vertices and edges of the link of v, after closing the boundary with OMEGA."""
nxt = fan(mesh, v)
verts, edges = set(), set()
for a, (b, _) in nxt.items():
verts |= {a, b}
edges.add(frozenset((a, b)))
ends = {b for b, _ in nxt.values()}
for a in nxt:
if a not in ends: # the edge v -> a has no face on its other side
verts.add(OMEGA)
edges.add(frozenset((a, OMEGA)))
for b in ends:
if b not in nxt: # the edge b -> v has no face on its other side
verts.add(OMEGA)
edges.add(frozenset((b, OMEGA)))
return verts, edges
def link_condition(mesh, vs, vt):
"""True if Lk(vs) and Lk(vt) meet exactly in Lk(vs vt): the collapse keeps the surface a manifold."""
fl, fr = edge_faces(mesh, vs, vt)
if fl is None and fr is None:
return False
lk_e = {x[1] for x in (fl, fr) if x is not None}
if fl is None or fr is None:
lk_e.add(OMEGA)
vs_verts, vs_edges = link(mesh, vs) # @line L12
vt_verts, vt_edges = link(mesh, vt)
return (vs_verts & vt_verts) == lk_e and not (vs_edges & vt_edges) # @line L13
def ecol(mesh, vs, vt, p):
"""Collapse the edge vs vt into vs at position p, and return the vertex split that undoes it."""
fl, fr = edge_faces(mesh, vs, vt) # @line L1
vl = fl[1] if fl else None
vr = fr[1] if fr else None
if vl == vr or not link_condition(mesh, vs, vt): # @line L2
raise ValueError("the collapse of %r %r breaks the link condition" % (vs, vt))
rec = VSplit(vs, vt, vl, vr, mesh.pos[vs], mesh.pos[vt], # @line L3
(fl[0], mesh.faces[fl[0]]) if fl else None, (fr[0], mesh.faces[fr[0]]) if fr else None)
for x in (fl, fr):
if x is not None:
f = x[0]
for v in mesh.faces.pop(f): # @line L4
mesh.star[v].discard(f)
for f in mesh.star.pop(vt):
mesh.faces[f] = tuple(vs if v == vt else v for v in mesh.faces[f]) # @line L5
mesh.star[vs].add(f)
mesh.pos[vs] = p # @line L6
del mesh.pos[vt]
return rec # @line L7
def vsplit(mesh, rec):
"""Undo the edge collapse that returned rec."""
vs, vt, vl, vr = rec.vs, rec.vt, rec.vl, rec.vr
nxt = fan(mesh, vs)
ends = {b for b, _ in nxt.values()}
starts = [x for x in nxt if x not in ends]
if len(starts) > 1:
raise ValueError("vertex %r has more than one fan" % (vs,))
# Walk counterclockwise from the edge to vr (or from the start of the fan) to the edge
# to vl (or to the end of the fan), passing over the boundary gap of vs if there is one.
a = vr if vr is not None else starts[0]
moved = []
while a != vl: # @line L8
if a not in nxt:
if vl is None or not starts or len(moved) > len(nxt):
break
a = starts[0]
continue
b, f = nxt[a]
moved.append(f)
a = b
mesh.star[vt] = set()
for f in moved:
mesh.faces[f] = tuple(vt if v == vs else v for v in mesh.faces[f]) # @line L9
mesh.star[vs].discard(f)
mesh.star[vt].add(f)
mesh.pos[vs], mesh.pos[vt] = rec.ps, rec.pt # @line L10
for x in (rec.fl, rec.fr):
if x is not None:
f, tri = x
mesh.faces[f] = tri # @line L11
for v in tri:
mesh.star[v].add(f)
def edges(mesh):
return sorted({tuple(sorted((t[k], t[(k + 1) % 3]))) for t in mesh.faces.values() for k in range(3)})
def squared_length(mesh, a, b):
return sum((x - y) ** 2 for x, y in zip(mesh.pos[a], mesh.pos[b]))
def build(vertices, faces, target):
"""Collapse the shortest legal edge to its midpoint until target vertices remain or no edge is legal.
Returns (base mesh, vertex splits in refinement order). Coordinates should be int or
Fraction so that the costs and midpoints are exact.
"""
mesh = Mesh(vertices, faces)
records = []
while len(mesh.pos) > target:
best = None
for a, b in edges(mesh):
if link_condition(mesh, a, b):
key = (squared_length(mesh, a, b), a, b)
if best is None or key < best:
best = key
if best is None:
break
_, vs, vt = best # @line L14
p = tuple(Fraction(x + y, 2) for x, y in zip(mesh.pos[vs], mesh.pos[vt]))
records.append(ecol(mesh, vs, vt, p))
records.reverse()
return mesh, records # @line L15
def refine(base, records, k=None):
"""The mesh after the first k vertex splits (all of them if k is None)."""
mesh = base.copy()
for rec in records[:k]:
vsplit(mesh, rec)
return mesh
test_progressive_mesh.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/progressive-mesh/. The authors are listed in prov/WJ1E5T.jsonl.
import random
from fractions import Fraction
import pytest
from mx2geom import directed_edges, euler_characteristic
from progressive_mesh import Mesh, build, ecol, edges, link_condition, refine, vsplit
TET_V = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
TET_F = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)]
OCTA_V = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
OCTA_F = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
STRIP_V = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (0, 1, 0), (1, 1, 0), (2, 1, 0)]
STRIP_F = [(0, 1, 4), (0, 4, 3), (1, 2, 5), (1, 5, 4)]
def subdivide(v, f):
v = list(v)
mid, out = {}, []
def m(a, b):
key = (min(a, b), max(a, b))
if key not in mid:
mid[key] = len(v)
v.append(tuple(Fraction(x + y, 2) for x, y in zip(v[a], v[b])))
return mid[key]
for a, b, c in f:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
out += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
return v, out
def jitter(v, seed):
rng = random.Random(seed)
return [tuple(Fraction(x) + Fraction(rng.randint(-20, 20), 400) for x in p) for p in v]
def torus(r, c):
idx = lambda i, j: (i % r) * c + (j % c)
v = [(i, j, 0) for i in range(r) for j in range(c)]
f = []
for i in range(r):
for j in range(c):
f += [(idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)), (idx(i, j), idx(i + 1, j + 1), idx(i, j + 1))]
return v, f
def grid_disk(r, c):
idx = lambda i, j: i * (c + 1) + j
v = [(i, j, 0) for i in range(r + 1) for j in range(c + 1)]
f = []
for i in range(r):
for j in range(c):
f += [(idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)), (idx(i, j), idx(i + 1, j + 1), idx(i, j + 1))]
return v, f
def meshes():
octa2 = subdivide(*subdivide(OCTA_V, OCTA_F))
return [
("octahedron", OCTA_V, OCTA_F),
("octahedron subdivided twice", jitter(octa2[0], 1), octa2[1]),
("torus 5 x 6", jitter(torus(5, 6)[0], 2), torus(5, 6)[1]),
("grid disk 4 x 5", jitter(grid_disk(4, 5)[0], 3), grid_disk(4, 5)[1]),
("strip", STRIP_V, STRIP_F),
]
def is_manifold_surface(mesh):
faces = list(mesh.faces.values())
directed_edges(faces) # raises if a directed edge is used twice
assert len({frozenset(t) for t in faces}) == len(faces)
for v, star in mesh.star.items(): # each vertex has one fan: a cycle or one path
nxt = {}
for f in star:
t = mesh.faces[f]
k = t.index(v)
nxt[t[(k + 1) % 3]] = t[(k + 2) % 3]
assert len(nxt) == len(star)
starts = [a for a in nxt if a not in nxt.values()]
assert len(starts) <= 1
first = a = starts[0] if starts else next(iter(nxt))
steps = 0
while a in nxt and steps <= len(nxt):
a = nxt[a]
steps += 1
if a == first:
break
assert steps == len(nxt) # one walk visits every face at v
def test_every_legal_collapse_is_undone_exactly():
for name, v, f in meshes():
original = Mesh(v, f)
chi = euler_characteristic(f)
for a, b in edges(original):
for vs, vt in ((a, b), (b, a)):
mesh = original.copy()
if not link_condition(mesh, vs, vt):
with pytest.raises(ValueError):
ecol(mesh, vs, vt, (0, 0, 0))
assert mesh.state() == original.state()
continue
rec = ecol(mesh, vs, vt, (7, 7, 7))
assert vt not in mesh.pos and mesh.pos[vs] == (7, 7, 7)
is_manifold_surface(mesh)
assert euler_characteristic(list(mesh.faces.values())) == chi
vsplit(mesh, rec)
assert mesh.state() == original.state(), (name, vs, vt)
def test_whole_sequence_restores_the_input_and_every_level():
for name, v, f in meshes():
original = Mesh(v, f)
base, records = build(v, f, target=4)
# Replay the collapses to get the mesh at every level.
levels = [refine(base, records, k).state() for k in range(len(records) + 1)]
assert levels[-1] == original.state(), name
assert levels[0] == base.state()
for k in range(len(records)):
assert len(levels[k + 1][0]) == len(levels[k][0]) + 1
def test_link_condition_rejects_bad_collapses():
tet = Mesh(TET_V, TET_F)
for a, b in edges(tet):
assert not link_condition(tet, a, b) and not link_condition(tet, b, a)
strip = Mesh(STRIP_V, STRIP_F)
assert not link_condition(strip, 1, 4) # an inner edge between two boundary vertices: a pinch
assert link_condition(strip, 0, 1) # a boundary edge
assert not link_condition(strip, 0, 5) # not an edge
def test_simplification_keeps_the_topology():
for name, v, f in meshes():
chi = euler_characteristic(f)
base, records = build(v, f, target=4)
is_manifold_surface(base)
assert euler_characteristic(list(base.faces.values())) == chi
if name.startswith("octahedron"):
assert len(base.pos) == 4 and len(base.faces) == 4 # a sphere ends as a tetrahedron
def test_record_is_small_and_ids_are_fresh():
v, f = meshes()[1][1:]
base, records = build(v, f, target=4)
assert len(base.pos) + len(records) == len(v)
created = [r.vt for r in records]
assert len(set(created)) == len(created) and not set(created) & set(base.pos)
for r in records:
assert r.fl is not None and r.fr is not None # a closed mesh: two faces per split
def test_random_orders_round_trip():
for seed in range(4):
rng = random.Random(seed)
name, v, f = meshes()[seed % 4]
mesh = Mesh(v, f)
original = mesh.state()
stack = []
for _ in range(len(v)):
legal = [(a, b) for a, b in edges(mesh) if link_condition(mesh, a, b)]
if not legal:
break
a, b = rng.choice(legal)
if rng.random() < 0.5:
a, b = b, a
stack.append(ecol(mesh, a, b, mesh.pos[rng.choice((a, b))]))
while stack:
vsplit(mesh, stack.pop())
assert mesh.state() == original
History
Hugues Hoppe introduced progressive meshes at SIGGRAPH 1996, with the edge collapse as the only simplification step, the vertex split as its inverse, geomorphs between levels, and progressive transmission. He built the sequence by an energy that measured the distance to the original surface, from his earlier work on mesh optimization. In 1997 he extended it to view-dependent refinement. Michael Garland and Paul Heckbert's quadric error metrics of 1997 gave a fast cost for choosing the collapses. Dey, Edelsbrunner, Guha and Nekhayev stated the link condition in 1999 as the local test that an edge contraction keeps the topology of a manifold.
References
- Hugues Hoppe, Progressive meshes, Proceedings of SIGGRAPH 96, pages 99-108, 1996, the edge collapse and vertex split, the representation as a base mesh with a sequence of vertex splits, geomorphs, progressive transmission, and the construction by energy minimization
- Tamal K. Dey, Herbert Edelsbrunner, Sumanta Guha and Dmitry V. Nekhayev, Topology preserving edge contraction, Publications de l'Institut Mathématique (Beograd) (N.S.) 66(80), pages 23-45, 1999, the link condition for an edge contraction that keeps the topological type of a 2-manifold
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag WJ1E5T Edit this page History Report an error Markdown