Algorithm Search⌘K

Algorithmadvanced

Edgebreaker

Also called Edgebreaker compression.

Rossignac's connectivity compression that visits the triangles of a mesh one by one and writes one of five symbols for each, using at most 2 bits per triangle on a closed genus 0 mesh.

Time
O(t^2) decodeO(t) expected encode
Space
Θ(t) extra
Where
t = the number of triangles
Properties
deterministicexactiterative
Origin
Jarek Rossignac, 1999

Edgebreaker compresses the connectivity of a triangle mesh: the list of which vertices form each triangle, without the coordinates. It visits the triangles one by one, each next to one already visited, and writes one of five symbols, C, L, E, R or S, for each. The symbol says where the third vertex of the new triangle lies: a new vertex, or a vertex on the border of the visited part. On a closed mesh with the topology of a sphere, the code with 1 bit for C and 3 bits for the other symbols takes exactly 2t−12t - 1 bits for tt triangles, and the decoder rebuilds the same mesh with its vertices renumbered. Jarek Rossignac published the method in 1999, and it is a standard method of mesh compression.

In plain words

Think of the surface as a ball covered with triangles. Paint one triangle. Then, again and again, paint a triangle next to the painted part, and write one letter that says what its far corner touches.

If the far corner was never painted, write C. If it is the painted corner just to the left or just to the right, write L or R. If the triangle fills the last gap of a hole, write E. If the corner is somewhere else on the edge of the paint, the unpainted part splits in two. Write S, finish one part, and come back for the other.

C is very common, so it gets a short word of one bit, and the other letters get three bits. A reader who gets only the letters can paint the same triangles in the same order, and so rebuild the whole mesh.

The problem

The input is a mesh MM given as an indexed face set: a list of tt triangles, each a triple of three different vertex ids, oriented by the right-hand rule so that every directed edge a→ba \to b is in exactly one triangle and its reverse b→ab \to a in exactly one other. So MM is closed, every edge has two triangles, and MM is oriented. We also need MM to be connected through its edges and to have χ=V−E+F=2−2g=2\chi = V - E + F = 2 - 2g = 2, that is, genus g=0g = 0. The proof shows that these conditions make MM a triangulated sphere. The goal is a short string from which a decoder can rebuild MM up to a renumbering of its vertices: the decoder must give the triangles of MM with each vertex vv replaced by φ(v)\varphi(v) for one bijection φ\varphi of the vertex ids onto 0,1,…,V−10, 1, \dots, V - 1. The vertex coordinates are sent separately, in the order of φ\varphi.

The algorithm

The encoder keeps the triangles it has visited. The rest of the surface, the part not yet visited, is a set of pieces, and each piece is bounded by a closed loop of vertices and edges. The loop runs along the visited triangles in their own direction. One edge of the current loop is the gate a→ba \to b. The triangle on the other side of the gate is (b,a,x)(b, a, x), and xx is its tip. The encoder looks up neighbours with a corner table. The five cases:

  • C: xx is new. The loop gets the vertex xx between aa and bb.
  • L: xx is the vertex just before aa on the loop, so the triangle to the left is visited. The vertex aa leaves the loop.
  • R: xx is the vertex just after bb, so the triangle to the right is visited. The vertex bb leaves the loop.
  • E: both; the loop was the triangle a,b,xa, b, x and it closes.
  • S: xx is elsewhere on the loop. The loop splits into a right loop x→b→⋯→xx \to b \to \dots \to x and a left loop a→x→⋯→aa \to x \to \dots \to a. The encoder finishes the right loop first and keeps the left one on a stack.
  1. ENCODE(M, f_0)
  2. 1mark f_0 and its vertices a, b, c; push the triangle across the edge a → b; for each triangle t = (b, a, x) taken from the stack or reached by "go on", with gate a → b, mark t and do:
  3. 2if x is not marked then write C; mark x; go on across x → b
  4. 3else if the triangles across a x and across x b are both marked then write E; take the next triangle from the stack
  5. 4else if the triangle across a x is marked then write L; go on across x → b
  6. 5else if the triangle across x b is marked then write R; go on across a → x
  7. 6else write S; push the triangle across a → x; go on across x → b
  8. DECODE(symbols)
  9. 7ℓ_i ← the length of the right loop of each S, from the counts of the symbols up to its E; faces ← (0, 1, 2); loop ← 0 → 1 → 2 → 0; gate ← 0 → 1; then for each symbol s_i, with the gate a → b:
  10. 8if s_i = C then x ← the next new vertex; insert x between a and b; gate ← x → b
  11. 9if s_i = L then x ← the vertex before a; remove a from the loop; gate ← x → b
  12. 10if s_i = R then x ← the vertex after b; remove b from the loop; gate ← a → x
  13. 11if s_i = E then x ← the vertex before a; the loop a → b → x closes; gate ← the gate taken from the stack (none at the end)
  14. 12if s_i = S then x ← the vertex ℓ_i − 1 steps after b; split the loop into x → b → … → x and a → x → … → a; gate ← x → b
  15. 13push the gate a → x
  16. 14append the face (b, a, x)
  17. 15return faces

The bits. The code is C = 0, S = 100, R = 101, L = 110, E = 111. It is a prefix code, so the bit string splits back into symbols without separators.

Line L7. The decoder must know where the tip of an S is. The encoder does not send it: the decoder finds it from the symbols that follow. Let a loop have ℓ\ell edges. Then C adds one edge, L and R remove one, S makes ℓ+1\ell + 1 edges in two loops, and E removes a loop of 3 edges. The right loop of the S at position ii is finished by the symbols from i+1i + 1 to the E at which, for the first time, the number of E symbols is one more than the number of S symbols. If these symbols have nCn_C C, nLn_L L, nRn_R R and nSn_S S, then ℓi=3+2nS−nC+nL+nR\ell_i = 3 + 2 n_S - n_C + n_L + n_R. The code finds all the ends in one pass with a stack.

Degenerate cases. The encoder rejects a face that repeats a vertex, a directed edge used twice, a boundary edge, V−E+F≠2V - E + F \ne 2, and a mesh that is not connected. The smallest valid input is the pillow: two triangles (0,1,2)(0, 1, 2) and (0,2,1)(0, 2, 1) on the same three vertices, coded as the single symbol E.

Example

Take the octahedron with the faces (0,2,4)(0, 2, 4), (2,1,4)(2, 1, 4), (1,3,4)(1, 3, 4), (3,0,4)(3, 0, 4), (2,0,5)(2, 0, 5), (1,2,5)(1, 2, 5), (3,1,5)(3, 1, 5), (0,3,5)(0, 3, 5), so t=8t = 8 and V=6V = 6. Start at f0=(0,2,4)f_0 = (0, 2, 4). The encoder writes CCRCRRE and meets the vertices in the order 0,2,4,5,1,30, 2, 4, 5, 1, 3, so φ\varphi maps them to 0,1,2,3,4,50, 1, 2, 3, 4, 5. The decoder sees only the symbols:

step symbol gate a→ba \to b tip xx face (b,a,x)(b, a, x) loop after
L7 (0,1,2)(0, 1, 2) 0→1→20 \to 1 \to 2
1 C 0→10 \to 1 new 3 (1,0,3)(1, 0, 3) 0→3→1→20 \to 3 \to 1 \to 2
2 C 3→13 \to 1 new 4 (1,3,4)(1, 3, 4) 0→3→4→1→20 \to 3 \to 4 \to 1 \to 2
3 R 4→14 \to 1 2, after 1 (1,4,2)(1, 4, 2) 0→3→4→20 \to 3 \to 4 \to 2
4 C 4→24 \to 2 new 5 (2,4,5)(2, 4, 5) 0→3→4→5→20 \to 3 \to 4 \to 5 \to 2
5 R 5→25 \to 2 0, after 2 (2,5,0)(2, 5, 0) 0→3→4→50 \to 3 \to 4 \to 5
6 R 5→05 \to 0 3, after 0 (0,5,3)(0, 5, 3) 3→4→53 \to 4 \to 5
7 E 5→35 \to 3 4, before 5 (3,5,4)(3, 5, 4) closed

The eight faces are the input faces in the encoder's order, with each vertex renamed by φ\varphi: for example (0,2,4)(0, 2, 4) becomes (0,1,2)(0, 1, 2) and (2,0,5)(2, 0, 5) becomes (1,0,3)(1, 0, 3). The bit string is 0 0 101 0 101 101 111, which is 15=2⋅8−115 = 2 \cdot 8 - 1 bits. Every one of the 8 start faces gives the same string CCRCRRE.

An S needs a less regular mesh. The tests make random edge flips on an octahedron, an icosahedron and a subdivided octahedron, and these meshes use all five symbols. On the icosahedron split twice into four and then changed by 200 random flips (seed 0, start face 0), the encoder writes 25 S symbols, and the longest right loop that line L7 finds has 28 edges.

Correctness

The proof in proofs/correctness.md shows four facts for every valid input.

  1. A valid input is a triangulated sphere. If the mesh is closed, oriented, connected through its edges and has V−E+F=2V - E + F = 2, then no vertex is pinched and the genus is 0.
  2. Key invariant. Before each step, every unvisited piece is a closed disk bounded by its loop, the loops are simple, and the triangles outside each disk next to its loop are visited. So the five cases are exactly the five places where the tip can be, and the encoder never reaches a visited triangle again.
  3. The rule of line L7 gives the length of each right loop. With it, after each symbol the decoder has the same loops, gates and stack as the encoder, with each vertex renamed by φ\varphi. So decoding inverts encoding: DECODE(ENCODE(MM)) is MM renamed by φ\varphi, face by face in the encoder's order.
  4. Bit bound. There are exactly V−3V - 3 C symbols and t−1t - 1 symbols in all, and t=2V−4t = 2V - 4. So the code has exactly (V−3)+3(t−1−(V−3))=2t−1(V - 3) + 3(t - 1 - (V - 3)) = 2t - 1 bits.

Fact 1 and the disk facts in fact 2 use the Jordan and Schoenflies theorems, which the proof cites. The rest is proved.

Proof: Edgebreaker decoding inverts encoding on every triangulated sphere, and the code takes exactly 2t - 1 bitsfull

Setting. MM is a list of tt triangles, each a triple of three different vertex ids, such that every directed edge a→ba \to b is in exactly one triangle and b→ab \to a in exactly one other, the triangles are connected through shared edges, and V−E+F=2V - E + F = 2. An edge is a pair of vertices, so each edge has exactly two triangles. ENCODE and DECODE are lines L1 to L15 of the page. For a triangle t=(b,a,x)t = (b, a, x) reached across the gate a→ba \to b, the left triangle is the other triangle of the edge {a,x}\{a, x\} and the right triangle is the other triangle of the edge {x,b}\{x, b\}. A vertex is marked once line L1 or L2 marks it; every marked vertex is a vertex of a visited triangle.

Claim.

  1. MM is a triangulated sphere: the triangles at each vertex form one cycle around it, and MM is a closed orientable surface of genus 0.
  2. ENCODE terminates, visits every triangle exactly once, and before each step the invariant below holds.
  3. Let φ\varphi number the vertices 0,1,2,…0, 1, 2, \dots in the order in which the encoder marks them. Then DECODE(ENCODE(MM)) is the list of the triangles of MM in the order of their visit, with each vertex vv replaced by φ(v)\varphi(v).
  4. The symbol string has exactly t−1t - 1 symbols, of which V−3V - 3 are C, and nE=nS+1n_E = n_S + 1. The code C = 0, S = 100, R = 101, L = 110, E = 111 has exactly 2t−12t - 1 bits.

Facts cited. (F1) Every closed connected orientable surface has χ=2−2g\chi = 2 - 2g for its genus g≥0g \ge 0, and g=0g = 0 means a sphere (the classification of surfaces). (F2) The closure of the complement of an open disk bounded by a polygonal simple closed curve on the sphere is a closed disk (the Schoenflies theorem). (F3) If DD is a closed disk made of triangles and γ\gamma is a path of edges from a point of ∂D\partial D to another point of ∂D\partial D whose edges and inner vertices are not on ∂D\partial D, then γ\gamma cuts DD into two closed disks; the boundary of each is γ\gamma followed by one of the two arcs of ∂D\partial D between the ends of γ\gamma, and every triangle of DD is in exactly one of them (the theta-curve theorem, a form of the Jordan curve theorem). A closed disk made of triangles is connected through edges, and a disk whose boundary is the boundary of one of its triangles is that triangle.

Proof of 1. At a vertex vv, join two triangles of vv when they share an edge at vv. Each edge vxvx has exactly two triangles, so this graph has degree 2 everywhere and is a union of kv≥1k_v \ge 1 cycles, the fans of vv. Replace each vertex vv by kvk_v copies, one for each fan. The result M^\hat M is a closed surface: every vertex now has one fan, so it has a disk around it. M^\hat M is connected through edges as MM is, and it is oriented by the same triangles. It has the same edges and triangles and ∑v(kv−1)\sum_v (k_v - 1) more vertices, so χ(M^)=2+∑v(kv−1)\chi(\hat M) = 2 + \sum_v (k_v - 1). By (F1) χ(M^)≤2\chi(\hat M) \le 2, so every kv=1k_v = 1, M^=M\hat M = M and g=0g = 0. □\square

The invariant. The code does not store loops; they are defined here for the proof. A piece is a set DD of unvisited triangles with a loop PP, a cyclic sequence of vertices, such that:

  • (I1) the union of the triangles of DD is a closed disk whose boundary is the closed path PP, and PP passes each vertex at most once;
  • (I2) an edge of a triangle of DD is an edge of PP exactly when its other triangle is not in DD, and then that other triangle is visited and contains the edge in the direction of PP;
  • (I3) the gate of the piece is an edge a→ba \to b of PP, and the triangle across it, which contains b→ab \to a, is in DD.

Before each step, the unvisited triangles are split into the pieces of the current gate and of the gates on the stack, one piece for each, with no triangle in two pieces. (For the code, "the stack" holds the triangle across each stored gate; the current gate is the one across which the next triangle is reached.)

Lemma A. In a piece DD with loop PP: a vertex on PP is marked, and a vertex of a triangle of DD that is not on PP is not marked.

Proof. A vertex on PP is on an edge of PP, which is in a visited triangle by (I2); the vertices of a visited triangle are marked (line L1 marks those of f0f_0, and a later triangle is visited across a gate whose two ends are on a loop, so marked, while its tip is marked at line L2 or was marked before). Now let yy be a vertex of a triangle of DD that is not on PP. No edge at yy is an edge of PP, so by (I2) every edge at yy that has one triangle in DD has both in DD. Going around the single fan of yy (claim 1), all triangles of yy are in DD, so none is visited and yy is not marked. □\square

Lemma B. For the triangle t=(b,a,x)t = (b, a, x) across the gate a→ba \to b of a piece DD with loop PP: the left triangle is visited exactly when xx is the vertex just before aa on PP, and the right triangle is visited exactly when xx is the vertex just after bb.

Proof. If the left triangle is visited, it is not in DD, so by (I2) the edge {a,x}\{a, x\} is an edge of PP in the direction it has in the left triangle. That triangle has x→ax \to a, because tt has a→xa \to x. So x→ax \to a is an edge of PP and xx comes just before aa. Conversely, if x→ax \to a is an edge of PP, then by (I2) the other triangle of {a,x}\{a, x\}, which is the left triangle, is visited. The right side is the same with x→bx \to b replaced by b→xb \to x. □\square

Proof of 2. Start. By claim 1 and (F2), the triangles other than f0=(a,b,c)f_0 = (a, b, c) form a closed disk with boundary a→b→c→aa \to b \to c \to a, the directions of f0f_0. With the gate a→ba \to b this is one piece: (I1) holds, the other triangle of each edge of f0f_0 is not f0f_0 and so is in DD, and (I3) holds because the triangle across a→ba \to b contains b→ab \to a.

Step. Let DD be the current piece with loop PP, gate a→ba \to b and tip triangle t=(b,a,x)∈Dt = (b, a, x) \in D (I3), so tt is not visited and the check of the code never fires. The encoder marks tt. Write P=a→b→p1→⋯→pm→aP = a \to b \to p_1 \to \dots \to p_m \to a. There are five cases, and they are the five branches of lines L2 to L6.

  • x not marked (C). By Lemma A, xx is not on PP, so the edges {a,x}\{a, x\} and {x,b}\{x, b\} are not on PP and the path a,x,ba, x, b satisfies (F3). It cuts DD into tt (the side bounded by a→b→x→aa \to b \to x \to a) and D′=D∖{t}D' = D \setminus \{t\} with loop a→x→b→p1→⋯→aa \to x \to b \to p_1 \to \dots \to a. The other triangle of {x,b}\{x, b\} is in DD by (I2), so in D′D', and the new gate x→bx \to b satisfies (I3). (I2) holds on the two new loop edges, because tt is visited and has a→xa \to x, x→bx \to b.
  • x marked, left and right visited (E). By Lemma B, xx is just before aa and just after bb, so P=a→b→x→aP = a \to b \to x \to a and every edge of tt is on PP. DD is connected through edges, and by (I2) no triangle of DD shares an edge with tt, so D={t}D = \{t\}, and the piece is finished.
  • x marked, only the left visited (L). By Lemma B, x=pmx = p_m and xx is not just after bb, so {x,b}\{x, b\} is not on PP. The single edge x,bx, b satisfies (F3) and cuts DD into tt and D′D' with loop x→b→p1→⋯→pmx \to b \to p_1 \to \dots \to p_m; the vertex aa leaves the loop. The gate x→bx \to b satisfies (I3) as in case C.
  • x marked, only the right visited (R). Symmetric: x=p1x = p_1, the edge a,xa, x cuts off tt, bb leaves the loop, and the new gate is a→xa \to x.
  • x marked, neither visited (S). By Lemma A, xx is on PP, so x=prx = p_r for some 1≤r≤m1 \le r \le m, and by Lemma B, x≠p1x \ne p_1 and x≠pmx \ne p_m. Neither {a,x}\{a, x\} nor {x,b}\{x, b\} is on PP, by (I2). By (F3) the edge a,xa, x cuts DD into DLD_L with loop a→x→pr+1→⋯→pm→aa \to x \to p_{r+1} \to \dots \to p_m \to a and a disk with loop a→b→p1→⋯→x→aa \to b \to p_1 \to \dots \to x \to a, and the edge x,bx, b cuts that disk into tt and DRD_R with loop x→b→p1→⋯→pr−1→xx \to b \to p_1 \to \dots \to p_{r-1} \to x. Each loop passes each vertex once, since PP does. The other triangles of {a,x}\{a, x\} and {x,b}\{x, b\} are in DLD_L and DRD_R, so the gates a→xa \to x (pushed) and x→bx \to b (current) satisfy (I3).

In all cases the other pieces are not changed, so the invariant holds again. Each step visits one triangle that was not visited, so ENCODE stops after at most t−1t - 1 steps. It stops only after an E with an empty stack, when there are no pieces left; then every triangle is visited, and the check "not connected" does not fire. □\square

Proof of 3. The lengths of line L7. Consider the S at position ii, with right piece DRD_R and loop RR of ℓi\ell_i edges. The stack is last in, first out, so the steps i+1,…,ji + 1, \dots, j that follow visit exactly the triangles of DRD_R and of the pieces cut from it, and step jj is the E that finishes the last of them. Count the pieces cut from DRD_R that are not finished: 1 at the start, plus 1 for each S and minus 1 for each E, so jj is the first position after ii where the E symbols are one more than the S symbols. Count also the edges on their loops: from the proof of 2, a C adds 1, an L or R removes 1, an S turns a loop of ℓ\ell edges into loops with ℓ+1\ell + 1 edges in all, and an E removes a loop of 3 edges. The count goes from ℓi\ell_i to 0, so ℓi+nC−nL−nR+nS−3nE=0\ell_i + n_C - n_L - n_R + n_S - 3 n_E = 0 with nE=nS+1n_E = n_S + 1, that is ℓi=3+2nS−nC+nL+nR\ell_i = 3 + 2 n_S - n_C + n_L + n_R, the rule of line L7. The code finds each jj in one pass: with dd the number of E minus the number of S so far, the S at ii sets dd to some value did_i and waits for d=di+1d = d_i + 1; an S nested inside waits for a smaller value, so the waiting S with the smallest target is always on top of the stack.

Lock step. We show by induction on the number of symbols read that the decoder's loops, current gate, stacked gates and faces are those of the encoder renamed by φ\varphi, and that the next new vertex number is the number of marked vertices. At the start both have the loop φ(a)→φ(b)→φ(c)=0→1→2\varphi(a) \to \varphi(b) \to \varphi(c) = 0 \to 1 \to 2, the gate 0→10 \to 1 and the face (0,1,2)(0, 1, 2). In a step, the decoder reads the symbol the encoder wrote for the triangle t=(b,a,x)t = (b, a, x) across the same gate, and it computes the same new loops as the proof of 2: for C a new vertex, which is φ(x)\varphi(x) since xx is the next vertex marked; for L the vertex before aa; for R the vertex after bb; for E the remaining vertex. For S, the right loop is x→b→p1→⋯→pr−1→xx \to b \to p_1 \to \dots \to p_{r-1} \to x with ℓi=r+1\ell_i = r + 1 edges, so x=prx = p_r is ℓi−1\ell_i - 1 steps after bb on PP, which line L12 finds, and since PP passes each vertex once the vertex is unique. In each case line L14 appends (φ(b),φ(a),φ(x))=φ(t)(\varphi(b), \varphi(a), \varphi(x)) = \varphi(t). Both pop gates in the same order, so the decoder stops after the last symbol, with every triangle of MM renamed by φ\varphi, in the order of the visit. □\square

Proof of 4. One symbol is written for each triangle other than f0f_0, so there are t−1t - 1. Each C marks one vertex, the other symbols mark none, and by claim 2 every vertex is in a visited triangle, so it is marked; f0f_0 marks 3, so nC=V−3n_C = V - 3. The number of pieces goes from 1 to 0, up by 1 at each S and down by 1 at each E, so nE=nS+1n_E = n_S + 1. Each triangle has 3 edges and each edge 2 triangles, so 3t=2E3t = 2E, and V−E+t=2V - E + t = 2 gives t=2V−4t = 2V - 4. The code has nC+3(t−1−nC)=3t−3−2(V−3)=3t+3−(t+4)=2t−1n_C + 3(t - 1 - n_C) = 3t - 3 - 2(V - 3) = 3t + 3 - (t + 4) = 2t - 1 bits. It is a prefix code, so the bit string splits back into the same symbols. □\square

Claims 1 to 4 give what the page states: on every closed, oriented, edge-connected triangle mesh with V−E+F=2V - E + F = 2, ENCODE stops, DECODE(ENCODE(MM)) equals MM up to the renumbering φ\varphi of the vertices, and the code has exactly 2t−1<2t2t - 1 < 2t bits. ■\blacksquare

Complexity

The encoder builds the corner table with a hash table on the directed edges in O(t)O(t) expected time and then does a constant amount of work for each triangle, so it takes O(t)O(t) expected time. The decoder of this page does a constant amount of work for each symbol, plus the walk of line L12, which takes ℓi−1\ell_i - 1 steps for each S. A loop with ℓ\ell edges bounds a disk of at least ℓ−2\ell - 2 triangles, so a right loop has at most t+2t + 2 edges, and the walks take O(t)O(t) each and O(t2)O(t^2) in all. This is the bound we prove; we did not build a mesh that reaches it. Both use Θ(t)\Theta(t) space.

Measured on the code of this page (one run each, start face 0; icokk is the icosahedron split kk times into four, and the last mesh is ico2 after 200 random edge flips with seed 0):

mesh tt C L R S E bits per triangle entropy per triangle
icosahedron 20 9 0 9 0 1 1.950 1.183
ico1 80 39 1 36 1 2 1.988 1.297
ico2 320 159 1 156 1 2 1.997 1.100
ico3 1280 639 1 636 1 2 1.999 1.031
ico4 5120 2559 1 2556 1 2 2.000 1.009
ico2, flipped 320 159 17 92 25 26 1.997 1.820

The bits per triangle are (2t−1)/t(2t - 1)/t, as proved. The last column is the order-0 Shannon entropy of the symbol string divided by tt, which is about what an ideal arithmetic coder with fixed symbol frequencies would need, not counting the frequencies themselves. On the regular subdivided meshes the string is almost only C and R in turn, the traversal goes round in a spiral, and the entropy falls to about 1 bit per triangle. After random flips it is 1.82.

Properties

  • Proved. Decoding inverts encoding for every closed connected oriented triangle mesh with V−E+F=2V - E + F = 2, from every start face.
  • Proved. The code takes exactly 2t−12t - 1 bits, so at most 2 bits per triangle, and exactly V−3V - 3 symbols are C.
  • Proved. The numbers of S and E symbols satisfy nE=nS+1n_E = n_S + 1.
  • Measured. The tests check DECODE(ENCODE(MM)) =φ(M)= \varphi(M) from every start face of 17 meshes with up to 80 triangles (the pillow, the tetrahedron, octahedron and icosahedron, their subdivisions, 4 bipyramids, and 6 meshes made by random edge flips with seed 7), and from random starts after random renumbering (seed 11).
  • Proved. Each triangle except the first is reached across its gate from a triangle visited before it, so the gates form a spanning tree of the triangles, in which two triangles are joined when they share an edge.
  • Lossless. The connectivity comes back exactly; only the vertex numbering changes, and φ\varphi is the order in which the coordinates are sent.
  • Connectivity only. The method says nothing about the coordinates. No geometric predicate is used.

Variants and improvements

  • Entropy coding. The symbols are far from equally likely, so a Huffman code of symbol pairs or an arithmetic code does better than the fixed 1 and 3 bit code. Rossignac reports less than 1.5 bits per triangle in this way on large meshes. This is measured on his meshes, not a bound.
  • A better worst case. King and Rossignac (1999) gave a code with at most 3.673.67 bits per vertex, about 1.831.83 bits per triangle. By Tutte's count of planar triangulations, about log⁡2(256/27)≈3.245\log_2 (256/27) \approx 3.245 bits per vertex are needed in the worst case.
  • Linear time decoders. The Wrap and Zip decoder of Rossignac and Szymczak (1999) puts the S tips in place afterwards by zipping the loops, and the Spirale Reversi decoder of Isenburg and Snoeyink (2000) reads the symbols backwards; both take O(t)O(t) time.
  • Edgebreaker on a corner table. Rossignac, Safonova and Szymczak (2001) wrote both coders in a few lines on the arrays of a corner table.
  • Holes and handles. Rossignac's paper also handles meshes with boundaries and meshes of higher genus, with extra bits for each hole and each handle: at a handle an S can hit a loop that is still on the stack and needs extra information. Another way to treat a hole, used by Touma and Gotsman, is to fill it with one extra vertex. The code of this page rejects these meshes.
  • Valence coding. Touma and Gotsman (1998) code the degree of each vertex instead of one symbol per triangle; on regular meshes this takes much less than 1 bit per triangle.
  • Progressive coding. A progressive mesh sends a coarse mesh first and then vertex splits, which Edgebreaker cannot do: its order is fixed by the traversal.

When to use it

Use Edgebreaker to store or send the connectivity of a large triangle mesh in about 2 bits per triangle, or less with entropy coding, instead of the 3log⁡2V3 \log_2 V bits per triangle of an indexed face set. It needs a manifold mesh; a mesh with non-manifold edges or vertices must be cut into manifold pieces first. The whole string must arrive before the mesh can be used. For streaming at several levels of detail, use a progressive mesh. For a guarantee below 2 bits per triangle, use a coder with a better worst case.

Pitfalls

  • The wrong side first. After an S the encoder must finish the right loop before the left one, and the decoder must assume the same. If the order or the side of "go on" in lines L2, L4 and L5 differs between the two, the lengths of line L7 are wrong and the decoder silently builds a different mesh.
  • Orientation. The cases L and R are told apart by the orientation of the triangles. An input that is not oriented by one rule, for example with one face reversed, makes a directed edge appear twice; the encoder must reject it, and it can be fixed by consistent mesh orientation.
  • Duplicate vertices. A mesh whose shared vertices were stored twice, once per triangle, has boundaries everywhere and is rejected. Run vertex welding first.
  • Testing only the Euler characteristic. V−E+F=2V - E + F = 2 alone is not enough. Two octahedra glued at two vertices also have V−E+F=2V - E + F = 2, but they are not connected through edges, and the encoder must reject them. The tests include this case.
  • Visiting a triangle twice. On a valid input the encoder never reaches a visited triangle; on a bad input it can, and without a check it may loop. The code of this page raises an error there.
  • Comparing with the input numbering. The decoder numbers the vertices 0,1,2,…0, 1, 2, \dots in the order of first visit. A test must rename the input by φ\varphi before it compares faces.

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.

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

"""Edgebreaker connectivity compression for closed triangle meshes of genus 0 (after Rossignac 1999).

A mesh is a list of faces, each a tuple of three vertex ids, oriented by the
right-hand rule. The encoder walks the triangles from a first triangle and
writes one symbol for each other triangle:

    C  the tip vertex is new;
    L  the tip is the vertex just before the gate on the boundary loop;
    R  the tip is the vertex just after the gate;
    E  both: the triangle closes the loop;
    S  the tip is elsewhere on the loop, which splits in two.

The decoder rebuilds the faces, with the vertices numbered in the order in
which the encoder met them. The code C = 0, S = 100, R = 101, L = 110,
E = 111 gives exactly 2T - 1 bits for T triangles on a closed genus 0 mesh.
"""

CODE = {"C": "0", "S": "100", "R": "101", "L": "110", "E": "111"}
DECODE = {v: k for k, v in CODE.items()}


def nxt(c):
    return c - c % 3 + (c + 1) % 3


def prv(c):
    return c - c % 3 + (c + 2) % 3


def corner_table(faces):
    """The corner table: V[c] is the vertex of corner c, O[c] the opposite corner (or -1)."""
    v = [x for tri in faces for x in tri]
    facing = {}
    for c in range(len(v)):
        e = (v[nxt(c)], v[prv(c)])
        if e in facing:
            raise ValueError("directed edge %r used twice" % (e,))
        facing[e] = c
    o = [facing.get((v[prv(c)], v[nxt(c)]), -1) for c in range(len(v))]
    return v, o


def encode(faces, start=0):
    """(symbols, vertex order, triangle order) for a closed connected genus 0 mesh, starting at face start."""
    if any(len(set(tri)) != 3 for tri in faces):
        raise ValueError("a face repeats a vertex")
    v, o = corner_table(faces)
    t = len(faces)
    if -1 in o:
        raise ValueError("the mesh has a boundary")
    nverts = len({x for tri in faces for x in tri})
    if nverts - 3 * t // 2 + t != 2:
        raise ValueError("V - E + F is not 2: the mesh is not a sphere")
    seen_v, seen_t = set(), [False] * t
    c0 = 3 * start
    order = [v[c0], v[c0 + 1], v[c0 + 2]]  # @line L1
    seen_v.update(order)
    seen_t[start] = True
    tri_order = [start]
    symbols = []
    stack = [o[c0 + 2]]  # the triangle across the edge from v[c0] to v[c0 + 1]
    while stack:
        c = stack.pop()
        while True:
            # c is the corner at the tip x of the new triangle (b, a, x); the gate is a -> b.
            if seen_t[c // 3]:
                raise ValueError("the mesh is not a manifold sphere")  # never on a valid input
            seen_t[c // 3] = True
            tri_order.append(c // 3)
            left = seen_t[o[nxt(c)] // 3]  # the triangle across the edge a x
            right = seen_t[o[prv(c)] // 3]  # the triangle across the edge x b
            if v[c] not in seen_v:  # @line L2
                symbols.append("C")
                seen_v.add(v[c])
                order.append(v[c])
                c = o[prv(c)]
            elif left and right:  # @line L3
                symbols.append("E")
                break
            elif left:  # @line L4
                symbols.append("L")
                c = o[prv(c)]
            elif right:  # @line L5
                symbols.append("R")
                c = o[nxt(c)]
            else:  # @line L6
                symbols.append("S")
                stack.append(o[nxt(c)])
                c = o[prv(c)]
    if not all(seen_t):
        raise ValueError("the mesh is not connected")
    return "".join(symbols), order, tri_order


def right_loop_lengths(symbols):
    """For each S at position i, the length of the loop of its right branch (symbols i+1 to its E)."""
    count = {s: [0] for s in "CLRSE"}
    for s in symbols:
        for k in count:
            count[k].append(count[k][-1] + (s == k))
    # Let D(j) = #E - #S in symbols[0..j]. The right branch of the S at i ends at the
    # first E at j > i with D(j) = D(i) + 1. Nested S symbols have smaller targets, so
    # the open S with the smallest target is on top of the stack.
    out = {}
    stack = []  # (target, i) for each S whose right branch is open
    d = 0
    for j, s in enumerate(symbols):
        if s == "S":
            d -= 1
            stack.append((d + 1, j))
        elif s == "E":
            d += 1
            if stack and stack[-1][0] == d:
                i = stack.pop()[1]
                n = {k: count[k][j + 1] - count[k][i + 1] for k in count}
                out[i] = 3 + 2 * n["S"] - n["C"] + n["L"] + n["R"]
    if d != 1 or stack:
        raise ValueError("the numbers of S and E symbols do not match")
    return out


def decode(symbols):
    """The faces, with vertex ids 0, 1, 2, ... in the order of the encoder, in the encoder's triangle order."""
    lengths = right_loop_lengths(symbols)  # @line L7
    faces = [(0, 1, 2)]
    vert = [0, 1, 2]  # loop nodes: their vertex, next and previous node
    nx = [1, 2, 0]
    pv = [2, 0, 1]
    nverts = 3
    gate = 0  # the gate is the loop edge from node gate to node nx[gate]
    stack = []
    for i, s in enumerate(symbols):
        if gate is None:
            raise ValueError("symbols after the last loop was closed")
        g, h = gate, nx[gate]
        a, b = vert[g], vert[h]
        if s == "C":  # @line L8
            x = nverts
            nverts += 1
            vert.append(x)
            nx.append(h)
            pv.append(g)
            nx[g] = pv[h] = len(vert) - 1
            gate = len(vert) - 1
        elif s == "L":  # @line L9
            p = pv[g]
            x = vert[p]
            nx[p], pv[h] = h, p
            gate = p
        elif s == "R":  # @line L10
            q = nx[h]
            x = vert[q]
            nx[g], pv[q] = q, g
        elif s == "E":  # @line L11
            x = vert[pv[g]]
            if nx[h] != pv[g]:
                raise ValueError("E on a loop that is not a triangle")
            gate = stack.pop() if stack else None
        elif s == "S":  # @line L12
            k = h
            for _ in range(lengths[i] - 1):
                k = nx[k]
            x = vert[k]
            # Right loop: a new node for x, then h ... pv[k]. Left loop: g, k, ...
            vert.append(x)
            nx.append(h)
            pv.append(pv[k])
            nx[pv[k]] = len(vert) - 1
            pv[h] = len(vert) - 1
            nx[g], pv[k] = k, g
            stack.append(g)  # @line L13
            gate = len(vert) - 1
        else:
            raise ValueError("unknown symbol %r" % (s,))
        faces.append((b, a, x))  # @line L14
    if gate is not None:
        raise ValueError("the symbols end before every loop is closed")
    return faces  # @line L15


def to_bits(symbols):
    return "".join(CODE[s] for s in symbols)


def from_bits(bits):
    out, word = [], ""
    for ch in bits:
        word += ch
        if word in DECODE:
            out.append(DECODE[word])
            word = ""
    if word:
        raise ValueError("trailing bits")
    return "".join(out)
test_edgebreaker.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/edgebreaker/. The authors are listed in prov/5F4MY3.jsonl.

import random

import pytest

from edgebreaker import decode, encode, from_bits, right_loop_lengths, to_bits

TET = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (2, 0, 3)]
OCTA = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
ICO = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4),
       (11, 10, 2), (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8),
       (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)]


def bipyramid(n):
    """n side vertices 0..n-1, apex n and n+1."""
    faces = []
    for i in range(n):
        j = (i + 1) % n
        faces.append((i, j, n))
        faces.append((j, i, n + 1))
    return faces


def subdivide(faces):
    """Split each triangle into four."""
    nv = 1 + max(x for t in faces for x in t)
    mid = {}

    def m(a, b):
        nonlocal nv
        key = (min(a, b), max(a, b))
        if key not in mid:
            mid[key] = nv
            nv += 1
        return mid[key]

    out = []
    for a, b, c in faces:
        ab, bc, ca = m(a, b), m(b, c), m(c, a)
        out += [(a, ab, ca), (ab, b, bc), (ca, bc, c), (ab, bc, ca)]
    return out


def random_flips(faces, k, rng):
    """k random edge flips that keep the mesh simplicial (no double edge, every degree at least 3)."""
    faces = [list(t) for t in faces]
    done = 0
    for _ in range(50 * k):
        if done == k:
            break
        where = {}
        nbr = {}
        for f, t in enumerate(faces):
            for i in range(3):
                where[(t[i], t[(i + 1) % 3])] = (f, t[(i + 2) % 3])
                nbr.setdefault(t[i], set()).add(t[(i + 1) % 3])
        a, b = rng.choice(sorted(where))
        f, c = where[(a, b)]
        g, d = where[(b, a)]
        if d in nbr[c] or len(nbr[a]) <= 3 or len(nbr[b]) <= 3:
            continue
        faces[f] = [c, a, d]
        faces[g] = [d, b, c]
        done += 1
    return [tuple(t) for t in faces]


def canon(t):
    k = t.index(min(t))
    return t[k:] + t[:k]


def relabel(faces, rng):
    """The same mesh with random vertex ids, a random face order and random rotations of each face."""
    ids = sorted({x for t in faces for x in t})
    new = list(range(100, 100 + len(ids)))
    rng.shuffle(new)
    lab = dict(zip(ids, new))
    out = []
    for t in faces:
        r = rng.randrange(3)
        t = tuple(lab[x] for x in t)
        out.append(t[r:] + t[:r])
    rng.shuffle(out)
    return out


def meshes():
    rng = random.Random(7)
    out = [("pillow", [(0, 1, 2), (0, 2, 1)]), ("tet", TET), ("octa", OCTA), ("ico", ICO), ("tet1", subdivide(TET)),
           ("octa1", subdivide(OCTA)), ("ico1", subdivide(ICO))]
    out += [("bipyramid%d" % n, bipyramid(n)) for n in (3, 4, 5, 9)]
    for i in range(6):
        base = [OCTA, ICO, subdivide(OCTA)][i % 3]
        out.append(("flipped%d" % i, random_flips(base, 10 + 15 * i, rng)))
    return out


def check_round_trip(faces, start):
    symbols, order, tri_order = encode(faces, start)
    got = decode(symbols)
    index = {v: i for i, v in enumerate(order)}
    assert sorted(order) == sorted({x for t in faces for x in t})
    # Same mesh up to vertex order: the relabelled input is exactly the decoded list, face by face.
    want = [tuple(index[x] for x in faces[f]) for f in tri_order]
    assert [canon(t) for t in got] == [canon(t) for t in want]
    assert sorted(tri_order) == list(range(len(faces)))
    return symbols


def test_decode_inverts_encode_from_every_start():
    for name, faces in meshes():
        for start in range(len(faces)):
            check_round_trip(faces, start)


def test_round_trip_after_random_relabelling():
    rng = random.Random(11)
    for name, faces in meshes():
        for _ in range(5):
            g = relabel(faces, rng)
            check_round_trip(g, rng.randrange(len(g)))


def test_counts_and_bit_bound():
    for name, faces in meshes():
        t = len(faces)
        v = len({x for f in faces for x in f})
        assert v - 3 * t // 2 + t == 2
        for start in range(len(faces)):
            symbols, _, _ = encode(faces, start)
            assert len(symbols) == t - 1
            assert symbols.count("C") == v - 3
            assert symbols.count("E") == symbols.count("S") + 1
            bits = to_bits(symbols)
            assert len(bits) == 2 * t - 1
            assert from_bits(bits) == symbols


def test_all_five_symbols_occur():
    seen = set()
    for name, faces in meshes():
        for start in range(len(faces)):
            seen |= set(encode(faces, start)[0])
    assert seen == set("CLRSE")


def slow_lengths(symbols):
    """Brute force: for each S, scan forward until its right branch has one more E than S."""
    out = {}
    for i, s in enumerate(symbols):
        if s != "S":
            continue
        bal, j = 1, i
        while bal:
            j += 1
            bal += {"S": 1, "E": -1}.get(symbols[j], 0)
        part = symbols[i + 1:j + 1]
        # Each C adds one edge to the loop, L and R remove one, S adds one, E removes three.
        size = 0
        for x in reversed(part):
            size += {"C": -1, "L": 1, "R": 1, "S": -1, "E": 3}[x]
        out[i] = size
    return out


def test_loop_lengths_match_a_slow_scan():
    for name, faces in meshes():
        for start in range(0, len(faces), 3):
            symbols, order, tri_order = encode(faces, start)
            lengths = right_loop_lengths(symbols)
            assert lengths == slow_lengths(symbols)
            assert sorted(lengths) == [i for i, s in enumerate(symbols) if s == "S"]
            assert all(n >= 3 for n in lengths.values())


def test_rejects_meshes_that_are_not_spheres():
    with pytest.raises(ValueError):
        encode(TET[:3])  # a disk with a boundary
    torus = []
    m, n = 3, 4
    for i in range(m):
        for j in range(n):
            a, b = i * n + j, i * n + (j + 1) % n
            c, d = ((i + 1) % m) * n + j, ((i + 1) % m) * n + (j + 1) % n
            torus += [(a, b, d), (a, d, c)]
    with pytest.raises(ValueError):
        encode(torus)
    # Two octahedra glued at two opposite vertices: V - E + F = 10 - 24 + 16 = 2, but not a sphere.
    other = {0: 0, 1: 1, 2: 6, 3: 7, 4: 8, 5: 9}
    pinched = OCTA + [tuple(other[x] for x in f) for f in OCTA]
    with pytest.raises(ValueError):
        encode(pinched)
    with pytest.raises(ValueError):
        encode([(0, 0, 1)] + TET)
    with pytest.raises(ValueError):
        decode("CCE")  # too short for its loops
    with pytest.raises(ValueError):
        decode("CRSE")  # an S without the E of its second loop

History

Jarek Rossignac introduced Edgebreaker in 1999, in IEEE Transactions on Visualization and Computer Graphics, one year after the valence-based coder of Touma and Gotsman. His paper gave the five CLERS symbols, the stack for S and the bound of 2 bits per triangle for meshes with the topology of a sphere. Later papers made the decoder run in linear time, lowered the guaranteed bound, and gave a short implementation on a corner table. Edgebreaker and its variants became a standard part of the compression of 3D triangle meshes.

References

  1. Jarek Rossignac, Edgebreaker, connectivity compression for triangle meshes, IEEE Transactions on Visualization and Computer Graphics 5(1), pages 47-61, 1999, the five symbols C, L, E, R and S, the traversal with a stack for S, the code with 1 bit for C and 3 bits for the other symbols, the 2t bit bound for meshes with the topology of a sphere, and the measured rates with entropy coding

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.decode
  • a full proof of time.encode
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example