Data structureintro
Boundary representation
Also called B-rep, BRep.
Represent a solid by its boundary, a set of faces glued along edges and vertices, with the topology (which faces meet where) stored apart from the geometry (the surfaces and points).
- Time
- O(n) expected
- Space
- Θ(n) extra
- Where
- n = the number of half-edges (twice the number of edges)
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
A boundary representation (B-rep) describes a solid by its skin: a set of faces, each a piece of a surface, glued along edges and at vertices. It stores two kinds of data apart. The topology says which vertices bound each edge, which edges bound each face and which faces are next to each other. The geometry gives the plane or curved surface of each face, the curve of each edge and the point of each vertex. Almost every commercial CAD kernel stores its solids as B-reps, because a B-rep gives the faces and edges directly for drawing, for machining and for the computation of mass properties. This page builds a half-edge B-rep of a polyhedral manifold solid, with faces that may have holes, and checks that it is valid.
In plain words
Think of a cardboard box. You can describe the box by its six flat sides and by how the sides are taped together. The B-rep stores exactly this: a list of corners, a list of folds, and a list of sides, and for each side the folds around it.
Each fold is stored twice, once for each side that it touches, as two arrows that point in opposite directions. The arrows of one side go around it counterclockwise when you look at the side from outside the box. With these arrows you can go around a side, cross a fold to the next side, and turn around a corner. A side can also have a hole, for example the top of a block with a peg on it. The hole is one more ring of arrows on the same side.
The abstract type
The structure stores the boundary of a polyhedral solid, and it answers adjacency queries about it. The cells are the solid, its shells, faces, loops, edges and vertices. A shell is a connected part of the boundary, a face is a planar polygon, possibly with holes, and a loop is one boundary cycle of a face. The first loop of a face is its outer loop, and the other loops are its rings. Orientation follows the right-hand rule: when the fingers follow a loop, the thumb points along the outward normal of the face. So the outer loop runs counterclockwise seen from outside, and each ring runs clockwise.
- : make the structure from the points and the faces , each face a list of loops of vertex indices.
- : the loops of as vertex cycles, outer loop first.
- : the faces on the left and on the right of the edge from to .
- : the edges at in cyclic order, so also the faces and the neighbours of in that order.
- and : the faces next to , and the connected parts of the boundary.
- : check that the stored data is the boundary of a manifold solid, as far as the checks of the next sections go, and return the counts of the Euler-Poincaré formula for solids.
A B-rep is unambiguous in the sense of Requicha: a valid B-rep describes one r-set. It is not unique: a face can be cut into two coplanar faces, and the solid does not change.
Representation
Each edge is stored as two half-edges, one for each face that uses it, with opposite directions. The records are:
| record | fields |
|---|---|
| half-edge | , (the other half of the edge), and (the neighbours on the loop), |
| loop | and one half-edge |
| face | the list of its loops, outer loop first; in a curved B-rep also the surface |
| vertex | its point and one half-edge that starts at |
| shell, solid | the list of faces of each shell, the list of shells |
The face to the left of is , and the target of is . So the structure stores 10 references per edge: 5 for each of its two half-edges. The field can be dropped, at the cost of a walk around the loop to find it, which gives 8. This is the half-edge structure of Mäntylä (Chapter 10), and it is the doubly connected edge list of planar subdivisions with a loop record added between half-edges and faces, so that a face can have more than one boundary.
These queries take time: the two vertices of an edge, the two faces of an edge, the next and previous edge on a loop, the face of a loop, and the edge across from a half-edge. The edges, faces or neighbours around a vertex take time for a vertex of degree , and the boundary of a face takes time linear in its number of edges. A plain list of faces, as in an indexed face set, answers only the first of these queries without a search.
The geometry is stored apart. Here each vertex has an exact point with integer or rational coordinates, and the plane of a face is computed from its outer loop by Newell's sum . For a planar polygon, is twice its vector area, so it points along the outward normal by the right-hand rule.
Operations
BUILD(P, faces) ▷ each face: loops of vertex indices, outer loop first- 1
for each face f, each loop ℓ of f do - 2
for each pair (u, v) of cyclically adjacent vertices of ℓ do - 3
fail if key[(u, v)] exists; create h; origin[h] ← u; loop[h] ← ℓ; key[(u, v)] ← h - 4
link the half-edges of ℓ in a cycle with next and prev - 5
for each half-edge h with key (u, v) do twin[h] ← key[(v, u)]; fail if there is none - 6
for each half-edge h do if out[origin[h]] = nil then out[origin[h]] ← h OUTGOING(v) ▷ the half-edges out of v in cyclic order- 7
h ← out[v]; repeat output h; h ← twin[prev[h]] until h = out[v] VALIDATE()- 8
check twin[twin[h]] = h and origin[twin[h]] = origin[next[h]] for each h - 9
for each vertex v: check that OUTGOING(v) has every half-edge that starts at v - 10
the shells ← the components of the faces, linked across twins - 11
for each shell: χ ← V − E + F − R of the shell; check χ ≤ 2 and χ even; H ← H + (2 − χ)/2 - 12
for each face: N ← newell(outer loop); check N ≠ 0, all its vertices on the plane, N · newell(ring) < 0 for each ring - 13
check that the volume of each shell is not 0, and that the volume (1/6) Σ_f Σ_loops q_f · newell(loop) > 0
Build. Lines L1 to L4 make one half-edge for each pair of adjacent vertices of each loop. Line L3 fails if a directed edge comes twice: then a face is reversed, or more than two faces meet at the edge. Line L5 pairs each half-edge with the one that goes the other way, and fails if there is none: then an edge has only one face, and the surface has a gap.
Around a vertex. Line L7 is the rotation of the half-edge structure. The half-edge ends at on the face of , and its twin starts at on the face across that edge. So each step moves to the next face around , across the edge between them.
Validity. Line L9 is the vertex condition of a manifold: the faces at make one fan. Line L11 uses the Euler-Poincaré formula for solids in its per-shell form : a B-rep does not store , so the formula gives the genus of each shell, and the check is that this genus is a whole number . Line L12 checks, with exact integers, that each face is planar and that its rings turn the other way from its outer loop. Line L13 computes the volume by the divergence theorem: on a planar face is constant, so , where is any vertex of . A cavity shell has negative volume, and a solid whose faces all point inward has a negative total.
Example
Take the unit cube with the vertices , , , and to the same points with . The faces, each with one loop counterclockwise from outside, are
| face | loop | outward normal |
|---|---|---|
| 0 | 0, 3, 2, 1 | |
| 1 | 4, 5, 6, 7 | |
| 2 | 0, 1, 5, 4 | |
| 3 | 1, 2, 6, 5 | |
| 4 | 2, 3, 7, 6 | |
| 5 | 3, 0, 4, 7 |
BUILD makes the 24 half-edges in this order, four per face. Half-edge 0 goes from 0 to 3 on face 0; its twin is half-edge 20, from 3 to 0 on face 5. Half-edge 8 goes from 0 to 1 on face 2, with twin 3 on face 0. So EDGE-FACES(0, 1) is (2, 0): the front face is on the left of the edge from 0 to 1, and the bottom face on its right.
OUTGOING(0) starts at . Then (from 1 to 0) and ; then (from 4 to 0) and ; then and , the start. The half-edges go to the neighbours , on the faces : the three faces at the corner, in one fan.
VALIDATE finds one shell with , so , and returns , , , , , , . The volume is 1. The tests run the same check on three more solids:
| solid | volume | |||||||
|---|---|---|---|---|---|---|---|---|
| unit cube | 8 | 12 | 6 | 6 | 0 | 1 | 0 | 1 |
| square frame minus the hole | 16 | 24 | 10 | 12 | 2 | 1 | 1 | 8 |
| plate with the block on top | 16 | 24 | 11 | 12 | 1 | 1 | 0 | 20 |
| cube with the cavity | 16 | 24 | 12 | 12 | 0 | 2 | 0 | 26 |
In the frame, the top and the bottom faces are square rings, each with an outer loop and one ring, so , and . In the plate with the block, the top face of the plate has the outline of the block as a ring, and the four sides of the block are attached to that ring. In the cube with a cavity, the inner shell has its normals pointing into the cavity, so its volume is and the total is .
Correctness
Assume that VALIDATE returns. Then line L8 says that the half-edges pair up into edges with opposite directions, and lines L3 and L5 say that each edge has exactly two faces. Line L9 says that the faces at each vertex form one cycle, so the surface is a closed 2-manifold, and it is oriented because the two faces of each edge use it in opposite directions. If each face is a planar polygon whose rings lie inside its outer loop, then each face is a disk with holes, and joining each ring to the outer loop by a cut edge gives a decomposition into disks with more edges; so each shell has Euler characteristic , and the classification of closed orientable surfaces gives with its genus. So the counts that VALIDATE returns satisfy with the true . The volume of line L13 is exact by the divergence theorem, and a positive total rules out a solid whose faces all point inward. The queries walk cycles of the permutations and , so they stop and list each item once. The full proof is in the proof file.
VALIDATE does not check that faces of the surface do not cross each other, nor that a ring lies inside its outer loop. A surface with the face lists of the square frame passes all checks even if its points are moved so that two faces cross, as long as each face stays planar and the volume stays positive. A full geometric check needs a test of each pair of faces, and the solid Boolean operations and exact geometric computation pages discuss those tests.
Proof: The half-edge B-rep stores a closed oriented surface, and VALIDATE returns its true Euler-Poincaré countsfull
We use the pseudocode of the page. The input is a list of points and a list of faces, each face a list of loops, each loop a cyclic list of at least 3 distinct vertex indices. Write and .
Lemma 1 (BUILD). If BUILD does not fail, then (a) and are inverse permutations of the half-edges, and their cycles are exactly the loops of the input, in the input order; (b) is an involution with no fixed point, and ; (c) each undirected edge that occurs in a loop is used by exactly two half-edges, one in each direction.
Proof. Lines L2 and L3 make one half-edge for each position of each loop , with origin , and line L4 sets of position to position and to position of the same loop. So on each loop, is a cyclic shift and is its inverse, which gives (a). Line L3 fails if the key is already present, so if BUILD does not fail, each directed pair is the key of at most one half-edge. Line L5 sets for the half-edge with key , and fails if there is no such key. So has key , its own twin has key , which is , and because . The key of is , and the key of is the reverse, so . This is (b), and (c) follows because the directed pairs of each have exactly one half-edge.
Lemma 2 (rotation). In the structure of Lemma 1, is a permutation of the half-edges, and it maps a half-edge out of to a half-edge out of . If starts at , then and are the two faces of the edge of , which has as an end.
Proof. is the composition of the permutations and , so it is a permutation. If , then ends at by Lemma 1(b) applied to , and its twin starts at . The half-edge lies on the loop of , so it has the face of , and its twin has the other face of the same edge.
So the half-edges out of split into cycles of , and along a cycle consecutive faces share an edge at . A cycle of at is a fan of faces around . Line L7 lists the cycle of , and it stops when it returns to , which it does because is a permutation of a finite set.
Lemma 3 (the surface is a closed oriented 2-manifold). Assume that lines L8 and L9 pass, and let be the space made from the faces, each face a polygon with holes, glued along equal edges. Then is a closed 2-manifold, and the loop directions give it an orientation.
Proof. Each point inside a face has a disk neighborhood in that face. By Lemma 1(c), each edge is on exactly two face sides, so a point inside an edge has a neighborhood made of two half-disks glued along a segment, which is a disk. At a vertex , the corners of the faces at are glued in the order of the cycles of by Lemma 2. Line L9 checks that the cycle of contains every half-edge out of , so there is one cycle, and the corners form one disk around . The surface is compact because it has finitely many faces. Each edge is used in opposite directions by its two faces, by Lemma 1(b), so the orientations of the faces that the loop directions give agree along each edge, and is oriented.
Lemma 4 (the counts). Assume in addition that each face is a disk with holes: its outer loop is a simple closed polygon and its rings are simple closed polygons inside it that do not meet each other. Then for each shell (component of ) the number of line L11 is its Euler characteristic, the shell has genus , and the that VALIDATE returns is the sum of the genera of the shells. Line L11 then passes, and .
Proof. Line L10 finds the components of the graph whose nodes are the faces and whose arcs join the two faces of each edge. Two faces in the same component are joined by a chain of faces that share edges, so they lie in one component of . Conversely, a path in goes through faces and crosses from face to face only at edges or at vertices, and at a vertex the faces form one fan by Lemma 3, so consecutive faces of the path are joined by a chain of faces through edges. So line L10 finds the shells. In a face with rings, draw segments in the face, each from a vertex of a ring to a vertex of the outer loop, that do not cross. They cut the face into one disk, and they add edges and no vertex or face. After this for all faces, every face is a disk, and the Euler characteristic of the shell is . A connected closed orientable surface has Euler characteristic with its genus, by the classification of surfaces. So and is even, line L11 passes, and it adds to . Summing over the shells gives , with .
Lemma 5 (volume). Assume that is embedded in , that is, the faces meet only along their shared edges and vertices, and that bounds the bounded set . Then equals if every loop is oriented by the right-hand rule with the outward normal of , and if every loop is reversed.
Proof. Take the vector field , whose divergence is 1. By the divergence theorem, with the outward unit normal. On a planar face with unit normal , has the same value at every point of the face, so the integral over is , where is the vector area. For a planar loop, is its vector area, with the sign of the right-hand rule, and for a disk with holes whose rings turn the other way, . Summing over the faces gives . If all loops are reversed, every changes sign. A cavity shell is oriented with its normals pointing into the cavity, away from , which is outward for , so it is counted with the outward sign.
Line L13 computes this sum with exact integers or fractions, so it decides the sign of the volume without rounding. Line L12 checks with exact arithmetic that , that every vertex of satisfies , and that each ring has , so each face is planar and its rings turn the other way from its outer loop.
Theorem. (a) BUILD stops after steps and hash-map operations. If it does not fail, the queries return: FACE-BOUNDARY() the loops of as given, EDGE-FACES(, ) the faces that use the edge from to and from to , OUTGOING() the cycle of at , ADJACENT-FACES() the faces that share an edge with , and SHELLS() the components of the face graph. (b) If VALIDATE returns, the surface is a closed, oriented 2-manifold made of planar faces, and the signed volume of its loops is positive. (c) If, in addition, the faces are disks with holes and the surface is embedded in , then the surface is the boundary of a manifold solid , the returned counts satisfy with the number of holes (the sum of the genera of the shells) of , and, if every shell is oriented outward, the returned volume is .
Proof. (a) BUILD loops once over the positions of all loops and once over the keys, with work and hash-map operations per half-edge. FACE-BOUNDARY walks from until it returns, which by Lemma 1(a) lists the loop in the input order. EDGE-FACES reads and its twin, whose keys are and by Lemma 1. OUTGOING is the cycle of by Lemma 2. ADJACENT-FACES collects over the half-edges of , which are the faces across each edge of by Lemma 1(c), and SHELLS is a graph search on these arcs. (b) Lemma 3 gives the manifold and the orientation, and lines L12 and L13 check the planarity and the sign. (c) By the Jordan-Brouwer separation theorem, each component of an embedded closed surface cuts into a bounded part and an unbounded part. Let be the set of points not in the unbounded part of an odd number of shells, that is, the points with odd nesting depth, with the surface added. It is bounded, closed and regular, and its boundary is , so it is a manifold solid. Lemma 4 gives the counts, and Lemma 5 gives the volume when every shell is oriented outward.
The theorem does not claim that VALIDATE rejects every surface that crosses itself or every face whose rings lie outside its outer loop: those need geometric intersection tests, which the page lists as a pitfall. It also does not claim that a positive total volume means that every shell points outward. If the shells of a solid with a cavity are both oriented outward as seen from their own inside, the inner shell adds its volume instead of taking it away, and the total is still positive. Line L13 rejects a solid whose shells all point inward, and a shell with zero volume. A full check of the orientation of each inner shell needs a point-in-solid test against the shells that contain it.
Termination. Every loop of the pseudocode is a loop over a finite list, or a walk along a cycle of the permutation or that stops when it returns to its start. So every operation stops, in the time that the page gives.
Complexity
Let be the number of half-edges, so .
- BUILD makes half-edges and does hash-map operations: expected time and space.
- Each pointer query takes time. OUTGOING() takes time, and FACE-BOUNDARY() takes time linear in the size of .
- VALIDATE takes time: lines L8 and L9 touch each half-edge a constant number of times, the shell search of line L10 visits each face and each half-edge once, and lines L12 and L13 do a constant number of exact products per half-edge. With integer coordinates of bits, each product has bits, so the arithmetic is exact and its cost is polynomial in .
Variants
- Winged edge. The winged-edge data structure stores one record per edge, with its two vertices, its two faces and four neighbouring edges. It uses 8 references per edge, but it must test the orientation of an edge in each step around a face.
- Radial edge. The radial edge data structure stores any number of faces around an edge, in angular order, and so it can store non-manifold solids such as two cubes that share an edge.
- Quad-edge. The quad-edge data structure stores a subdivision of a surface and its dual at the same time.
- Faces without rings. Many mesh structures allow only one loop per face, so a face with a hole must be cut into simpler faces by extra edges. The polygon mesh page gives the face-vertex and half-edge forms of meshes, and the corner table is a compact form for triangle meshes.
- Curved B-reps. Faces carry trimmed NURBS or analytic surfaces, edges carry curves, and the topology is the same. The faces of a curved solid are often trimmed surfaces.
- Construction by Euler operators. Instead of BUILD from a face list, a modeler can make and change a B-rep only by Euler operators, which keep the Euler-Poincaré formula for solids true after each step.
When to use it
Use a B-rep when the application needs faces, edges and vertices as objects: for drawing with sharp edges, for picking a face in a user interface, for tool paths, for attaching features and dimensions to faces, and for exact mass properties. It is the main representation of mechanical CAD. Use a CSG tree when the solid is built from primitives and the history must be kept, and a voxel set when exact faces do not matter and the shape is noisy, as in medical data. Booleans on B-reps are hard to make robust, and that is the main cost of the representation.
Pitfalls
- The formula is not a validity test. A B-rep can satisfy and still not be a solid: the formula does not see faces that cross, and it does not see a face that is reversed when the counts are kept. Line L11 is only one check among several.
- Rings must be counted. If a face with a hole is stored as one loop that joins the hole to the outer boundary by a doubled edge, the counts change: the doubled edge adds an edge and the ring disappears. Count rings as , and use faces that are disks with holes.
- Orientation of the rings. The outer loop and the rings of a face must turn in opposite directions. If a ring has the direction of the outer loop, the edges of that ring are used twice in one direction, and line L3 fails.
- A reversed inner shell. If the shell of a cavity has its normals pointing away from the cavity, the cavity adds volume instead of taking it away, and the total volume is still positive. The sign of the total does not find this error. A check must test a point of each inner shell against the shells around it.
- Floating point. The planarity test of line L12 and the volume sign of line L13 are sign tests. With floating-point coordinates, a face that is planar in exact arithmetic can fail the test, and a nearly flat shell can get the wrong sign. Use integer or rational coordinates, or a tolerance that the whole system agrees on.
- Non-manifold input. Two cubes that share an edge have an edge with four faces, and two cubes that share a vertex have a vertex with two fans. A half-edge B-rep cannot store either, so the build or the check must reject them, as lines L3 and L9 do.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-representation/. The authors are listed in prov/MR3WHM.jsonl.
"""A half-edge boundary representation (B-rep) of a polyhedral solid.
The topology is the hierarchy solid > shell > face > loop > half-edge > vertex.
A face is a list of loops: the first loop is the outer boundary and the other
loops are rings (holes in the face). Each loop is a list of vertex indices in
the order that keeps the face on the left when seen from outside the solid, so
the outer loop runs counterclockwise and the rings clockwise. This is the
right-hand rule: the fingers follow the loop and the thumb points out.
Coordinates are int or Fraction, and every geometric test is exact.
"""
from collections import Counter
from fractions import Fraction
from typing import Sequence, Union
Num = Union[int, Fraction]
Point = tuple[Num, Num, Num]
class InvalidBRep(ValueError):
"""The input does not describe a valid polyhedral solid."""
def _sub(a: Point, b: Point) -> Point:
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def _dot(a: Point, b: Point) -> Num:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _cross(a: Point, b: Point) -> Point:
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def newell(points: Sequence[Point]) -> Point:
"""Twice the vector area of a closed polygon: the sum of p_i x p_(i+1)."""
sx = sy = sz = 0
k = len(points)
for i in range(k):
c = _cross(points[i], points[(i + 1) % k])
sx, sy, sz = sx + c[0], sy + c[1], sz + c[2]
return (sx, sy, sz)
class BRep:
"""Half-edge B-rep. Half-edge h has origin, twin, next, prev and loop."""
def __init__(self, points: Sequence[Point], faces: Sequence[Sequence[Sequence[int]]]) -> None:
"""Build the structure from vertex points and faces given as lists of loops.
Raises InvalidBRep if a directed edge is used twice (a face is reversed
or more than two faces meet at an edge) or if an edge has only one face.
Time O(n) expected for n half-edges, with one hash map.
"""
self.points: list[Point] = [tuple(p) for p in points]
self.origin: list[int] = []
self.twin: list[int] = []
self.next: list[int] = []
self.prev: list[int] = []
self.loop: list[int] = []
self.loop_face: list[int] = [] # the face of each loop
self.loop_edge: list[int] = [] # one half-edge of each loop
self.face_loops: list[list[int]] = [] # the loops of each face, outer loop first
self.out: list[int] = [-1] * len(self.points) # one half-edge out of each vertex
self.key: dict[tuple[int, int], int] = {}
for f, loops in enumerate(faces): # @line L1
if not loops:
raise InvalidBRep(f"face {f} has no loop")
self.face_loops.append([])
for verts in loops:
k = len(verts)
if k < 3 or len(set(verts)) != k:
raise InvalidBRep(f"face {f} has a loop with fewer than 3 distinct vertices")
lp = len(self.loop_face)
self.loop_face.append(f)
self.face_loops[f].append(lp)
first = len(self.origin)
self.loop_edge.append(first)
for i, u in enumerate(verts): # @line L2
v = verts[(i + 1) % k]
if not (0 <= u < len(self.points)):
raise InvalidBRep(f"vertex {u} does not exist")
if (u, v) in self.key:
raise InvalidBRep(f"the directed edge {u}->{v} is used twice")
h = len(self.origin) # @line L3
self.key[(u, v)] = h
self.origin.append(u)
self.loop.append(lp)
self.twin.append(-1)
self.next.append(first + (i + 1) % k) # @line L4
self.prev.append(first + (i - 1) % k)
for (u, v), h in self.key.items(): # @line L5
t = self.key.get((v, u))
if t is None:
raise InvalidBRep(f"the edge {u}-{v} has only one face")
self.twin[h] = t
for h, u in enumerate(self.origin): # @line L6
if self.out[u] < 0:
self.out[u] = h
# ------------------------------------------------------------ queries
def face(self, h: int) -> int:
"""The face on the left of half-edge h. O(1)."""
return self.loop_face[self.loop[h]]
def loop_vertices(self, lp: int) -> list[int]:
"""The vertices of loop lp in order. O(length of the loop)."""
out = []
h = self.loop_edge[lp]
while True:
out.append(self.origin[h])
h = self.next[h]
if h == self.loop_edge[lp]:
return out
def face_boundary(self, f: int) -> list[list[int]]:
"""The loops of face f as vertex lists, outer loop first."""
return [self.loop_vertices(lp) for lp in self.face_loops[f]]
def edge_faces(self, u: int, v: int) -> tuple[int, int]:
"""The faces on the left and on the right of the edge from u to v. O(1) expected."""
h = self.key[(u, v)]
return self.face(h), self.face(self.twin[h])
def outgoing(self, v: int) -> list[int]:
"""The half-edges out of v, counterclockwise seen from outside. O(degree)."""
start = self.out[v]
if start < 0:
return []
res = []
h = start
while True: # @line L7
res.append(h)
h = self.twin[self.prev[h]]
if h == start:
return res
def faces_around(self, v: int) -> list[int]:
"""The faces at vertex v in cyclic order (a face is listed once per corner)."""
return [self.face(h) for h in self.outgoing(v)]
def neighbors(self, v: int) -> list[int]:
"""The vertices joined to v by an edge, in cyclic order."""
return [self.origin[self.twin[h]] for h in self.outgoing(v)]
def adjacent_faces(self, f: int) -> set[int]:
"""The faces that share an edge with face f."""
res = set()
for lp in self.face_loops[f]:
h = self.loop_edge[lp]
while True:
res.add(self.face(self.twin[h]))
h = self.next[h]
if h == self.loop_edge[lp]:
break
return res
def shells(self) -> list[list[int]]:
"""The shells: the components of the faces, linked across edges."""
seen = [False] * len(self.face_loops)
res = []
for f0 in range(len(self.face_loops)):
if seen[f0]:
continue
seen[f0] = True
comp, stack = [], [f0]
while stack:
f = stack.pop()
comp.append(f)
for g in self.adjacent_faces(f):
if not seen[g]:
seen[g] = True
stack.append(g)
res.append(sorted(comp))
return res
def volume(self) -> Fraction:
"""The signed volume, (1/6) sum over faces of q_f . (sum of p_i x p_(i+1)) over all loops."""
total = 0
for f in range(len(self.face_loops)):
loops = [[self.points[v] for v in vs] for vs in self.face_boundary(f)]
q = loops[0][0]
for pts in loops:
total += _dot(q, newell(pts))
return Fraction(total, 6)
# ------------------------------------------------------------ validity
def validate(self) -> dict[str, int]:
"""Check the topology and the exact geometry; return the counts V, E, F, L, R, S, H.
Raises InvalidBRep on the first failed check. It does not test that
faces of different shells, or far-apart faces, do not intersect.
"""
n = len(self.origin)
for h in range(n): # @line L8
t = self.twin[h]
if self.twin[t] != h or t == h or self.origin[t] != self.origin[self.next[h]]:
raise InvalidBRep(f"half-edge {h} has a bad twin")
degree = Counter(self.origin)
for v in range(len(self.points)): # @line L9
if degree[v] == 0:
raise InvalidBRep(f"vertex {v} is on no face")
if len(self.outgoing(v)) != degree[v]:
raise InvalidBRep(f"vertex {v} is non-manifold: its faces make more than one fan")
shells = self.shells() # @line L10
holes = 0
for comp in shells: # @line L11
loops = sum(len(self.face_loops[f]) for f in comp)
hs = [self.loop_edge[lp] for f in comp for lp in self.face_loops[f]]
half = []
for h in hs:
g = h
while True:
half.append(g)
g = self.next[g]
if g == h:
break
verts = {self.origin[h] for h in half}
chi = len(verts) - len(half) // 2 + len(comp) - (loops - len(comp))
if chi > 2 or chi % 2:
raise InvalidBRep(f"a shell has V - E + F - R = {chi}, which is not 2 - 2g")
holes += (2 - chi) // 2
for f in range(len(self.face_loops)): # @line L12
loops = [[self.points[v] for v in vs] for vs in self.face_boundary(f)]
nrm = newell(loops[0])
if nrm == (0, 0, 0):
raise InvalidBRep(f"face {f} has a degenerate outer loop")
q = loops[0][0]
for i, pts in enumerate(loops):
if any(_dot(nrm, _sub(p, q)) != 0 for p in pts):
raise InvalidBRep(f"face {f} is not planar")
if i > 0 and _dot(nrm, newell(pts)) >= 0:
raise InvalidBRep(f"a ring of face {f} has the orientation of the outer loop")
for comp in shells: # @line L13
sub = 0
for f in comp:
loops = [[self.points[v] for v in vs] for vs in self.face_boundary(f)]
sub += sum(_dot(loops[0][0], newell(pts)) for pts in loops)
if sub == 0:
raise InvalidBRep("a shell encloses no volume")
if self.volume() <= 0:
raise InvalidBRep("the solid has no positive volume: the faces point inward")
nf = len(self.face_loops)
nl = len(self.loop_face)
return {"V": len(self.points), "E": n // 2, "F": nf, "L": nl, "R": nl - nf, "S": len(shells), "H": holes}
test_boundary_representation.py 333 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-representation/. The authors are listed in prov/MR3WHM.jsonl.
import random
from fractions import Fraction
from itertools import product
import pytest
from boundary_representation import BRep, InvalidBRep, newell
# ---- building solids from coordinates ----
def rect(axis, c, a0, a1, b0, b1, normal):
"""The rectangle at coordinate c on axis, spanning [a0, a1] x [b0, b1] on the two other
axes, as a loop of points whose Newell normal points along normal * e_axis."""
b, d = (axis + 1) % 3, (axis + 2) % 3
def pt(s, t):
p = [0, 0, 0]
p[axis], p[b], p[d] = c, s, t
return tuple(p)
loop = [pt(a0, b0), pt(a1, b0), pt(a1, b1), pt(a0, b1)]
return loop if normal > 0 else loop[::-1]
def box(lo, hi, sign=1):
"""The 6 faces of the box [lo, hi], each one loop; sign -1 makes the normals point in."""
faces = []
for axis in range(3):
b, d = (axis + 1) % 3, (axis + 2) % 3
for end, nrm in ((lo[axis], -1), (hi[axis], 1)):
faces.append([rect(axis, end, lo[b], hi[b], lo[d], hi[d], nrm * sign)])
return faces
def make(coord_faces):
"""Index the points of faces given by coordinates and build the B-rep."""
ids, pts = {}, []
faces = []
for loops in coord_faces:
face = []
for loop in loops:
lp = []
for p in loop:
if p not in ids:
ids[p] = len(pts)
pts.append(p)
lp.append(ids[p])
face.append(lp)
faces.append(face)
return BRep(pts, faces), pts, faces
def frame():
"""The square frame [0, 3] x [0, 3] x [0, 1] with the hole (1, 2) x (1, 2): genus 1."""
fs = []
for z, nrm in ((0, -1), (1, 1)):
outer = rect(2, z, 0, 3, 0, 3, nrm)
ring = rect(2, z, 1, 2, 1, 2, -nrm)
fs.append([outer, ring])
for axis in (0, 1):
b, d = (axis + 1) % 3, (axis + 2) % 3
other = 1 - axis # the in-plane axis that is not z
for c, nrm, span in ((0, -1, (0, 3)), (3, 1, (0, 3)), (1, 1, (1, 2)), (2, -1, (1, 2))):
lo = {other: span[0], 2: 0}
hi = {other: span[1], 2: 1}
fs.append([rect(axis, c, lo[b], hi[b], lo[d], hi[d], nrm)])
return fs
def boss():
"""A 4 x 4 x 1 plate with a 2 x 2 x 1 block on top: the top face of the plate has a ring."""
fs = [f for f in box((0, 0, 0), (4, 4, 1)) if newell(f[0][0:4])[2] <= 0]
fs.append([rect(2, 1, 0, 4, 0, 4, 1), rect(2, 1, 1, 3, 1, 3, -1)])
fs += [f for f in box((1, 1, 1), (3, 3, 2)) if newell(f[0])[2] >= 0]
return fs
# ---- the examples of the page ----
def test_cube():
b, _, _ = make(box((0, 0, 0), (1, 1, 1)))
assert b.validate() == {"V": 8, "E": 12, "F": 6, "L": 6, "R": 0, "S": 1, "H": 0}
assert b.volume() == 1
for v in range(8):
assert len(b.neighbors(v)) == 3 and len(set(b.faces_around(v))) == 3
for f in range(6):
assert len(b.adjacent_faces(f)) == 4
def test_frame_has_one_hole():
b, _, _ = make(frame())
c = b.validate()
assert c == {"V": 16, "E": 24, "F": 10, "L": 12, "R": 2, "S": 1, "H": 1}
assert c["V"] - c["E"] + c["F"] - (c["L"] - c["F"]) - 2 * (c["S"] - c["H"]) == 0
assert b.volume() == 8
def test_boss_has_a_ring():
b, _, _ = make(boss())
assert b.validate() == {"V": 16, "E": 24, "F": 11, "L": 12, "R": 1, "S": 1, "H": 0}
assert b.volume() == 20
def test_cavity_has_two_shells():
b, _, _ = make(box((0, 0, 0), (3, 3, 3)) + box((1, 1, 1), (2, 2, 2), -1))
assert b.validate() == {"V": 16, "E": 24, "F": 12, "L": 12, "R": 0, "S": 2, "H": 0}
assert b.volume() == 26
def test_fraction_coordinates():
h = Fraction(1, 3)
b, _, _ = make(box((0, 0, 0), (h, 1, 2)))
assert b.validate()["H"] == 0
assert b.volume() == Fraction(2, 3)
# ---- invalid input ----
def test_open_surface_is_rejected():
with pytest.raises(InvalidBRep, match="only one face"):
make(box((0, 0, 0), (1, 1, 1))[:5])
def test_reversed_face_is_rejected():
fs = box((0, 0, 0), (1, 1, 1))
fs[0] = [fs[0][0][::-1]]
with pytest.raises(InvalidBRep, match="used twice"):
make(fs)
def test_inside_out_is_rejected():
b, _, _ = make(box((0, 0, 0), (1, 1, 1), -1))
with pytest.raises(InvalidBRep, match="inward"):
b.validate()
def test_non_planar_face_is_rejected():
fs = box((0, 0, 0), (2, 2, 2))
b, pts, faces = make(fs)
v = pts.index((2, 2, 2))
pts2 = list(pts)
pts2[v] = (3, 3, 3)
with pytest.raises(InvalidBRep, match="not planar"):
BRep(pts2, faces).validate()
def test_cubes_on_an_edge_are_rejected():
with pytest.raises(InvalidBRep, match="used twice"):
make(box((0, 0, 0), (1, 1, 1)) + box((1, 1, 0), (2, 2, 1)))
def test_cubes_on_a_vertex_are_rejected():
b, _, _ = make(box((0, 0, 0), (1, 1, 1)) + box((1, 1, 1), (2, 2, 2)))
with pytest.raises(InvalidBRep, match="non-manifold"):
b.validate()
def test_wrong_ring_orientation_is_rejected():
fs = frame()
fs[1] = [fs[1][0], fs[1][1][::-1]]
with pytest.raises(InvalidBRep):
make(fs)[0].validate()
# ---- random voxel solids against a scan of the face list ----
DIRS = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
def voxel_faces(cells):
"""The boundary squares of a set of unit cells, each oriented outward."""
fs = []
for c in sorted(cells):
for d in DIRS:
nb = (c[0] + d[0], c[1] + d[1], c[2] + d[2])
if nb in cells:
continue
axis = [i for i in range(3) if d[i]][0]
sgn = d[axis]
b, e = (axis + 1) % 3, (axis + 2) % 3
pos = c[axis] + (1 if sgn > 0 else 0)
fs.append([rect(axis, pos, c[b], c[b] + 1, c[e], c[e] + 1, sgn)])
return fs
def well_composed(cells, n):
"""No critical configuration: no diagonal pair of cells around an edge, and no
2 x 2 x 2 block with only two opposite cells full or only two opposite cells empty."""
def full(p):
return p in cells
for axis in range(3):
b, e = (axis + 1) % 3, (axis + 2) % 3
for base in product(range(-1, n + 1), repeat=3):
q = [[None, None], [None, None]]
for i, j in product((0, 1), repeat=2):
p = list(base)
p[b] += i
p[e] += j
q[i][j] = full(tuple(p))
if q[0][0] == q[1][1] and q[0][1] == q[1][0] and q[0][0] != q[0][1]:
return False
for base in product(range(-1, n + 1), repeat=3):
blk = {(i, j, k): full((base[0] + i, base[1] + j, base[2] + k)) for i, j, k in product((0, 1), repeat=3)}
cnt = sum(blk.values())
for i, j, k in product((0, 1), repeat=3):
a, o = blk[(i, j, k)], blk[(1 - i, 1 - j, 1 - k)]
if cnt == 2 and a and o:
return False
if cnt == 6 and not a and not o:
return False
return True
def components(cells):
"""The number of 6-connected components of a set of cells (flood fill)."""
seen, count = set(), 0
for c in cells:
if c in seen:
continue
count += 1
seen.add(c)
stack = [c]
while stack:
x = stack.pop()
for d in DIRS:
y = (x[0] + d[0], x[1] + d[1], x[2] + d[2])
if y in cells and y not in seen:
seen.add(y)
stack.append(y)
return count
def cubical_euler(cells):
"""V - E + F - C of the union of the closed unit cubes."""
verts, edges, squares = set(), set(), set()
for c in cells:
x, y, z = c
for i, j, k in product((0, 1), repeat=3):
verts.add((2 * (x + i), 2 * (y + j), 2 * (z + k)))
for axis in range(3):
for i, j in product((0, 1), repeat=2):
p = [2 * x, 2 * y, 2 * z]
p[axis] += 1
p[(axis + 1) % 3] += 2 * i
p[(axis + 2) % 3] += 2 * j
edges.add(tuple(p))
q = [2 * x + 1, 2 * y + 1, 2 * z + 1]
q[axis] = 2 * (c[axis] + i)
squares.add(tuple(q))
return len(verts) - len(edges) + len(squares) - len(cells)
def scan_checks(b, pts, faces):
"""Each query of the B-rep against a direct scan of the input face list."""
used = {}
for f, loops in enumerate(faces):
for loop in loops:
for i, u in enumerate(loop):
used[(u, loop[(i + 1) % len(loop)])] = f
assert b.face_boundary(0) == faces[0]
for f, loops in enumerate(faces):
assert b.face_boundary(f) == loops
scan_adj = {used[(v, u)] for (u, v), g in used.items() if g == f}
assert b.adjacent_faces(f) == scan_adj
for (u, v), f in used.items():
assert b.edge_faces(u, v) == (f, used[(v, u)])
for v in range(len(pts)):
scan_nb = {w for (u, w) in used if u == v}
nb = b.neighbors(v)
assert len(nb) == len(scan_nb) and set(nb) == scan_nb
scan_faces = sorted(f for (u, w), f in used.items() if u == v)
fa = b.faces_around(v)
assert sorted(fa) == scan_faces
# the edge to the next neighbor lies between consecutive faces around v
for i, w in enumerate(nb):
w_next = nb[(i + 1) % len(nb)]
assert used[(v, w)] == fa[i]
assert used[(w_next, v)] == fa[i]
def random_cells(rng, k):
"""Random cells: a random subset of a cube for even k, a drilled plate for odd k."""
if k % 2 == 0:
n = rng.choice((2, 3, 3, 4))
p = rng.choice((0.4, 0.6, 0.8))
return {c for c in product(range(n), repeat=3) if rng.random() < p}, n
dims = (rng.choice((3, 4, 5)), rng.choice((3, 4, 5)), rng.choice((1, 2, 3)))
drill = {(x, y) for x in range(1, dims[0] - 1) for y in range(1, dims[1] - 1) if rng.random() < 0.4}
cells = {c for c in product(*(range(d) for d in dims)) if (c[0], c[1]) not in drill and rng.random() >= 0.05}
if min(dims) >= 3 and rng.random() < 0.5: # a cavity of one cell
cells.discard(tuple(rng.randrange(1, d - 1) for d in dims))
return cells, max(dims)
def test_random_voxel_solids():
rng = random.Random(20260)
tested = rejected = with_holes = with_cavities = 0
k = 0
while tested < 600:
k += 1
cells, n = random_cells(rng, k)
if not cells:
continue
wc = well_composed(cells, n)
try:
b, pts, faces = make(voxel_faces(cells))
counts = b.validate()
ok = True
except InvalidBRep:
ok = False
assert ok == wc
if not ok:
rejected += 1
continue
tested += 1
empty = {c for c in product(range(-1, n + 1), repeat=3) if c not in cells}
shells = components(cells) + components(empty) - 1
holes = shells - cubical_euler(cells)
assert counts["S"] == shells and counts["H"] == holes
assert counts["F"] == len(faces) and counts["R"] == 0
assert counts["V"] - counts["E"] + counts["F"] - counts["R"] == 2 * (counts["S"] - counts["H"])
assert b.volume() == len(cells)
scan_checks(b, pts, faces)
with_holes += counts["H"] > 0
with_cavities += counts["S"] > components(cells)
assert rejected > 0 and with_holes >= 50 and with_cavities >= 5
History
Baumgart's winged-edge polyhedron of 1972 and 1975 was the first edge-based boundary structure; he made it for computer vision. In the 1970s, the BUILD modeler of Braid's group in Cambridge and other early systems stored solids by their faces, edges and vertices. Requicha's 1980 survey put the boundary representation into his theory of representation schemes, with validity and unambiguity as formal properties. Weiler compared the edge-based structures in 1985 and showed which adjacency queries each one answers in constant time. Mäntylä's book of 1988 gives the half-edge structure with loops that this page uses, and builds a modeler on it with Euler operators.
References
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, Chapter 6, Boundary models (p. 101; Section 6.2, Boundary data structures, p. 102; Section 6.2.4, Faces with several boundaries, p. 108; Section 6.3, Validity of boundary models, p. 110), and Chapter 10, Half-edge data structure (p. 161)
- Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the section on boundary representations, their validity, and the properties of the scheme
- Christoph M. Hoffmann, Geometric and Solid Modeling, An Introduction, Morgan Kaufmann, 1989, Chapter 2, Basic Concepts (boundary representation and the face, edge and vertex adjacencies)
- Kevin Weiler, Edge-based data structures for solid modeling in curved-surface environments, IEEE Computer Graphics and Applications 5(1), 21 to 40, 1985, the adjacency relations between vertices, edges and faces, and which of them each edge-based structure gives in constant time
- Bruce G. Baumgart, A polyhedron representation for computer vision, Proceedings of the AFIPS National Computer Conference 44, 589 to 596, 1975, the winged-edge polyhedron, the first edge-based boundary structure
Where this leads
- Blending surface
- Boundary evaluation
- B-rep healing
- B-rep reconstruction from segmented scans
- B-rep to CSG conversion
- Direct modeling
- Euler operators
- Euler-Poincare formula for solids
- Feature-based modeling
- Feature recognition
- Generic naming of topological entities
- Hint-based feature recognition
- Mass properties of solids
- Medial surface of a solid
- Mirtich's polyhedral mass properties
- Surface meshing in parametric space
- Persistent naming problem
- Radial edge data structure
- Reverse engineering of geometric models
- Boolean operations on solids
- Tolerant modeling
- Trimmed surface
- Vertex neighborhood classification
- Winged-edge data structure
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag MR3WHM Edit this page History Report an error Markdown