Algorithm Search⌘K

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

A progressive mesh stores a triangle mesh MnM^n as a coarse base mesh M0M^0 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 M1,M2,…,MnM^1, M^2, \dots, M^n 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:

  • ECOL(M,vs,vt,p)\mathrm{ECOL}(M, v_s, v_t, p): collapse the edge vsvtv_s v_t into the vertex vsv_s at the position pp, and return the vertex split that undoes it. It fails if the collapse would make the mesh stop being a manifold.
  • VSPLIT(M,s)\mathrm{VSPLIT}(M, s): apply the vertex split ss, the inverse of the collapse that made it.
  • LINK(M,vs,vt)\mathrm{LINK}(M, v_s, v_t): whether the collapse of vsvtv_s v_t is legal.
  • BUILD(Mn,n0)\mathrm{BUILD}(M^n, n_0): collapse edges until n0n_0 vertices remain, and return the base mesh M0M^0 and the splits s0,s1,…s_0, s_1, \dots in the order of refinement.
  • REFINE(M0,k)\mathrm{REFINE}(M^0, k): the mesh MkM^k after the first kk splits.

The main law is VSPLIT(ECOL(M,vs,vt,p))=M\mathrm{VSPLIT}(\mathrm{ECOL}(M, v_s, v_t, p)) = M 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 fl=(vs,vt,vl)f_l = (v_s, v_t, v_l) be the face with the directed edge vs→vtv_s \to v_t and fr=(vt,vs,vr)f_r = (v_t, v_s, v_r) the face with vt→vsv_t \to v_s. On a boundary edge one of them is missing. A vertex split is a record

field meaning
vsv_s, vtv_t the vertex that stays and the vertex that comes back
vlv_l, vrv_r the third vertices of flf_l and frf_r, or none
psp_s, ptp_t the positions of vsv_s and vtv_t before the collapse
flf_l, frf_r the ids and the corners of the two removed faces

The record does not list the faces that go back from vsv_s to vtv_t. They are found from vlv_l and vrv_r alone: they are the faces around vsv_s counterclockwise from the edge to vrv_r up to the edge to vlv_l. 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 M0M^0 are numbered 00 to n0−1n_0 - 1, the split sis_i creates the vertex n0+in_0 + i, and the new faces are appended. Then vtv_t and the face ids need no storage, vsv_s needs about log⁡2n\log_2 n bits, and vlv_l and vrv_r can be named by their place among the neighbours of vsv_s.

Operations

  1. ECOL(M, v_s, v_t, p)
  2. 1f_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
  3. 2if v_l = v_r or not LINK(M, v_s, v_t) then fail
  4. 3s ← (v_s, v_t, v_l, v_r, p(v_s), p(v_t), f_l with its corners, f_r with its corners)
  5. 4remove f_l and f_r
  6. 5in every other face of v_t, replace v_t by v_s
  7. 6p(v_s) ← p; remove v_t
  8. 7return s
  9. VSPLIT(M, s)
  10. 8F ← the faces around v_s counterclockwise from the edge to v_r up to the edge to v_l
  11. 9in every face of F, replace v_s by v_t
  12. 10p(v_s) ← s.p_s; p(v_t) ← s.p_t
  13. 11put back f_l and f_r with their ids and corners
  14. LINK(M, v_s, v_t)
  15. 12close the boundary with one extra vertex ω; Lk(v) ← the vertices and edges opposite v
  16. 13return Lk(v_s) ∩ Lk(v_t) = Lk(v_s v_t) ▷ Lk of the edge: v_l, v_r, and ω on a boundary edge
  17. BUILD(M, n_0)
  18. 14while 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)
  19. 15return M as M^0, and the pushed records in reverse order

Line L8 in detail. Around vtv_t counterclockwise, flf_l turns from vlv_l to vsv_s and frf_r from vsv_s to vrv_r, so the other faces of vtv_t run from vrv_r to vlv_l. Around vsv_s, frf_r turns from vrv_r to vtv_t and flf_l from vtv_t to vlv_l, so the other faces of vsv_s run from vlv_l to vrv_r. After the collapse both runs are around vsv_s, and the run from vrv_r to vlv_l is exactly the old faces of vtv_t. When vtv_t is on the boundary, its run has a gap: the walk goes from vrv_r to the end of the fan of vsv_s, then from the start of the fan to vlv_l. When vrv_r is missing, the walk starts at the start of the fan, and when vlv_l 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 ω\omega, 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 ω\omega, 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 pp 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 0=(1,0,0)0 = (1, 0, 0), 1=(−1,0,0)1 = (-1, 0, 0), 2=(0,1,0)2 = (0, 1, 0), 3=(0,−1,0)3 = (0, -1, 0), 4=(0,0,1)4 = (0, 0, 1), 5=(0,0,−1)5 = (0, 0, -1), and the faces 0: (0,2,4)0{:}\,(0, 2, 4), 1: (2,1,4)1{:}\,(2, 1, 4), 2: (1,3,4)2{:}\,(1, 3, 4), 3: (3,0,4)3{:}\,(3, 0, 4), 4: (2,0,5)4{:}\,(2, 0, 5), 5: (1,2,5)5{:}\,(1, 2, 5), 6: (3,1,5)6{:}\,(3, 1, 5), 7: (0,3,5)7{:}\,(0, 3, 5). Collapse vt=4v_t = 4 into vs=0v_s = 0 at p=(12,0,12)p = (\tfrac12, 0, \tfrac12).

  • Line L1: face 3 is (3,0,4)(3, 0, 4), which contains 0→40 \to 4, so flf_l is face 3 and vl=3v_l = 3. Face 0 is (0,2,4)(0, 2, 4), which contains 4→04 \to 0, so frf_r is face 0 and vr=2v_r = 2.
  • Line L2: the neighbours of 0 are {2,3,4,5}\{2, 3, 4, 5\} and those of 4 are {0,1,2,3}\{0, 1, 2, 3\}. They share only {2,3}={vr,vl}\{2, 3\} = \{v_r, v_l\}, and the links share no edge, so the collapse is legal.
  • Lines L3 to L6: the record is (0,4,3,2,(1,0,0),(0,0,1),face 3=(3,0,4),face 0=(0,2,4))(0, 4, 3, 2, (1, 0, 0), (0, 0, 1), \text{face } 3 = (3, 0, 4), \text{face } 0 = (0, 2, 4)). Faces 1 and 2 become (2,1,0)(2, 1, 0) and (1,3,0)(1, 3, 0). The result has 5 vertices, 9 edges and 6 faces, so V−E+F=2V - E + F = 2 is unchanged.

Now the split. Around vertex 0 the faces turn 2→12 \to 1 (face 1), 1→31 \to 3 (face 2), 3→53 \to 5 (face 7) and 5→25 \to 2 (face 4). Line L8 walks from vr=2v_r = 2: face 1 to 1, face 2 to 3, and stops at vl=3v_l = 3. 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 VV, FF legal edges at the start base mesh M0M^0 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 5×65 \times 6 30, 60 90 of 90 7 vertices, 14 faces 23 0
grid disk 4×54 \times 5 30, 40 67 of 69 4 vertices, 2 faces 26 14

Every level MkM^k rebuilt by REFINE was equal to the mesh after the matching collapse, and MnM^n 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 vtv_t to vsv_s, and those faces are exactly the run of line L8 at the moment the split is applied.

The proof in proofs/correctness.md shows:

  1. A legal collapse keeps V−E+FV - E + F: 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.
  2. The run of line L8 is exactly the set of faces of vtv_t other than flf_l and frf_r, in all four cases (both faces present, vtv_t on the boundary, vlv_l missing, vrv_r missing).
  3. So VSPLIT(ECOL(M))=M\mathrm{VSPLIT}(\mathrm{ECOL}(M)) = M exactly, and by induction on the stack, applying the first kk splits to M0M^0 gives MkM^k, for every kk.

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. MM is an oriented manifold mesh of triangles with stable vertex and face ids, faces oriented by the right-hand rule. For a vertex vv let NvN_v be the map a↦ba \mapsto b over the faces (v,a,b)(v, a, b) of vv, written with vv first in their cyclic order. Being an oriented manifold mesh means: every directed edge is in at most one face, so NvN_v is a function and is one to one; no face repeats a vertex; and for each vv the arcs a→Nv(a)a \to N_v(a) 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 vsvtv_s v_t is legal if line L2 does not fail: the edge exists, vl≠vrv_l \ne v_r, and the link condition holds.

Claim.

  1. A legal collapse leaves no face with a repeated vertex and no two faces on the same three vertices, and it keeps V−E+FV - E + F.
  2. Let TT be the set of faces of vtv_t other than flf_l and frf_r before a legal collapse. After the collapse, the walk of line L8 visits exactly the faces of TT.
  3. VSPLIT applied right after the ECOL that returned the record restores the mesh exactly. Hence if s0,…,sm−1s_0, \dots, s_{m-1} are the records of BUILD in refinement order, applying s0,…,sk−1s_0, \dots, s_{k-1} to M0M^0 gives the mesh MkM^k that BUILD had after m−km - k collapses, for every kk.
  4. ECOL, VSPLIT and BUILD terminate.

Facts from the link condition. In a manifold mesh the vertices of the link of vv are the neighbours of vv, plus ω\omega when vv is on the boundary, and its edges are the pairs {a,Nv(a)}\{a, N_v(a)\}, plus {a,ω}\{a, \omega\} for each boundary edge vava. The link of the edge vsvtv_s v_t has the vertices vlv_l and vrv_r that exist, plus ω\omega if the edge is on the boundary, and no edges. So the link condition says:

  • (a) the common neighbours of vsv_s and vtv_t are exactly the vertices vlv_l, vrv_r that exist;
  • (b) no edge {x,y}\{x, y\} is in a face of vsv_s and in a face of vtv_t opposite to them, and no boundary edge vsxv_s x goes with a boundary edge vtxv_t x;
  • (c) if vsvtv_s v_t is an inner edge, vsv_s and vtv_t are not both on the boundary, since then ω\omega would be a common link vertex that is not in the link of the edge.

Proof of 1. A face that contains both vsv_s and vtv_t contains the edge vsvtv_s v_t in one direction, and each direction is in at most one face, so these faces are flf_l and frf_r, which line L4 removes. So the faces of TT do not contain vsv_s, and renaming vtv_t to vsv_s in them, in line L5, makes no face with a repeated vertex. Suppose a face (vs,x,y)(v_s, x, y) of TT after the renaming has the same vertex set as another face. That face is not in TT (two faces of TT with the same vertices would have been equal before), so it is an old face {vs,x,y}\{v_s, x, y\} of vsv_s. Then the edge {x,y}\{x, y\} is opposite vsv_s and opposite vtv_t, which (b) forbids.

Counting: one vertex goes away. An edge vtxv_t x with x≠vsx \ne v_s becomes vsxv_s x, and it merges with an old edge exactly when xx is a common neighbour, which by (a) is vlv_l or vrv_r. So the edges lost are vsvtv_s v_t and one per face among flf_l, frf_r, and the faces lost are flf_l and frf_r. Inside the surface the change of V−E+FV - E + F is −1+3−2=0-1 + 3 - 2 = 0, and on a boundary edge it is −1+2−1=0-1 + 2 - 1 = 0. □\square

Proof of 2. Write NtN_t and NsN_s for the maps before the collapse. Since fl=(vs,vt,vl)f_l = (v_s, v_t, v_l) and fr=(vt,vs,vr)f_r = (v_t, v_s, v_r), the map NtN_t has the arcs vl→vsv_l \to v_s (from flf_l) and vs→vrv_s \to v_r (from frf_r), and NsN_s has the arcs vr→vtv_r \to v_t and vt→vlv_t \to v_l. Let AtA_t be NtN_t without its arcs from flf_l and frf_r; its arcs are the faces of TT. Let AsA_s be NsN_s without the arcs from flf_l and frf_r. After the collapse the map N′N' of vsv_s has the arcs of AsA_s and of AtA_t, since the renamed faces of TT have vsv_s in the place of vtv_t and contain neither vsv_s nor vtv_t otherwise (proof of 1).

The keys of AsA_s and AtA_t are disjoint. A common key is a common neighbour, so it is vlv_l or vrv_r by (a). In NtN_t the key vlv_l belongs to the arc vl→vsv_l \to v_s, which is not in AtA_t, and NtN_t has one arc per key, so vlv_l is not a key of AtA_t. In NsN_s the key vrv_r belongs to vr→vtv_r \to v_t, so vrv_r is not a key of AsA_s. In the same way the values are disjoint. So N′N' is a function, and the walk of line L8 is well defined.

Case 1: both faces exist, vtv_t inner. NtN_t is the cycle ⋯→vl→vs→vr→…\dots \to v_l \to v_s \to v_r \to \dots, so AtA_t is a path from vrv_r to vlv_l. The walk starts at vrv_r, follows AtA_t, since vrv_r is a key of AtA_t only, and the path never meets vlv_l before its last vertex. It stops at vlv_l after the faces of AtA_t, which are TT.

Case 2: both faces exist, vtv_t on the boundary. By (c), vsv_s is inner, so AsA_s is a path from vlv_l to vrv_r. NtN_t is a path that contains vl→vs→vrv_l \to v_s \to v_r, so AtA_t is two paths, Q1Q_1 from vrv_r to the end of NtN_t and Q2Q_2 from the start of NtN_t to vlv_l, either of which may have no arcs. Then N′N' is the single path Q2Q_2, AsA_s, Q1Q_1. The walk goes from vrv_r along Q1Q_1 to the end of N′N', where the vertex is not a key, jumps to the start of N′N', which is the start of Q2Q_2 (or vlv_l if Q2Q_2 is empty), and follows Q2Q_2 to vlv_l. It visits Q1∪Q2=TQ_1 \cup Q_2 = T and nothing of AsA_s.

Case 3: frf_r is missing. Then vt→vsv_t \to v_s is a boundary edge, and both ends are on the boundary. The arc vl→vsv_l \to v_s is the last arc of the path NtN_t and vt→vlv_t \to v_l is the first arc of NsN_s, so AtA_t is a path from the start of NtN_t to vlv_l and AsA_s a path from vlv_l to the end of NsN_s. N′N' is the path AtA_t, AsA_s. It is not a cycle: the start of NtN_t and the end of NsN_s are neighbours of vtv_t and vsv_s; if they were equal, this vertex would be a common neighbour other than vlv_l, against (a), or both paths would be empty and the link edge {vl,ω}\{v_l, \omega\} would be common, against (b). The walk starts at the start of N′N' and stops at vlv_l, after exactly the arcs of AtA_t.

Case 4: flf_l is missing. This is case 3 with the directions reversed: AsA_s is a path from the start of NsN_s to vrv_r and AtA_t a path from vrv_r to the end of NtN_t. The walk starts at vrv_r and stops at the end of N′N', after exactly the arcs of AtA_t. □\square

Proof of 3. Line L3 stores the old positions and the ids and corner tuples of flf_l and frf_r. Lines L4 to L6 change only flf_l, frf_r, the faces of TT, the position of vsv_s and the vertex vtv_t. By claim 2, line L9 renames vsv_s to vtv_t in exactly the faces of TT, at the same place in each tuple where line L5 renamed vtv_t to vsv_s, and these tuples contained no vsv_s before, so they get back their old tuples. Line L10 restores both positions, and line L11 puts flf_l and frf_r 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 M=K0,K1,…,KmM = K_0, K_1, \dots, K_m by collapses c1,…,cmc_1, \dots, c_m, and returns M0=KmM^0 = K_m and sjs_j = the record of cm−jc_{m-j}. By induction on kk, applying s0,…,sk−1s_0, \dots, s_{k-1} to KmK_m gives Km−kK_{m-k}: for k=0k = 0 it is KmK_m, and if the first kk splits gave Km−kK_{m-k}, then sks_k is the record of cm−kc_{m-k}, which turned Km−k−1K_{m-k-1} into Km−kK_{m-k}, so sks_k applied right after it gives Km−k−1K_{m-k-1} by the first part. So Mk=Km−kM^k = K_{m-k}, and Mm=MM^m = M. □\square

Proof of 4. ECOL and LINK do a fixed amount of work for each face of vsv_s and vtv_t. Each step of the walk of line L8 visits a new arc of N′N' (the arcs form a cycle or a path and the walk stops at vlv_l or at the end, and jumps to the start at most once), so it takes at most as many steps as vsv_s has faces. Each round of BUILD either removes one vertex or stops, so it runs at most VV rounds. □\square

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 V−E+FV - E + F, and the stored splits rebuild every level and the input exactly. ■\blacksquare

Complexity

With a hash set for each star, ECOL and VSPLIT look only at the faces of vsv_s and vtv_t, and LINK builds two links of the same size, so each takes O(d)O(d) time, expected for the hash sets, where dd is the number of faces at vsv_s and vtv_t. REFINE to level kk costs the sum of these over the kk splits, which is O(k)O(k) for meshes of bounded degree. The structure uses Θ(n)\Theta(n) 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 O(n2d)O(n^2 d) in total. With a priority queue of edge costs that is updated after each collapse, as in quadric simplification, it takes O(ndlog⁡n)O(n d \log n) for bounded degree dd.

Variants

  • Geomorphs. Instead of jumping from MkM^k to Mk+1M^{k+1}, move vtv_t from psp_s to ptp_t 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 pp always equal to the old position of vsv_s, no new positions are needed, and vsv_s 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 O(d)O(d) 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 vsv_s to pp 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 vtv_t to vsv_s makes the record size depend on the degree. Deriving them from vlv_l and vrv_r 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.build_code
  • a full proof of time.build_heap
  • a full proof of time.ecol
  • a full proof of time.refine
  • a full proof of time.vsplit
  • 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