Techniquecore
Euler operators
Also called Euler-Poincare operators, Euler ops.
Local steps such as make edge and vertex or kill face, make ring and hole that edit a B-rep and keep the Euler-Poincare formula and a valid topology, but not a valid geometry.
Euler operators are the small steps with which a solid modeler builds and edits a boundary representation. Each step adds or removes a few cells together, for example one edge and one vertex (MEV), or one edge and one face (MEF), and the cells change so that the Euler-Poincaré formula for solids stays true. More than that, each step changes a valid surface into a valid surface: a closed, oriented 2-manifold whose faces are disks with holes. So a modeler that changes its boundary model only through Euler operators never has a broken topology. It can still have a broken geometry, such as faces that cross, because the operators do not look at the coordinates. Baumgart introduced the idea in 1975, Braid, Hillyard and Stroud wrote the operators with rings and holes in 1980, and Mäntylä built the GWB modeler on them and proved in 1984 that they reach every valid topology.
This page is the technique. The formula itself, with its proof and the conditions it needs, is on the page of the Euler-Poincaré formula for solids, and the planar case for connected plane graphs is Euler's formula. The formula says which counts are possible. The operators are a way to move between models with possible counts, one valid model at each step.
The counts are vertices, edges, faces, loops (the boundary cycles of the faces, so is the number of rings, the inner loops), shells and holes (the total genus). The orientation is the right-hand rule: seen from outside the solid, the outer loop of a face runs counterclockwise and its rings run clockwise.
In plain words
Think of the surface of a solid as a map drawn on a rubber skin. You may change the map only with a few allowed moves. Draw a new line from a point to a new point. Draw a line across a country from one border to another, so that it splits into two countries. Rub out a line that has the same country on both sides, so that the country gets a hole in it. Glue two countries together through the inside of the solid, which makes a tunnel.
Each move changes the numbers of points, lines and countries in a fixed way, and the skin is never torn. Each move has an undo move. The moves do not know where the points are, so they cannot stop you from moving a point to a bad place.
When it applies
- The model is a boundary representation of a manifold solid: each shell is a closed, orientable surface, and each face is a disk with holes. A half-edge structure, the winged-edge structure or a doubly connected edge list with loops can store it.
- You want every program that changes the model to keep it valid by construction, instead of a full check after each change. Sweeps, gluing, Boolean operations and local edits of a B-rep modeler are made of Euler operators.
- You want a log of changes that can be undone. Each operator has an inverse with the opposite counts.
- It does not apply as it is to non-manifold models, such as two cubes that share an edge, or to faces with dangling sheets. Those need the operators of a non-manifold structure such as the radial edge data structure.
The template
A model is a set of shells. A face has one outer loop and a list of rings. A loop is a cycle of half-edges, each with an origin vertex, and and give the cycle. A loop that is a single vertex has one lone half-edge with no edge. An edge has two half-edges in opposite directions, and is the other half-edge of the edge of . A corner of a vertex in a loop is a pair with . The operator takes half-edges as arguments, because a vertex can have several corners in one loop.
MVSF(p) ▷ make vertex, shell and face- 1
create vertex v at p, a face f, and its outer loop (h), with h a lone half-edge at v MEV(h, p) ▷ make edge and vertex, in the corner of v = origin[h] before h- 2
create vertex w at p and an edge with half-edges a: v → w and b: w → v - 3
if h is lone then the loop of h becomes (a, b) else link prev[h] → a → b → h MEF(h1, h2) ▷ make edge and face; h1 and h2 are in one loop ℓ- 4
X ← (h1, next[h1], …, prev[h2]), empty if h1 = h2; Y ← the other half-edges of ℓ, from h2 - 5
create an edge with a: origin[h1] → origin[h2] and b: origin[h2] → origin[h1] - 6
ℓ ← Y followed by a; create a face f′ whose outer loop is X followed by b KEMR(a) ▷ kill edge, make ring; a and b = twin(a) are in one loop (a, X, b, Y)- 7
the loop becomes Y, a new ring of the same face becomes X, and the edge is deleted KFMRH(f1, f2) ▷ kill face, make ring and hole; f1 ≠ f2, and f2 has one loop- 8
same ← (f1 and f2 are in one shell) - 9
the loop of f2 becomes a ring of f1, and f2 is deleted - 10
if same then H ← H + 1 ▷ otherwise two shells became one
In lines L3, L6 and L7, an empty sequence of half-edges means a lone half-edge at the right vertex: in line L7, an empty is a lone half-edge at and an empty one at . The inverses are KVSF, KEV, KEF, MEKR and MFKRH. KEV needs , so that the far vertex has no other edge, and removes , and that vertex. KEF needs two different faces on the two sides of the edge, joins the two loops, and deletes the face of , whose other loops become rings of the face of . MEKR joins two loops of one face by a new edge into the loop . MFKRH makes the ring the outer loop of a new face, and goes down by 1 unless this splits the shell. The changes of the counts are these:
| operator | inverse | ||||||
|---|---|---|---|---|---|---|---|
| MVSF | +1 | 0 | +1 | +1 | +1 | 0 | KVSF |
| MEV | +1 | +1 | 0 | 0 | 0 | 0 | KEV |
| MEF | 0 | +1 | +1 | +1 | 0 | 0 | KEF |
| KEMR | 0 | -1 | 0 | +1 | 0 | 0 | MEKR |
| KFMRH, one shell | 0 | 0 | -1 | 0 | 0 | +1 | MFKRH |
| KFMRH, two shells | 0 | 0 | -1 | 0 | -1 | 0 | MFKRH |
Put each row into , the change of the left side of the formula: every row gives 0. KEMR keeps and adds a loop, so it adds a ring; KFMRH removes a face and keeps its loop, so it also adds a ring. The first five rows are a basis of the integer solutions of the formula, as the theorem page shows, so any change of counts that keeps the formula is a sum of operator steps.
Why each step gives a valid surface
Assume that the model before the step is valid: each shell is a closed, oriented surface, and the cells cut it into vertices, open arcs and faces that are open disks with holes, with the loops as boundaries. Each claim below is about the surface of one shell.
- MVSF makes a new shell: a sphere cut into one point and the open disk that is the rest. The disk has one loop, the vertex.
- MEV draws an arc inside the face of , from into the face, through the corner before , to a new point inside . The face minus a simple arc that touches its boundary at one end is still a disk with the same number of holes. Its loop now goes out along and back along .
- MEF draws an arc inside from the corner before to the corner before , both on the loop . A face is planar (a disk with holes), so an arc with both ends on one boundary loop cuts it into two parts. One part is bounded by and , and the operator makes it the new face. The other part keeps , and the other loops. Each part is again a disk with holes. If , the arc is closed at and cuts off a disk bounded by the one edge .
- KEMR removes an edge with the same loop on both sides. If has holes and its loop runs along twice, then is connected, orientable, has boundary loops, and has compact Euler characteristic . A surface of genus with boundary loops has , so : the new face is again a disk with holes, now of them.
- KFMRH removes the disk and a small disk inside , and joins the two circles by a tube. This adds a handle if and are in one shell (the genus grows by 1), and it joins two shells into one otherwise (the connected sum). In both cases the result is a closed, oriented surface, and is a disk with one more hole.
- The inverses undo these changes, and their preconditions are exactly what makes the undo a valid surface. The checks in KEV and KEF ask that the far vertex has degree 1 and that the edge has two different faces. KEMR asks for one loop on both sides of the edge. MEKR asks for two loops of one face.
Each new edge gets two half-edges in opposite directions, and each loop that the operators build keeps the order of the old half-edges, so the orientation stays consistent. Mäntylä (1984) proved the converse: every valid topology of this kind, with any number of shells and holes, is reached from nothing by a finite sequence of these operators. The operators are therefore enough to build any manifold solid model.
Cost
MVSF, MEV and KEV change pointers. MEF, KEF, KEMR and MEKR set the loop pointer of each half-edge that changes loop, so they take time for loops of half-edges in total. KFMRH and MFKRH move one loop in time, plus a search of the shell in time to decide whether or changes. A modeler that does not store can skip the search and get from the counts when it needs it.
Classic examples
A cube. The sequence MVSF, 3 MEV, MEF, 4 MEV, 4 MEF builds the unit cube. The implementation of this page builds it like this, and the counts after each group of steps are these:
| step | the operator does | ||||||
|---|---|---|---|---|---|---|---|
| MVSF | vertex 0 and one face | 1 | 0 | 1 | 1 | 1 | 0 |
| 3 MEV | the path 0, 1, 2, 3 of the bottom | 4 | 3 | 1 | 1 | 1 | 0 |
| MEF | closes the bottom square with the edge from 3 to 0 | 4 | 4 | 2 | 2 | 1 | 0 |
| 4 MEV | the vertical edges up to 4, 5, 6, 7 | 8 | 8 | 2 | 2 | 1 | 0 |
| 4 MEF | the top edges, which cut off the 4 sides | 8 | 12 | 6 | 6 | 1 | 0 |
In the MEF that closes the bottom, is the half-edge from 3 to 2 and is the half-edge from 0 to 1. Then is the half-edges from 3 to 2, 2 to 1 and 1 to 0, and the new face has the loop 3, 2, 1, 0: the bottom, which runs clockwise seen from above, so its outward normal points down. The old face keeps 0, 1, 2, 3 and becomes the top later. The test checks that the 6 faces have the right corners, that each face is planar, and that the signed volume is exactly 1.
A cube with a through-hole. Take the box from the 13 steps above. Then:
- MEV from the top corner to , the bridge, and 3 MEV to , and .
- MEF closes the inner square. This makes the inner square face, and the top loop goes around the outer square, along the bridge, around the inner square and back. Now , , , .
- KEMR on the bridge. The inner square becomes a ring of the top face: , , so .
- 4 MEV from the corners of the inner square face down to , and 4 MEF that cut off the 4 walls of the hole. The inner square face is now at the bottom of a well: , , , , , .
- KFMRH with the bottom face as and the bottom of the well as . They are in one shell, so the hole opens: , , .
The result is the square frame of the theorem page, , with volume exactly 8 in the test. The state before the last step has the same counts as a plate with a block on top: both are spheres with one ring face, so no count can tell them apart.
A cube with a cavity. Build a second box with MVSF and the same 12 steps, but with an orientation that points into the cavity. This is a second shell: , , , , , , and the signed volume of minus is 26.
The smallest cases. MVSF and then MEF with the lone half-edge give a sphere cut by one closed edge into two disks: , , , . MVSF twice and then KFMRH move the second vertex into the face of the first shell as a ring: , , , , , and .
Edits of triangle meshes. The edge collapse of mesh simplification removes 1 vertex, 3 edges and 2 faces from a closed triangle mesh. This is KEF twice, for the two triangles of the edge, and then KEV: . An edge flip is KEF followed by MEF, and it keeps all counts.
Sweeps and gluing. To extrude a face with edges, do MEV at each of its vertices and then MEF: the counts change by . To glue two solids along two equal faces, a modeler can use KFMRH to join the two shells through the two faces, and then remove the double edges and vertices of the seam with KEF and KEV.
Variations
- Other operator sets. Baumgart's Euler primitives (1975) act on the winged-edge structure. Braid, Hillyard and Stroud (1980) wrote their operators for the BUILD modeler with loops and holes in the counts. Mäntylä names the first operator MVFS, make vertex, face and solid, because a solid in GWB starts with one shell. This page writes MVSF, with S for the new shell. Any five operators whose change vectors are a basis of the solutions work as well.
- A more general MEV. In GWB the low-level MEV takes two half-edges at the same vertex, and it splits the vertex: the edges between the two corners move to the new vertex, and the new edge joins the two. The MEV of this page is the case in which the two half-edges are the same.
- High-level operators. A modeler offers sweeps, gluing, chamfers and Booleans as sequences of the basic ones. Then the result of any program stays a valid surface, and the log of basic steps makes undo simple.
- Non-manifold operators. For wire edges, faces that touch along an edge and solids that touch at a vertex, the counts and the operators change, and they act on a structure such as the radial edge data structure.
Pitfalls
- A valid topology is not a valid solid. The operators keep the surface a closed, oriented 2-manifold with disk faces, but they do not look at the points. A MEV can put the new vertex outside the face, a MEF can join two points by a curve that leaves the face, and a sequence can give faces that cross. A modeler must check the geometry, or build only by steps that are geometrically safe, such as sweeps. (The stub of this page said that every result is valid; that is true only for the topology.)
- The formula is not the check. The formula holds after every operator, but a model can satisfy the formula without being built by valid steps. Building by operators gives validity; checking the counts does not.
- Which side is the new face. MEF splits the loop at two corners, and which part goes to the new face is a convention. The half-edges go to the new face here. A wrong choice gives the right topology but the wrong face for later steps, for example the bottom of a cube where the top should be.
- Outer loop and ring. The topology does not know which loop of a face is the outer one. KEMR and MFKRH need the caller to decide this from the geometry.
- Lone half-edges. A loop that is a single vertex has no edge. MEV and MEF on such a loop, and KEV, KEF and KEMR that empty a loop, must make or remove the lone half-edge, or the vertex is lost.
- KFMRH between shells. If the two faces are in different shells, the genus does not grow; the two shells become one. Code that always adds 1 to gets wrong counts.
Code
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
# Part of https://algorithm.tamnd.com/euler-operators/. The authors are listed in prov/23HY3M.jsonl.
"""Euler operators on a half-edge boundary model (the topology only).
A face has an outer loop and a list of rings. A loop is a cycle of half-edges
linked by next and prev. A loop that is a single vertex has one lone half-edge
whose edge is None. An edge has two half-edges in opposite directions: he1 runs
from the first vertex to the second and he2 runs back. The twin of a half-edge
is the other half-edge of its edge.
Orientation: the loops of a face run so that the face is on the left seen from
outside the solid (the right-hand rule). The operators always give the two
half-edges of an edge opposite directions, so they keep a consistent
orientation. Points are stored but never used: the operators change only the
topology, and the caller must keep the geometry valid.
The operators and the change in (V, E, F, L, S, H):
mvsf (+1, 0, +1, +1, +1, 0) kvsf is the inverse
mev (+1, +1, 0, 0, 0, 0) kev is the inverse
mef (0, +1, +1, +1, 0, 0) kef is the inverse
kemr (0, -1, 0, +1, 0, 0) mekr is the inverse
kfmrh (0, 0, -1, 0, 0, +1), or (0, 0, -1, 0, -1, 0) if it joins two shells;
mfkrh is the inverse
"""
from __future__ import annotations
from typing import Any, Optional
class EulerError(ValueError):
"""The arguments do not meet the precondition of the operator."""
class Vertex:
__slots__ = ("id", "point")
def __init__(self, vid: int, point: Any) -> None:
self.id = vid
self.point = point
class Edge:
__slots__ = ("he1", "he2")
class HalfEdge:
__slots__ = ("vertex", "loop", "edge", "next", "prev")
def __init__(self, vertex: Vertex, edge: Optional[Edge]) -> None:
self.vertex = vertex
self.edge = edge
self.loop: Loop
self.next: HalfEdge = self
self.prev: HalfEdge = self
class Loop:
__slots__ = ("he", "face")
def __init__(self, face: "Face") -> None:
self.face = face
self.he: HalfEdge
class Face:
__slots__ = ("outer", "rings")
def __init__(self) -> None:
self.outer: Loop
self.rings: list[Loop] = []
def loops(self) -> list[Loop]:
return [self.outer] + self.rings
def twin(h: HalfEdge) -> HalfEdge:
"""The other half-edge of the edge of h."""
e = h.edge
if e is None:
raise EulerError("a lone half-edge has no twin")
return e.he2 if e.he1 is h else e.he1
def is_lone(h: HalfEdge) -> bool:
return h.edge is None
def walk(h: HalfEdge, stop: Optional[HalfEdge] = None) -> list[HalfEdge]:
"""The half-edges h, next[h], ... before stop (the whole cycle if stop is None).
A lone half-edge gives the empty list, and walk(h, h) is empty.
"""
if is_lone(h):
return []
if stop is h:
return []
out = [h]
g = h.next
while g is not h and g is not stop:
out.append(g)
g = g.next
return out
class Model:
"""A set of shells. The counts V, E, F and L are the sizes of the stores, S is
found by a search, and H is kept by kfmrh and mfkrh."""
def __init__(self) -> None:
# dicts used as ordered sets, so that iteration does not depend on id()
self.vertices: dict[int, Vertex] = {}
self.edges: dict[Edge, None] = {}
self.faces: dict[Face, None] = {}
self.loops: dict[Loop, None] = {}
self.holes = 0
self._fresh = 0
# ----- helpers -----
def _vertex(self, point: Any, vid: Optional[int]) -> Vertex:
if vid is None:
vid = self._fresh
if vid in self.vertices:
raise EulerError(f"vertex id {vid} is in use")
self._fresh = max(self._fresh, vid + 1)
v = Vertex(vid, point)
self.vertices[vid] = v
return v
def _edge(self, u: Vertex, w: Vertex) -> tuple[HalfEdge, HalfEdge]:
e = Edge()
a, b = HalfEdge(u, e), HalfEdge(w, e)
e.he1, e.he2 = a, b
self.edges[e] = None
return a, b
def _relink(self, loop: Loop, hs: list[HalfEdge], vertex: Vertex) -> None:
"""Make hs the cycle of loop. An empty hs gives a lone half-edge at vertex."""
if not hs:
hs = [HalfEdge(vertex, None)]
k = len(hs)
for i, h in enumerate(hs):
h.next = hs[(i + 1) % k]
h.prev = hs[i - 1]
h.loop = loop
loop.he = hs[0]
def _check_he(self, h: HalfEdge) -> None:
if getattr(h, "loop", None) not in self.loops:
raise EulerError("the half-edge is not in the model")
def shell(self, f: Face) -> set[Face]:
"""The faces of the shell of f: a search across the edges."""
seen = {f}
stack = [f]
while stack:
g = stack.pop()
for loop in g.loops():
for h in walk(loop.he):
k = twin(h).loop.face
if k not in seen:
seen.add(k)
stack.append(k)
return seen
def shells(self) -> list[set[Face]]:
out: list[set[Face]] = []
done: set[Face] = set()
for f in self.faces:
if f not in done:
s = self.shell(f)
done |= s
out.append(s)
return out
def counts(self) -> dict[str, int]:
return {
"V": len(self.vertices),
"E": len(self.edges),
"F": len(self.faces),
"L": len(self.loops),
"S": len(self.shells()),
"H": self.holes,
}
# ----- make and kill vertex, shell and face -----
def mvsf(self, point: Any = None, vid: Optional[int] = None) -> Face:
"""Make vertex, shell and face: a new shell with one vertex and one face
whose only loop is that vertex. Returns the face."""
v = self._vertex(point, vid) # @line L1
f = Face()
loop = Loop(f)
f.outer = loop
self.faces[f] = None
self.loops[loop] = None
self._relink(loop, [], v)
return f
def kvsf(self, f: Face) -> Vertex:
"""Kill vertex, shell and face: the inverse of mvsf. Returns the vertex."""
if f not in self.faces or f.rings or not is_lone(f.outer.he):
raise EulerError("kvsf needs a face whose only loop is a lone vertex")
v = f.outer.he.vertex
del self.vertices[v.id]
del self.loops[f.outer]
del self.faces[f]
return v
# ----- make and kill edge and vertex -----
def mev(self, h: HalfEdge, point: Any = None, vid: Optional[int] = None) -> HalfEdge:
"""Make edge and vertex: a new edge from v = h.vertex to a new vertex w, in
the corner of v before h. Returns the half-edge from v to w."""
self._check_he(h)
v = h.vertex
w = self._vertex(point, vid)
a, b = self._edge(v, w) # @line L2
loop = h.loop
if is_lone(h): # @line L3
self._relink(loop, [a, b], v)
else:
p = h.prev
p.next, a.prev = a, p
a.next, b.prev = b, a
b.next, h.prev = h, b
a.loop = b.loop = loop
return a
def kev(self, a: HalfEdge) -> HalfEdge:
"""Kill edge and vertex: a runs from v to w, and w has no other edge.
Returns the half-edge h with mev(h) as the inverse."""
self._check_he(a)
b = twin(a)
if a.next is not b:
raise EulerError("kev needs an edge whose far vertex has degree 1")
v, w = a.vertex, b.vertex
loop = a.loop
if b.next is a:
self._relink(loop, [], v)
h = loop.he
else:
p, h = a.prev, b.next
p.next, h.prev = h, p
loop.he = h
del self.edges[a.edge]
del self.vertices[w.id]
return h
# ----- make and kill edge and face -----
def mef(self, h1: HalfEdge, h2: HalfEdge) -> HalfEdge:
"""Make edge and face: h1 and h2 lie in one loop. A new edge runs from
h1.vertex to h2.vertex, and the half-edges h1, ..., prev(h2) go to a new
face. Returns the new half-edge a in the old face; twin(a) is in the new face."""
self._check_he(h1)
self._check_he(h2)
loop = h1.loop
if h2.loop is not loop:
raise EulerError("mef needs two half-edges of one loop")
x = walk(h1, h2) # @line L4
y = walk(h1) if h1 is h2 else walk(h2, h1)
a, b = self._edge(h1.vertex, h2.vertex) # @line L5
f2 = Face() # @line L6
loop2 = Loop(f2)
f2.outer = loop2
self.faces[f2] = None
self.loops[loop2] = None
self._relink(loop, y + [a], h1.vertex)
self._relink(loop2, x + [b], h2.vertex)
return a
def kef(self, a: HalfEdge) -> tuple[HalfEdge, HalfEdge]:
"""Kill edge and face: the faces of a and twin(a) differ. The face of
twin(a) is deleted and its other loops become rings of the face of a.
Returns (h1, h2) with mef(h1, h2) as the inverse, if the loop of a was
longer than a alone."""
self._check_he(a)
b = twin(a)
la, lb = a.loop, b.loop
f1, f2 = la.face, lb.face
if f1 is f2:
raise EulerError("kef needs an edge between two faces")
x = walk(b.next, b) if b.next is not b else []
y = walk(a.next, a) if a.next is not a else []
self._relink(la, x + y, a.vertex)
for ring in f2.loops():
if ring is not lb:
ring.face = f1
f1.rings.append(ring)
del self.edges[a.edge]
del self.loops[lb]
del self.faces[f2]
h1 = x[0] if x else (y[0] if y else la.he)
h2 = y[0] if y else h1
return h1, h2
# ----- kill edge make ring, and its inverse -----
def kemr(self, a: HalfEdge) -> tuple[HalfEdge, HalfEdge]:
"""Kill edge, make ring: a and twin(a) lie in one loop (a, X, b, Y). The loop
keeps Y, and X becomes a new ring of the same face. Returns (h1, h2) with
mekr(h1, h2) as the inverse."""
self._check_he(a)
b = twin(a)
loop = a.loop
if b.loop is not loop:
raise EulerError("kemr needs an edge with both half-edges in one loop")
x = walk(a.next, b) # @line L7
y = walk(b.next, a)
v, w = a.vertex, b.vertex
f = loop.face
ring = Loop(f)
f.rings.append(ring)
self.loops[ring] = None
del self.edges[a.edge]
self._relink(loop, y, v)
self._relink(ring, x, w)
return loop.he, ring.he
def mekr(self, h1: HalfEdge, h2: HalfEdge) -> HalfEdge:
"""Make edge, kill ring: h1 and h2 lie in two loops of one face. A new edge
joins h1.vertex to h2.vertex, and the two loops become one. Returns the new
half-edge from h1.vertex to h2.vertex."""
self._check_he(h1)
self._check_he(h2)
l1, l2 = h1.loop, h2.loop
f = l1.face
if l1 is l2 or l2.face is not f:
raise EulerError("mekr needs two loops of one face")
a, b = self._edge(h1.vertex, h2.vertex)
hs = [a] + walk(h2) + [b] + walk(h1)
if f.outer is l2:
f.rings.remove(l1)
f.outer = l1
else:
f.rings.remove(l2)
del self.loops[l2]
self._relink(l1, hs, h1.vertex)
return a
# ----- kill face make ring and hole, and its inverse -----
def kfmrh(self, f1: Face, f2: Face) -> Loop:
"""Kill face, make ring and hole: the only loop of f2 becomes a ring of f1.
If f1 and f2 are in one shell, the genus grows by 1; otherwise two shells
become one. Returns the new ring."""
if f1 not in self.faces or f2 not in self.faces or f1 is f2:
raise EulerError("kfmrh needs two faces")
if f2.rings:
raise EulerError("kfmrh needs a face f2 with one loop")
same = f2 in self.shell(f1) # @line L8
ring = f2.outer # @line L9
ring.face = f1
f1.rings.append(ring)
del self.faces[f2]
if same: # @line L10
self.holes += 1
return ring
def mfkrh(self, ring: Loop) -> Face:
"""Make face, kill ring and hole: a ring of a face becomes the outer loop of
a new face. Returns the new face."""
if ring not in self.loops or ring.face.outer is ring:
raise EulerError("mfkrh needs a ring")
f1 = ring.face
f1.rings.remove(ring)
f2 = Face()
f2.outer = ring
ring.face = f2
self.faces[f2] = None
if f2 in self.shell(f1):
self.holes -= 1
return f2
# ----- the check -----
def check(self) -> dict[str, int]:
"""Check the structure and return the counts. Raises EulerError if a
pointer is wrong, a vertex is not one fan, or a shell has an Euler
characteristic that is odd or greater than 2, or if the holes do not add up."""
out_of: dict[Vertex, list[HalfEdge]] = {v: [] for v in self.vertices.values()}
on_edge: dict[Edge, int] = {e: 0 for e in self.edges}
for f in self.faces:
for loop in f.loops():
if loop not in self.loops or loop.face is not f:
raise EulerError("a loop and its face do not agree")
n_loops = sum(len(f.loops()) for f in self.faces)
if n_loops != len(self.loops):
raise EulerError("a loop has no face")
for loop in self.loops:
h = loop.he
k = 0
while True:
if h.loop is not loop or h.next.prev is not h:
raise EulerError("next, prev and loop do not agree")
if h.vertex not in out_of:
raise EulerError("a half-edge has no vertex")
out_of[h.vertex].append(h)
if is_lone(h):
if h.next is not h:
raise EulerError("a lone half-edge is not alone in its loop")
else:
if h.edge not in on_edge:
raise EulerError("a half-edge has no edge")
on_edge[h.edge] += 1
if twin(h).vertex is not h.next.vertex:
raise EulerError("the twins of an edge do not run in opposite directions")
k += 1
h = h.next
if h is loop.he:
break
for e, c in on_edge.items():
if c != 2 or e.he1.edge is not e or e.he2.edge is not e:
raise EulerError("an edge is not used by its two half-edges")
for v, hs in out_of.items():
if not hs:
raise EulerError("a vertex has no half-edge")
if any(is_lone(h) for h in hs):
if len(hs) != 1:
raise EulerError("a lone vertex has edges")
continue
fan = {hs[0]}
g = twin(hs[0].prev)
while g is not hs[0]:
fan.add(g)
g = twin(g.prev)
if len(fan) != len(hs):
raise EulerError("the faces at a vertex do not make one fan")
genus = 0
for s in self.shells():
hs_ = [h for f in s for loop in f.loops() for h in walk(loop.he)]
verts = {h.vertex for f in s for loop in f.loops() for h in [loop.he] + walk(loop.he)}
nv = len(verts)
ne = len(hs_) // 2
nf = len(s)
nr = sum(len(f.rings) for f in s)
chi = nv - ne + nf - nr
if chi > 2 or chi % 2:
raise EulerError("a shell has an impossible Euler characteristic")
genus += (2 - chi) // 2
if genus != self.holes:
raise EulerError("the holes do not add up")
return self.counts()
test_euler_operators.py 459 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/euler-operators/. The authors are listed in prov/23HY3M.jsonl.
import random
import unittest
from fractions import Fraction
from euler_operators import EulerError, Model, is_lone, twin, walk
# change in (V, E, F, L, S, H) of each operator
TABLE = {
"mvsf": (1, 0, 1, 1, 1, 0),
"kvsf": (-1, 0, -1, -1, -1, 0),
"mev": (1, 1, 0, 0, 0, 0),
"kev": (-1, -1, 0, 0, 0, 0),
"mef": (0, 1, 1, 1, 0, 0),
"kef": (0, -1, -1, -1, 0, 0),
"kemr": (0, -1, 0, 1, 0, 0),
"mekr": (0, 1, 0, -1, 0, 0),
"kfmrh": ((0, 0, -1, 0, 0, 1), (0, 0, -1, 0, -1, 0)),
"mfkrh": ((0, 0, 1, 0, 0, -1), (0, 0, 1, 0, 1, 0)),
}
KEYS = ("V", "E", "F", "L", "S", "H")
def euler_poincare(c):
return c["V"] - c["E"] + c["F"] - (c["L"] - c["F"]) - 2 * (c["S"] - c["H"])
def recount(m):
"""Count by a scan of the loops, with shells by union-find (the brute force)."""
loops = [] # (face index, list of (vertex id, edge or None))
faces = list(m.faces)
index = {f: i for i, f in enumerate(faces)}
for f in faces:
for loop in f.loops():
seq = []
h = loop.he
while True:
seq.append((h.vertex.id, h.edge))
h = h.next
if h is loop.he:
break
loops.append((index[f], seq))
parent = list(range(len(faces)))
def find(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
edge_faces = {}
for fi, seq in loops:
for _, e in seq:
if e is not None:
edge_faces.setdefault(e, []).append(fi)
for fs in edge_faces.values():
assert len(fs) == 2
parent[find(fs[0])] = find(fs[1])
roots = {find(i) for i in range(len(faces))}
per = {r: [set(), set(), 0, 0] for r in roots} # vertices, edges, faces, loops
for fi, seq in loops:
p = per[find(fi)]
p[3] += 1
for vid, e in seq:
p[0].add(vid)
if e is not None:
p[1].add(e)
for i in range(len(faces)):
per[find(i)][2] += 1
genus = 0
for vs, es, nf, nl in per.values():
chi = len(vs) - len(es) + nf - (nl - nf)
assert chi <= 2 and chi % 2 == 0, chi
genus += (2 - chi) // 2
return {
"V": len({vid for _, seq in loops for vid, _ in seq}),
"E": len(edge_faces),
"F": len(faces),
"L": len(loops),
"S": len(roots),
"H": genus,
}
def signature(m):
"""The faces as sorted lists of loops, each loop its least rotation of
(vertex id, lone) pairs. Outer loops and rings are not told apart."""
def loop_sig(loop):
seq = []
h = loop.he
while True:
seq.append((h.vertex.id, is_lone(h)))
h = h.next
if h is loop.he:
break
return min(tuple(seq[i:] + seq[:i]) for i in range(len(seq)))
return tuple(sorted(tuple(sorted(loop_sig(lp) for lp in f.loops())) for f in m.faces))
def delta(before, after):
return tuple(after[k] - before[k] for k in KEYS)
class Tracker:
"""Apply operators, and after each one check the structure, the brute-force
counts, the change table and the Euler-Poincare formula."""
def __init__(self, test, m):
self.t = test
self.m = m
self.c = m.check()
def do(self, name, *args, **kw):
res = getattr(self.m, name)(*args, **kw)
c = self.m.check()
self.t.assertEqual(c, recount(self.m))
d = delta(self.c, c)
want = TABLE[name]
if isinstance(want[0], tuple):
self.t.assertIn(d, want)
else:
self.t.assertEqual(d, want)
self.t.assertEqual(euler_poincare(c), 0)
self.c = c
return res
def he(m, f, u, w=None):
"""The half-edge of face f that starts at vertex u (and ends at w)."""
found = []
for loop in f.loops():
h = loop.he
while True:
if h.vertex.id == u and (w is None or (not is_lone(h) and h.next.vertex.id == w)):
found.append(h)
h = h.next
if h is loop.he:
break
assert len(found) == 1, (u, w, len(found))
return found[0]
def face_with(m, u, w):
"""The face that has the half-edge from u to w."""
out = [f for f in m.faces for lp in f.loops() for h in walk(lp.he) if h.vertex.id == u and h.next.vertex.id == w]
assert len(out) == 1
return out[0]
def build_box(tr, lo, hi, inward=False):
"""A box by mvsf, 3 mev, mef, 4 mev, 4 mef. Returns the vertex ids
(bottom 0..3, top 4..7) and the undo list. With inward, x and y are swapped
in every point, a reflection, so the box is oriented inward."""
m = tr.m
(x0, y0, z0), (x1, y1, z1) = lo, hi
pts = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]
if inward:
pts = [(p[1], p[0], p[2]) for p in pts]
undo = []
f = tr.do("mvsf", pts[0])
v = [f.outer.he.vertex.id]
undo.append(("kvsf", f))
h = f.outer.he
for i in (1, 2, 3):
a = tr.do("mev", h, pts[i])
v.append(a.next.vertex.id)
undo.append(("kev", a))
h = twin(a) # starts at the new vertex
a = tr.do("mef", he(m, f, v[3]), he(m, f, v[0])) # closes the bottom
undo.append(("kef", a))
top = a.loop.face
for i in range(4):
a = tr.do("mev", he(m, top, v[i], v[(i + 1) % 4]), pts[4 + i])
v.append(a.next.vertex.id)
undo.append(("kev", a))
for i in range(4):
h1 = he(m, top, v[4 + i], v[i])
nxt = 4 + (i + 1) % 4
h2 = he(m, top, v[nxt], v[(i + 1) % 4]) if i < 3 else he(m, top, v[4], v[5])
a = tr.do("mef", h1, h2)
undo.append(("kef", a))
return v, pts, undo
def undo_all(tr, undo):
"""Apply the inverses in reverse order. An argument that is a list of one
item is read when it is used, and an entry with a third item stores its
result there (kemr deletes an edge, so its inverse makes a new one)."""
for entry in reversed(undo):
name, arg = entry[0], entry[1]
args = arg if isinstance(arg, tuple) else (arg,)
args = tuple(x[0] if isinstance(x, list) else x for x in args)
res = tr.do(name, *args)
if len(entry) == 3:
entry[2][0] = res
def loops_xyz(m):
"""Each face as a list of loops of points."""
out = []
for f in m.faces:
out.append([[h.vertex.point for h in walk(lp.he)] for lp in f.loops()])
return out
def volume(m):
"""The signed volume by the divergence theorem, exact (Newell normals)."""
total = Fraction(0)
for loops in loops_xyz(m):
q = loops[0][0]
for pts in loops:
n = [0, 0, 0]
for i in range(len(pts)):
a, b = pts[i], pts[(i + 1) % len(pts)]
n[0] += a[1] * b[2] - a[2] * b[1]
n[1] += a[2] * b[0] - a[0] * b[2]
n[2] += a[0] * b[1] - a[1] * b[0]
total += q[0] * n[0] + q[1] * n[1] + q[2] * n[2]
return total / 6
def planar(m):
for loops in loops_xyz(m):
pts = loops[0]
n = [0, 0, 0]
for i in range(len(pts)):
a, b = pts[i], pts[(i + 1) % len(pts)]
n[0] += a[1] * b[2] - a[2] * b[1]
n[1] += a[2] * b[0] - a[0] * b[2]
n[2] += a[0] * b[1] - a[1] * b[0]
q = pts[0]
for lp in loops:
for p in lp:
if sum(n[k] * (p[k] - q[k]) for k in range(3)) != 0:
return False
return True
def build_frame(tr):
"""The square frame [0,3]^2 x [0,1] with the hole (1,2)^2 x [0,1]."""
m = tr.m
v, pts, undo = build_box(tr, (0, 0, 0), (3, 3, 1))
top = face_with(m, v[4], v[5])
bottom = face_with(m, v[3], v[2])
a = tr.do("mev", he(m, top, v[4], v[5]), (1, 1, 1)) # the bridge
bridge = a
bridge_ref = [a]
undo.append(("kev", bridge_ref))
w = [a.next.vertex.id]
h = twin(a)
for p in ((2, 1, 1), (2, 2, 1), (1, 2, 1)):
a = tr.do("mev", h, p)
undo.append(("kev", a))
w.append(a.next.vertex.id)
h = twin(a)
a = tr.do("mef", he(m, top, w[0], w[1]), he(m, top, w[3])) # the inner square face
undo.append(("kef", a))
inner = twin(a).loop.face
h1, h2 = tr.do("kemr", bridge) # the ring of the top face
undo.append(("mekr", (h1, h2), bridge_ref))
low = []
for i, p in enumerate(((1, 1, 0), (2, 1, 0), (2, 2, 0), (1, 2, 0))):
a = tr.do("mev", he(m, inner, w[i], w[(i + 1) % 4]), p)
undo.append(("kev", a))
low.append(a.next.vertex.id)
for i in range(4):
h1 = he(m, inner, low[i], w[i])
h2 = he(m, inner, low[(i + 1) % 4], w[(i + 1) % 4]) if i < 3 else he(m, inner, low[0], low[1])
a = tr.do("mef", h1, h2)
undo.append(("kef", a))
ring = tr.do("kfmrh", bottom, inner) # the hole
undo.append(("mfkrh", ring))
return undo
class EulerOperatorTests(unittest.TestCase):
def test_cube(self):
tr = Tracker(self, Model())
v, pts, undo = build_box(tr, (0, 0, 0), (1, 1, 1))
self.assertEqual(tr.c, {"V": 8, "E": 12, "F": 6, "L": 6, "S": 1, "H": 0})
self.assertEqual(volume(tr.m), 1)
self.assertTrue(planar(tr.m))
got = sorted(sorted(lp[0]) for lp in loops_xyz(tr.m))
want = []
for axis in range(3):
for c in (0, 1):
want.append(sorted(p for p in pts if p[axis] == c))
self.assertEqual(got, sorted(want))
undo_all(tr, undo)
self.assertEqual(tr.c, {k: 0 for k in KEYS})
def test_cube_with_through_hole(self):
tr = Tracker(self, Model())
undo = build_frame(tr)
self.assertEqual(tr.c, {"V": 16, "E": 24, "F": 10, "L": 12, "S": 1, "H": 1})
self.assertEqual(volume(tr.m), 8)
self.assertTrue(planar(tr.m))
rings = [f for f in tr.m.faces if f.rings]
self.assertEqual(len(rings), 2)
undo_all(tr, undo)
self.assertEqual(tr.c, {k: 0 for k in KEYS})
def test_cavity(self):
tr = Tracker(self, Model())
build_box(tr, (0, 0, 0), (3, 3, 3))
build_box(tr, (1, 1, 1), (2, 2, 2), inward=True)
self.assertEqual(tr.c, {"V": 16, "E": 24, "F": 12, "L": 12, "S": 2, "H": 0})
self.assertEqual(volume(tr.m), 26)
def test_one_vertex_cases(self):
tr = Tracker(self, Model())
f = tr.do("mvsf")
a = tr.do("mef", f.outer.he, f.outer.he) # a sphere cut by one closed edge
self.assertEqual(tr.c, {"V": 1, "E": 1, "F": 2, "L": 2, "S": 1, "H": 0})
tr.do("kef", a)
g = tr.do("mvsf")
ring = tr.do("kfmrh", f, g) # a vertex moved into a face of another shell
self.assertEqual(tr.c, {"V": 2, "E": 0, "F": 1, "L": 2, "S": 1, "H": 0})
tr.do("mfkrh", ring)
self.assertEqual(tr.c["S"], 2)
def test_preconditions(self):
m = Model()
tr = Tracker(self, m)
undo = build_frame(tr)
before = signature(m)
top_ring = next(f for f in m.faces if f.rings)
cube_edge = next(iter(m.edges)).he1
with self.assertRaises(EulerError):
m.kev(cube_edge) # both ends have degree 3
with self.assertRaises(EulerError):
m.kemr(cube_edge) # two different loops
with self.assertRaises(EulerError):
m.mekr(top_ring.outer.he, top_ring.outer.he.next) # one loop
with self.assertRaises(EulerError):
m.mfkrh(top_ring.outer) # not a ring
with self.assertRaises(EulerError):
m.kfmrh(next(f for f in m.faces if not f.rings), top_ring) # f2 has a ring
with self.assertRaises(EulerError):
m.kvsf(top_ring)
with self.assertRaises(EulerError):
m.mef(top_ring.outer.he, top_ring.rings[0].he) # two loops
self.assertEqual(signature(m), before)
undo_all(tr, undo)
def test_random_sequences(self):
rng = random.Random(20261114)
seen = {"H": 0, "S": 0}
used = set()
rounds = 0
for run in range(40):
m = Model()
tr = Tracker(self, m)
for step in range(250):
name, args = self.pick(rng, m)
used.add(name)
before = signature(m)
pre = self.context(name, args)
res = tr.do(name, *args)
seen["H"] = max(seen["H"], tr.c["H"])
seen["S"] = max(seen["S"], tr.c["S"])
if rng.random() < 0.4:
inv = self.inverse(name, res, pre)
if inv is not None:
tr.do(*inv)
self.assertEqual(signature(m), before)
rounds += 1
self.assertEqual(used, set(TABLE))
self.assertGreaterEqual(seen["H"], 2)
self.assertGreaterEqual(seen["S"], 3)
self.assertGreater(rounds, 3000)
@staticmethod
def context(name, args):
"""What the inverse needs to know from before the operator."""
if name == "kev":
w = twin(args[0]).vertex
return (w.point, w.id)
if name == "kef":
a = args[0]
b = twin(a)
# mef puts no rings in the new face, and with h1 = h2 its new face is (b)
return not b.loop.face.rings and not (a.next is a and b.next is not b)
if name == "mfkrh":
return args[0].face
return None
@staticmethod
def inverse(name, res, pre):
if name == "mvsf":
return ("kvsf", res)
if name == "kvsf":
return ("mvsf", res.point, res.id)
if name == "mev":
return ("kev", res)
if name == "kev":
return ("mev", res, pre[0], pre[1])
if name == "mef":
return ("kef", res)
if name == "kef":
return ("mef", *res) if pre else None
if name == "kemr":
return ("mekr", *res)
if name == "mekr":
return ("kemr", res)
if name == "kfmrh":
return ("mfkrh", res)
if name == "mfkrh":
return ("kfmrh", pre, res)
return None
@staticmethod
def pick(rng, m):
hes = [h for lp in m.loops for h in ([lp.he] if is_lone(lp.he) else walk(lp.he))]
real = [h for h in hes if not is_lone(h)]
size = len(hes)
options = []
options.append(("mvsf", ()))
if hes and size < 60:
options.append(("mev", (rng.choice(hes),)))
lp = rng.choice(list(m.loops))
hs = [lp.he] if is_lone(lp.he) else walk(lp.he)
options.append(("mef", (rng.choice(hs), rng.choice(hs))))
kev = [h for h in real if h.next is twin(h)]
if kev:
options.append(("kev", (rng.choice(kev),)))
kef = [h for h in real if h.loop.face is not twin(h).loop.face]
if kef:
options.append(("kef", (rng.choice(kef),)))
kemr = [h for h in real if h.loop is twin(h).loop]
if kemr:
options.append(("kemr", (rng.choice(kemr),)))
multi = [f for f in m.faces if f.rings]
if multi:
f = rng.choice(multi)
l1, l2 = rng.sample(f.loops(), 2)
h1 = l1.he if is_lone(l1.he) else rng.choice(walk(l1.he))
h2 = l2.he if is_lone(l2.he) else rng.choice(walk(l2.he))
options.append(("mekr", (h1, h2)))
options.append(("mfkrh", (rng.choice(f.rings),)))
singles = [f for f in m.faces if not f.rings]
if len(m.faces) >= 2 and singles:
f2 = rng.choice(singles)
f1 = rng.choice([f for f in m.faces if f is not f2])
options.append(("kfmrh", (f1, f2)))
lone = [f for f in m.faces if not f.rings and is_lone(f.outer.he)]
if lone:
options.append(("kvsf", (rng.choice(lone),)))
if size >= 60:
options = [o for o in options if o[0] not in ("mvsf",)] or options
return rng.choice(options)
if __name__ == "__main__":
unittest.main()
Exercises
- Give a sequence of Euler operators that builds a tetrahedron, and list the counts after each step.
- Show that every row of the table keeps , and check that MVSF, MEV, MEF, KEMR and KFMRH in one shell have linearly independent change vectors.
- Write a sequence that builds a solid with two through-holes, the plate with holes over and . Check that it ends with , , , , .
- Show that the edge flip of a triangle mesh is KEF followed by MEF, and say which half-edges the MEF takes.
- Why is KEF not allowed for an edge that has the same face on both sides, but in two different loops of that face? What would removing the edge do to the surface?
References
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, Chapter 9 (p. 139), with Sections 9.1.3 (p. 145), 9.2.2 (p. 148), 9.2.4 (p. 151), 9.3 (p. 152), 9.4.1 (p. 154) and 9.4.3 (p. 158); Chapter 11 (p. 175) for the low-level operators of GWB
- Martti Mäntylä and Reijo Sulonen, GWB, a solid modeler with Euler operators, IEEE Computer Graphics and Applications 2(7), 1982, 17 to 31, the operators of GWB and their use for sweeps and gluing
- Martti Mäntylä, A note on the modeling space of Euler operators, Computer Vision, Graphics, and Image Processing 26(1), 1984, 45 to 60, the proof that the operators reach every valid topology and only valid ones
- Bruce G. Baumgart, A polyhedron representation for computer vision, AFIPS National Computer Conference 44, 1975, 589 to 596, the winged-edge structure and its Euler primitives
- Ian C. Braid, R. C. Hillyard and Ian A. Stroud, Stepwise construction of polyhedra in geometric modelling, in K. W. Brodlie (ed.), Mathematical Methods in Computer Graphics and Design, Academic Press, 1980, 123 to 141, the operators of the BUILD modeler, with loops and holes counted
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 23HY3M Edit this page History Report an error Markdown