Data structureadvanced
Radial edge data structure
Also called Weiler radial edge.
Weiler's structure for non-manifold solids that orders the faces around each edge radially, so wire edges, sheets and solids sharing an edge can be stored.
- Time
- O(n m) expected
- Space
- Θ(n) extra
- Where
- m = the largest number of faces at one edge; n = the sum of the face sizes, so the number of edgeuses is 2n
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
The radial edge data structure stores the boundary of a non-manifold model: solids that share an edge or a vertex, sheets with free edges, and wire edges, all in one structure. Kevin Weiler gave it in his 1986 thesis. A winged edge or a half-edge B-rep stores exactly two faces at each edge, so it can store only a manifold solid. The radial edge structure stores the uses of each cell: each face has two faceuses, one for each side, and each edge has one edgeuse for each side of each face at it. Around each edge, the faces are kept in their angular order, and each edgeuse points to the edgeuse of the next face that faces the same wedge of space. This page builds the structure for planar faces with exact integer points, and inserts each new face into the angular order at each of its edges with a sign test.
In plain words
Think of a book that lies open with its pages spread out around the spine. Each page has two sides, and the space between two pages next to each other is a wedge. A plain B-rep can store only a book with two pages, the front and the back of one closed box. The radial edge structure can store any number of pages at one spine.
For each side of each page, the structure keeps a record at the spine. That record knows the record on the other side of the same page, and the record on the side of the next page that looks into the same wedge. If you go from page to page through these records, you go once around the spine in order. The pages can belong to boxes that touch along the spine, to single sheets of paper, or to both.
The abstract type
The structure stores a set of vertices with points, a set of planar faces, and wire edges, and it answers adjacency queries about them.
- : add a planar face given as a list of vertices, counterclockwise about its normal. Fail if a side of lies on the same half-plane as a face that is already at that edge.
- : add an edge with no face.
- : the faces at in counterclockwise order about the direction of .
- , , and : the cells around a face and around a vertex.
- : the faceuses grouped into the parts of the boundary of a region that are connected across edges.
A faceuse is a face together with one of its two sides. The faceuse is on the side of the normal of , and is on the other side. Each region of space near the boundary is bounded by faceuses, not by faces: a sheet between two regions is in the boundary of both, once with each side.
Representation
The records are those of Weiler with the loops and the regions left out, because here each face has one loop and the regions are not computed:
| record | fields |
|---|---|
| vertex | its point and the list of edgeuses that start at (Weiler's vertexuses) |
| edge | its ends , , the number of faces at it, and one edgeuse that runs from to |
| face | its vertex list, its normal (Newell's sum, exact) and its faceuse |
| faceuse | its face, its side , its (the other side) and one edgeuse of its loop |
| edgeuse | its edge, its start vertex, its faceuse, and on the loop, and |
The loop of follows the vertex list of , and the loop of goes the other way. So each loop runs counterclockwise seen from the side of its faceuse, which is the orientation of a manifold B-rep seen from outside. For an edgeuse of face at edge :
- is the edgeuse of on the other side of . It runs the other way.
- is the edgeuse of the next face around on the side that faces the same wedge as . It also runs the other way.
Both are involutions without fixed points. A wire edge has two edgeuses with no faceuse, and each is the mate and the radial of the other.
The angular order is defined by the fin of each face at each edge: the direction , where runs along the edge from to . The fin is perpendicular to the edge and points from the edge into the face, because a loop that runs counterclockwise about has its face on its left. Let . Then the fin is counterclockwise of the fin by less than a half turn about exactly when , the orientation test in three dimensions. With integer points, all fins and determinants are integers.
Which use faces which wedge? Let if runs from to , and if not, so that . A quarter turn of counterclockwise about gives the direction , because is perpendicular to . So the side of faces the counterclockwise wedge exactly when , that is, when runs from to . The same holds for with . In both cases: the edgeuse that runs from to faces the wedge counterclockwise of its face, and its mate faces the wedge clockwise of it. This is the rule that the code uses.
Operations
RADIAL-FACES(e) ▷ the faces at e, counterclockwise about v₁ − v₀- 1
u₀ ← eu[e]; u ← u₀ ▷ eu[e] runs from v₀ to v₁ - 2
repeat output face(u) - 3
u ← mate[radial[u]] - 4
until u = u₀ ADD-FACE(f) ▷ f planar, counterclockwise about its normal N- 5
make f⁺ and f⁻: the edgeuses of f⁺ follow f, those of f⁻ go backwards; pair each with its mate - 6
for each side of f from p to q do - 7
e ← the edge {p, q}; make it with v₀ = p and v₁ = q if it is new - 8
x ← the edgeuse of f at e that runs from v₀ to v₁; y ← mate[x]; w ← N × (q − p) - 9
if e has no face then radial[x] ← y; radial[y] ← x; eu[e] ← x - 10
else u ← eu[e] - 11
while w is not inside the wedge from fin(u) counterclockwise to fin(radial[u]) do u ← mate[radial[u]] - 12
z ← radial[u]; radial[u] ← y; radial[y] ← u; radial[x] ← z; radial[z] ← x
Around an edge. Let the faces at be in counterclockwise order of their fins about , and let be the edgeuse of that runs from to , and . Then faces the wedge from to , and so does . The structure keeps , indices mod . So , and lines L1 to L4 visit once around. With one face, : the two sides of a free edge of a sheet face the same wedge, which is the whole turn around the edge.
Insert a face. Line L11 walks around the edge until it finds the wedge that contains the new fin . The test is exact:
- if , the wedge from to is less than a half turn, and is inside it if and ;
- if , the wedge is more than a half turn, and is inside it if it is not inside the wedge from to ;
- if and are opposite, is inside if , and if and are the same fin (one face), the wedge is the whole turn.
Line L12 then puts the new face between and : the wedge from to is cut into two, now pairs with and pairs with . Before any change, ADD-FACE checks each edge: it fails if a fin of the new face has the same direction as a fin already there, because then two faces overlap near the edge, and if an edge is a wire edge.
Shells. Two faceuses that are joined by a radial pointer face the same wedge at an edge, so they bound the same region near that edge. SHELLS joins the faceuses of and for every edgeuse with a union-find structure. The sets are the parts of the boundary of each region that are connected across edges. Weiler's shells are also connected at vertices, for example for the outside of two cubes that touch at one corner. To join these, a modeler must sort the faceuses around the vertex, which is the job of vertex neighbourhood classification. This page does not do it.
Example
Take two unit cubes, and , that share the edge from to , so . Four faces meet at :
| face | part of | fin direction | angle about | use that runs up | it faces |
|---|---|---|---|---|---|
| , the face of the first cube | first cube | 270° | the empty quarter , | ||
| , the face of the second cube | second cube | 0° | the second cube | ||
| , the face of the second cube | second cube | 90° | the empty quarter , | ||
| , the face of the first cube | first cube | 180° | the first cube |
The normals of the faces point out of their cubes, so the side is outside the first cube and is inside the second cube. The radial pointers join with (both face the empty quarter , ), with (both inside the second cube), with (the other empty quarter) and with (inside the first cube). RADIAL-FACES() returns .
SHELLS returns three sets: the 12 outer faceuses, which are joined through , the 6 inner faceuses of the first cube and the 6 inner faceuses of the second cube. A half-edge B-rep cannot store this model at all, because has four faces. If the two cubes touch only at the vertex , SHELLS returns four sets, because the two outer sets meet only at that vertex.
A book with three square pages on one spine is a model with sheets. Each page has free edges, where its two sides are radial to each other, so all six faceuses form one set. A wire edge added at a corner of a page is stored with no faceuse, and it does not change the shells.
Correctness
The structure keeps this invariant at each edge with faces: the edgeuses that run from to are , one per face, in strictly counterclockwise order of their fins, and and . With it, lines L1 to L4 list each face at once in order and stop after steps.
ADD-FACE keeps the invariant. The fins at have different directions, and the new fin has none of them, so lies strictly inside exactly one of the open wedges between consecutive fins, and the walk of line L11 finds it within steps. The sign tests of the wedge test are exact, so the choice is never wrong. Line L12 changes four radial pointers so that the new face sits between and , and the order stays counterclockwise. The loops and the mates of the new face are made once, in line L5, and no other loop changes. The full proof, with the wedge test and the claim about the side that each use faces, is in the proof file.
Proved here: the structure stores the topology and the radial order exactly for any set of planar faces that do not overlap near an edge. Not checked: that faces do not cross each other away from their edges, and that the model is the boundary of a set of regions. Those are geometric checks, as for any B-rep.
Proof: ADD-FACE keeps the faces at each edge in counterclockwise order, and radial joins the uses that face the same wedgefull
We use the pseudocode and the records of the page. All points are integer vectors. For an edge write . For a face with normal at , let be the direction in which runs along , and let the fin be . Write .
Lemma 1 (fins). is a nonzero vector perpendicular to , and it points from the edge into .
Proof. is planar with normal , and the edge lies in , so . The cross product of two nonzero perpendicular vectors is nonzero and perpendicular to both, so and . Seen from the tip of , the loop of runs counterclockwise, so the face is on the left of each side, and the left of in the plane with normal is the direction .
So all fins at lie in the plane through the origin perpendicular to . Orient so that points toward the viewer. For , is parallel to , and , where is the angle that turns to counterclockwise about .
Lemma 2 (wedge test). Let be nonzero, with in the direction of neither nor . The wedge test of the page (the function inside_wedge of the code) returns true exactly when lies in the open wedge that turns counterclockwise about from to , the whole turn if and have the same direction.
Proof. Let be the angle from to and the angle from to ; because is not in the direction of . The claim is that INSIDE is true exactly when , or when . If the function returns true. If , then , and holds exactly when and : if both angles are in , and if either , so , or , so the second sine is negative. These are the signs of and . If , then with , and exactly when , since . If , then , and fails exactly when is in the open wedge from to , which is less than a half turn, so the first case decides it with and swapped.
Lemma 3 (which side faces which wedge). Let be an edgeuse of a face at that runs from to . Then the side of the faceuse of faces the wedge counterclockwise of about , and the side of faces the wedge clockwise of it.
Proof. Let if runs from to and if not, so and . The direction a quarter turn counterclockwise of about is , and by the expansion of the double cross product and . So : the side of faces the counterclockwise wedge if , and the side of faces it if . If , then runs from to like , so is on , the side of . If , then runs from to and , which runs the other way, is on , the side of . In both cases the side of faces the counterclockwise wedge. The side of is the other side of , which faces the clockwise wedge.
Invariant R. For each edge with faces, let and . Then (a) are the edgeuses of that run from to , one for each face at , and ; (b) their fins are in strictly counterclockwise order about : no fin at lies in the open wedge from the fin of to the fin of ; (c) and . For a wire edge, its two edgeuses are the mate and the radial of each other. Also (d) for each face , the edgeuses of form one cycle under in the order of the vertex list, those of form the reverse cycle, and joins the use of each side of on with the use of the same side on .
Lemma 4 (RADIAL-FACES). Under R, lines L1 to L4 output the faces at once each in counterclockwise order and stop after steps.
Proof. Line L3 maps to by the definition in R, and by (a) the are different edgeuses on different faces with . The order is (b).
By (c) and Lemma 3, joins , which faces the wedge from to , with , which faces the wedge clockwise of , that is the same wedge. So radial joins exactly the pairs of uses that face the same wedge, and SHELLS joins faceuses that bound the same region near an edge.
Lemma 5 (ADD-FACE). If R holds and ADD-FACE() does not fail, then R holds after it, and no field of a face other than changes except four radial pointers at each edge of that already had faces.
Proof. Line L5 makes the edgeuses of and with the loops and mates of (d), and these fields are not changed later. Take a side of with edge , and let be the new use that runs from to and . If is new, line L9 sets and , and , so R holds for with : . If is a wire edge, ADD-FACE fails before any change. Otherwise has faces in the order of R, and the check before the changes makes sure that the new fin (Lemma 1) has none of their directions. The open wedges from to for cover minus the rays of the fins, without overlap, by (b); for the one wedge is the whole turn minus one ray. So exactly one wedge contains , and by Lemma 2 the test of line L11 is true for it and false for the others. Line L11 visits by Lemma 4, so it stops at the of that wedge within steps. Line L12 sets, with , the four pointers , , , . Now the sequence of R is : and , and the other steps did not change. This gives (a) with uses and (c). For (b), the wedge from to contained no fin other than , so the two new wedges, from to and from to , contain none, and the other wedges did not change. did not change and still runs from to . The sides of are on different edges, because the vertices of are distinct, so each edge gets exactly one new face, and the steps for different sides change different edges.
Theorem. After any sequence of ADD-WIRE and ADD-FACE calls that do not fail, RADIAL-FACES() outputs the faces at each edge once each in counterclockwise order about , joins exactly the edgeuses that face the same wedge, FACE-VERTICES and FACE-EDGES give the loop of each face, and each call stops. A failed call changes nothing.
Proof. R holds for the empty structure. ADD-WIRE makes a new edge with the pointers of R and fails before any change on an edge that exists. ADD-FACE keeps R by Lemma 5, and it checks the size, the distinct vertices, the area, the planarity, the wire edges and the fin directions before it changes anything. So R holds after each call by induction. Lemma 4 gives the output of RADIAL-FACES, the remark after it gives the radial claim, and (d) gives the face loops. Every loop in the code runs over a finite cycle or a finite list.
The tests check the same facts against a brute force that keeps only the face lists. For each edge it finds the faces by a scan and sorts their fins by an exact pseudo-angle with fractions, in a basis of the plane , which is a different method from the wedge test. For random sets of unit cubes in a grid, with the faces inserted in a random order, it also finds the shells by walking the cells of the grid around each edge, and compares them with SHELLS.
Complexity
Let be the sum of the face sizes, the number of faces at an edge, and the largest .
- ADD-FACE for a face with sides takes expected time for the hash map of the edges, plus time at each edge for the check of the fins and the walk of line L11. So building a model costs expected time, and when every edge has at most a constant number of faces, as in a manifold.
- RADIAL-FACES() takes time, FACE-VERTICES and FACE-EDGES take time linear in the size of the face, and the vertex queries take time linear in the number of edgeuses at the vertex.
- SHELLS takes time with union-find.
- Space: edgeuses with 7 fields each, two faceuses per face, and the edges and vertices. For a manifold, this is about twice the size of a half-edge structure, because each side of each face has its own loop. Lee and Lee report that their partial entity structure stores the same information in about half the space.
Variants
- Full radial edge. Weiler's structure also has loopuses for faces with holes, vertexuses as records, shells and regions as records, and the model at the top. A loop can be a single vertex, and a shell can be a single vertex or a wire.
- Compact variants. The partial entity structure of Lee and Lee keeps a use record only where the model is non-manifold, and so it is much smaller on models that are mostly manifold.
- Non-manifold Euler operators. Weiler's boundary graph operators and later work extend the Euler operators to wires, sheets and solids that touch, with the radial order kept by each operator.
- Cell complexes. Simplicial and cell complexes with incidence graphs store any dimension, and mesh arrangements store the cells of many intersecting meshes. They give up the edge-centred walks of the radial edge structure.
When to use it
Use the radial edge structure when a model must hold mixed dimensions or solids that touch: in non-manifold modelers, in finite element pre-processing where the regions of an assembly share faces, in the intermediate steps of solid Boolean operations, and in models that store the result of a Boolean before regularization. For a manifold solid, a half-edge or winged-edge structure uses about half the memory and does not need the radial sort.
Pitfalls
- Sides, not faces. A region is bounded by faceuses. Code that treats a face as one boundary element loses the information that a sheet separates two regions, or that both sides of a face bound the same region.
- The radial order needs exact tests. Two faces at a small angle can swap places with floating-point determinants, and then the radial pointers join faceuses that do not face the same wedge. Use integer or rational points, or an exact predicate.
- The direction of the edge. The rule that the use from to faces the counterclockwise wedge depends on the direction of the edge record. If the code compares fins about in one place and about in another, the order comes out reversed.
- Overlapping faces. Two faces whose fins have the same direction overlap near the edge. The radial order is then undefined, so reject them, or merge them first.
- Shells through vertices. Joining faceuses across edges does not join the parts of a region boundary that meet only at a vertex. Do not count regions from these sets without the vertex step.
- Memory. Each face has two loops and each edge has edgeuses. On large manifold meshes, the structure uses about twice the memory of a half-edge mesh.
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/radial-edge-data-structure/. The authors are listed in prov/X79HMJ.jsonl.
"""Weiler's radial edge structure for a non-manifold polyhedral boundary.
Each face f has two faceuses, one for each side: f+ on the side of its normal N
and f- on the other side. Each faceuse has a loop of edgeuses. The edgeuses of
f+ follow the vertex list of f, which is counterclockwise seen from the tip of
N, and those of f- go the other way. For an edgeuse x:
- mate(x) is the edgeuse of the same edge on the other side of the same face;
- radial(x) is the edgeuse of the next face around the edge that faces the
same wedge of space as x.
Around an edge e from v0 to v1, the faces are kept in counterclockwise order
about the direction v1 - v0. The edgeuse that runs from v0 to v1 faces the
wedge counterclockwise of its face. All tests are exact on integer points.
An edge can have any number of faces, also one (a free edge of a sheet), and
an edge with no face is a wire edge.
"""
from __future__ import annotations
from typing import Optional, Sequence
Vec = tuple[int, int, int]
class RadialEdgeError(ValueError):
"""The input does not fit the structure."""
def sub(p: Vec, q: Vec) -> Vec:
return (p[0] - q[0], p[1] - q[1], p[2] - q[2])
def cross(a: Vec, b: Vec) -> Vec:
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 dot(a: Vec, b: Vec) -> int:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def det(a: Vec, b: Vec, d: Vec) -> int:
"""The sign of det[a, b, d] says if b is counterclockwise of a about d."""
return dot(cross(a, b), d)
def inside_wedge(a: Vec, b: Vec, w: Vec, d: Vec) -> bool:
"""Is w strictly inside the wedge that turns counterclockwise about d from
the fin a to the fin b? The fins are perpendicular to d, and w has neither
the direction of a nor of b. If a and b have the same direction, the wedge
is the full turn."""
ab = det(a, b, d)
if ab == 0 and dot(a, b) > 0:
return True
if ab > 0:
return det(a, w, d) > 0 and det(w, b, d) > 0
if ab == 0:
return det(a, w, d) > 0
return not (det(b, w, d) > 0 and det(w, a, d) > 0)
def same_direction(a: Vec, b: Vec) -> bool:
return cross(a, b) == (0, 0, 0) and dot(a, b) > 0
class Face:
__slots__ = ("id", "verts", "normal", "use")
def __init__(self, fid: int, verts: list[int], normal: Vec) -> None:
self.id, self.verts, self.normal = fid, verts, normal
self.use: Optional[FaceUse] = None # the faceuse f+
class FaceUse:
__slots__ = ("face", "side", "mate", "eu")
def __init__(self, face: Face, side: int) -> None:
self.face, self.side = face, side
self.mate: Optional[FaceUse] = None
self.eu: Optional[EdgeUse] = None # one edgeuse of the loop
class Edge:
__slots__ = ("id", "v0", "v1", "eu", "n_faces")
def __init__(self, eid: int, v0: int, v1: int) -> None:
self.id, self.v0, self.v1 = eid, v0, v1
self.eu: Optional[EdgeUse] = None # an edgeuse that runs from v0 to v1
self.n_faces = 0
class EdgeUse:
__slots__ = ("id", "edge", "vertex", "fu", "next", "prev", "mate", "radial")
def __init__(self, uid: int, edge: Edge, vertex: int, fu: Optional[FaceUse]) -> None:
self.id, self.edge, self.vertex, self.fu = uid, edge, vertex, fu
self.next: Optional[EdgeUse] = None
self.prev: Optional[EdgeUse] = None
self.mate: Optional[EdgeUse] = None
self.radial: Optional[EdgeUse] = None
def head(self) -> int:
return self.edge.v1 if self.vertex == self.edge.v0 else self.edge.v0
class RadialEdge:
def __init__(self, points: Sequence[Sequence[int]]) -> None:
self.points: list[Vec] = [tuple(p) for p in points] # type: ignore[misc]
self.edges: list[Edge] = []
self.faces: list[Face] = []
self.edgeuses: list[EdgeUse] = []
self.key: dict[frozenset[int], Edge] = {}
self.vertex_uses: list[list[EdgeUse]] = [[] for _ in self.points] # edgeuses that start at v
# ----- geometry -----
def newell(self, verts: Sequence[int]) -> Vec:
"""Twice the vector area of the polygon, exact."""
n = (0, 0, 0)
k = len(verts)
for i in range(k):
c = cross(self.points[verts[i]], self.points[verts[(i + 1) % k]])
n = (n[0] + c[0], n[1] + c[1], n[2] + c[2])
return n
def fin(self, x: EdgeUse) -> Vec:
"""The direction from the edge of x into the face of x, perpendicular to the edge."""
face = x.fu.face
p, q = x.vertex, x.head()
if x.fu.side < 0:
p, q = q, p # the direction in which f+ uses the edge
return cross(face.normal, sub(self.points[q], self.points[p]))
def axis(self, e: Edge) -> Vec:
return sub(self.points[e.v1], self.points[e.v0])
# ----- building -----
def _new_edge(self, u: int, v: int) -> Edge:
e = Edge(len(self.edges), u, v)
self.edges.append(e)
self.key[frozenset((u, v))] = e
return e
def _new_use(self, e: Edge, vertex: int, fu: Optional[FaceUse]) -> EdgeUse:
x = EdgeUse(len(self.edgeuses), e, vertex, fu)
self.edgeuses.append(x)
self.vertex_uses[vertex].append(x)
return x
def add_wire(self, u: int, v: int) -> int:
"""Add a wire edge, an edge with no face. Returns the edge id."""
if u == v or frozenset((u, v)) in self.key:
raise RadialEdgeError("a wire edge needs two vertices that have no edge yet")
e = self._new_edge(u, v)
a, b = self._new_use(e, u, None), self._new_use(e, v, None)
a.next = a.prev = b
b.next = b.prev = a
a.mate = a.radial = b
b.mate = b.radial = a
e.eu = a
return e.id
def add_face(self, verts: Sequence[int]) -> int:
"""Add a planar face given counterclockwise about its normal, and put it
into the radial order of each of its edges. Returns the face id."""
verts = list(verts)
k = len(verts)
if k < 3 or len(set(verts)) != k:
raise RadialEdgeError("a face needs at least 3 distinct vertices")
normal = self.newell(verts)
if normal == (0, 0, 0):
raise RadialEdgeError("the face has zero area")
p0 = self.points[verts[0]]
if any(dot(normal, sub(self.points[v], p0)) != 0 for v in verts):
raise RadialEdgeError("the face is not planar")
# check every edge before any change, so that a failure leaves the structure as it was
for i in range(k):
p, q = verts[i], verts[(i + 1) % k]
e = self.key.get(frozenset((p, q)))
if e is None:
continue
if e.n_faces == 0:
raise RadialEdgeError("a face cannot use a wire edge")
w = cross(normal, sub(self.points[q], self.points[p]))
for x in self._edge_uses_forward(e):
if same_direction(self.fin(x), w):
raise RadialEdgeError("two faces lie on the same half-plane at an edge")
face = Face(len(self.faces), verts, normal)
self.faces.append(face)
plus, minus = FaceUse(face, 1), FaceUse(face, -1)
plus.mate, minus.mate = minus, plus
face.use = plus
ups, downs = [], []
for i in range(k): # @line L5
p, q = verts[i], verts[(i + 1) % k]
e = self.key.get(frozenset((p, q))) or self._new_edge(p, q)
ups.append(self._new_use(e, p, plus))
downs.append(self._new_use(e, q, minus))
for i in range(k):
ups[i].next, ups[i].prev = ups[(i + 1) % k], ups[i - 1]
downs[i].next, downs[i].prev = downs[i - 1], downs[(i + 1) % k]
ups[i].mate, downs[i].mate = downs[i], ups[i]
plus.eu, minus.eu = ups[0], downs[0]
for i in range(k): # @line L6
e = ups[i].edge # @line L7
p, q = verts[i], verts[(i + 1) % k]
x, y = (ups[i], downs[i]) if p == e.v0 else (downs[i], ups[i]) # @line L8
w = cross(normal, sub(self.points[q], self.points[p]))
if e.n_faces == 0: # @line L9
x.radial, y.radial = y, x
e.eu = x
else:
d = self.axis(e)
u = e.eu # @line L10
while not inside_wedge(self.fin(u), self.fin(u.radial), w, d): # @line L11
u = u.radial.mate
z = u.radial # @line L12
u.radial, y.radial = y, u
x.radial, z.radial = z, x
e.n_faces += 1
return face.id
def _edge_uses_forward(self, e: Edge) -> list[EdgeUse]:
"""The edgeuses of e that run from v0 to v1, one per face, in radial order."""
out = []
u0 = e.eu # @line L1
u = u0
while True:
out.append(u) # @line L2
u = u.radial.mate # @line L3
if u is u0: # @line L4
break
return out
# ----- queries -----
def edge(self, u: int, v: int) -> Optional[int]:
e = self.key.get(frozenset((u, v)))
return None if e is None else e.id
def edge_vertices(self, eid: int) -> tuple[int, int]:
e = self.edges[eid]
return e.v0, e.v1
def radial_faces(self, eid: int) -> list[int]:
"""The faces at the edge, counterclockwise about v1 - v0. O(number of faces)."""
e = self.edges[eid]
if e.n_faces == 0:
return []
return [x.fu.face.id for x in self._edge_uses_forward(e)]
def is_wire(self, eid: int) -> bool:
return self.edges[eid].n_faces == 0
def face_vertices(self, fid: int) -> list[int]:
out = []
x0 = self.faces[fid].use.eu
x = x0
while True:
out.append(x.vertex)
x = x.next
if x is x0:
break
return out
def face_edges(self, fid: int) -> list[int]:
out = []
x0 = self.faces[fid].use.eu
x = x0
while True:
out.append(x.edge.id)
x = x.next
if x is x0:
break
return out
def vertex_edges(self, v: int) -> list[int]:
return sorted({x.edge.id for x in self.vertex_uses[v]})
def vertex_faces(self, v: int) -> list[int]:
return sorted({x.fu.face.id for x in self.vertex_uses[v] if x.fu is not None})
def shells(self) -> list[set[tuple[int, int]]]:
"""The faceuses (face id, side) joined across edges by radial: each set
is the part of the boundary of one region that is connected through
edges. Wire edges are not in any set."""
parent: dict[tuple[int, int], tuple[int, int]] = {}
def find(a):
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
for f in self.faces:
parent[(f.id, 1)] = (f.id, 1)
parent[(f.id, -1)] = (f.id, -1)
for x in self.edgeuses:
if x.fu is not None:
a = find((x.fu.face.id, x.fu.side))
b = find((x.radial.fu.face.id, x.radial.fu.side))
parent[a] = b
groups: dict[tuple[int, int], set[tuple[int, int]]] = {}
for a in parent:
groups.setdefault(find(a), set()).add(a)
return list(groups.values())
def check(self) -> None:
"""Check the pointers and the radial order."""
for x in self.edgeuses:
if x.mate.mate is not x or x.radial.radial is not x:
raise RadialEdgeError("mate and radial must be involutions")
if x.mate.edge is not x.edge or x.radial.edge is not x.edge:
raise RadialEdgeError("mate and radial must stay on the edge")
if x.mate.vertex == x.vertex or x.radial.vertex == x.vertex:
raise RadialEdgeError("mate and radial must run the other way")
if x.next.prev is not x or x.next.vertex != x.head():
raise RadialEdgeError("the loop links do not agree")
if x.fu is not None:
if x.mate.fu is not x.fu.mate or x.next.fu is not x.fu:
raise RadialEdgeError("an edgeuse is on the wrong faceuse")
for e in self.edges:
if e.eu.vertex != e.v0:
raise RadialEdgeError("the edge must point to a use from v0 to v1")
if e.n_faces == 0:
continue
uses = self._edge_uses_forward(e)
if len(uses) != e.n_faces or len({x.fu.face.id for x in uses}) != e.n_faces:
raise RadialEdgeError("the radial cycle must meet each face once")
d = self.axis(e)
fins = [self.fin(x) for x in uses]
m = len(fins)
for i in range(m):
if m > 1 and any(inside_wedge(fins[i], fins[(i + 1) % m], fins[j], d) for j in range(m) if j not in (i, (i + 1) % m)):
raise RadialEdgeError("the radial order is not counterclockwise")
test_radial_edge_data_structure.py 291 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/radial-edge-data-structure/. The authors are listed in prov/X79HMJ.jsonl.
import random
import unittest
from fractions import Fraction
from radial_edge_data_structure import RadialEdge, RadialEdgeError
CUBE_FACES = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
def box_points(x0, y0, z0, s=1):
return [(x0, y0, z0), (x0 + s, y0, z0), (x0 + s, y0 + s, z0), (x0, y0 + s, z0),
(x0, y0, z0 + s), (x0 + s, y0, z0 + s), (x0 + s, y0 + s, z0 + s), (x0, y0 + s, z0 + s)]
def two_boxes(second, merge):
"""Two unit cubes; vertices of the second cube that equal a vertex of the first are merged."""
pts = box_points(0, 0, 0)
ids = []
for p in box_points(*second):
if merge and p in pts:
ids.append(pts.index(p))
else:
ids.append(len(pts))
pts.append(p)
faces = [list(f) for f in CUBE_FACES] + [[ids[v] for v in f] for f in CUBE_FACES]
return pts, faces
# ----- the brute force: face lists, scans and a sort by an exact pseudo-angle -----
def sub(p, q):
return tuple(a - b for a, b in zip(p, q))
def cross(a, b):
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 dot(a, b):
return sum(x * y for x, y in zip(a, b))
def area_normal(points, verts):
n = (0, 0, 0)
for i in range(len(verts)):
a, b, c = points[verts[0]], points[verts[i - 1]], points[verts[i]]
t = cross(sub(b, a), sub(c, a))
n = tuple(x + y for x, y in zip(n, t))
return n
def pseudo_angle(x, y):
"""A strictly increasing function of the angle of (x, y) in [0, 4), exact."""
if y >= 0:
return Fraction(y, x + y) if x >= 0 else 1 + Fraction(-x, -x + y)
return 2 + Fraction(-y, -x - y) if x < 0 else 3 + Fraction(x, x - y)
def scan_radial(points, faces, u, v):
"""The faces that have the side {u, v}, sorted counterclockwise about v - u."""
d = sub(points[v], points[u])
axis = next(a for a in ((1, 0, 0), (0, 1, 0), (0, 0, 1)) if cross(d, a) != (0, 0, 0))
b1 = cross(d, axis)
b2 = cross(d, b1)
out = []
for f, c in enumerate(faces):
k = len(c)
for i in range(k):
p, q = c[i], c[(i + 1) % k]
if {p, q} == {u, v}:
w = cross(area_normal(points, c), sub(points[q], points[p]))
out.append((pseudo_angle(dot(w, b1), dot(w, b2)), f))
return [f for _, f in sorted(out)]
def rotation(cyc, start):
i = cyc.index(start)
return cyc[i:] + cyc[:i]
def compare(test, rs, points, faces, wires):
rs.check()
pairs = {frozenset((c[i], c[(i + 1) % len(c)])) for c in faces for i in range(len(c))}
pairs |= {frozenset(w) for w in wires}
test.assertEqual(len(rs.edges), len(pairs))
for pair in pairs:
u, v = sorted(pair)
e = rs.edge(u, v)
a, b = rs.edge_vertices(e)
want = scan_radial(points, faces, a, b)
got = rs.radial_faces(e)
test.assertEqual(sorted(got), sorted(want))
if want:
test.assertEqual(rotation(got, want[0]), want)
test.assertEqual(rs.is_wire(e), frozenset((u, v)) in {frozenset(w) for w in wires})
for f, c in enumerate(faces):
test.assertEqual(rotation(rs.face_vertices(f), c[0]), c)
test.assertEqual(sorted(rs.face_edges(f)), sorted(rs.edge(c[i], c[(i + 1) % len(c)]) for i in range(len(c))))
for v in range(len(points)):
test.assertEqual(rs.vertex_faces(v), [f for f, c in enumerate(faces) if v in c])
test.assertEqual(rs.vertex_edges(v), sorted(rs.edge(*sorted(p)) for p in pairs if v in p))
def build(points, faces, wires=(), order=None):
rs = RadialEdge(points)
for w in wires:
rs.add_wire(*w)
ids = {}
for f in order if order is not None else range(len(faces)):
ids[f] = rs.add_face(faces[f])
return rs, ids
# ----- voxel complexes and a grid walk for the shells -----
AXES = [(0, 1, 2), (1, 2, 0), (2, 0, 1)] # (a, b, c) with e_b x e_c = e_a
def voxel_faces(filled, n):
"""The boundary squares of a set of unit cells in an n by n by n grid, each
counterclockwise seen from the empty side. Returns (points, faces, sides),
where sides[f] = (filled cell, empty cell)."""
vid = {}
points = []
def pt(p):
if p not in vid:
vid[p] = len(points)
points.append(p)
return vid[p]
faces, sides = [], []
for cell in sorted(filled):
for a, b, c in AXES:
for s in (1, -1):
nb = list(cell)
nb[a] += s
nb = tuple(nb)
if nb in filled:
continue
corners = []
for db, dc in ((0, 0), (1, 0), (1, 1), (0, 1)):
p = [0, 0, 0]
p[a] = cell[a] + (1 if s > 0 else 0)
p[b], p[c] = cell[b] + db, cell[c] + dc
corners.append(pt(tuple(p)))
if s < 0:
corners.reverse()
faces.append(corners)
sides.append((cell, nb))
return points, faces, sides
def grid_shells(points, faces, sides, filled):
"""The faceuses joined across edges, found by walking the cells around each edge."""
face_of = {}
for f, (inn, out) in enumerate(sides):
face_of[(inn, out)] = f
face_of[(out, inn)] = f
parent = {(f, s): (f, s) for f in range(len(faces)) for s in (1, -1)}
def find(x):
while parent[x] != x:
x = parent[x]
return x
for f, c in enumerate(faces):
inn, out = sides[f]
for i in range(4):
p, q = points[c[i]], points[c[(i + 1) % 4]]
a = next(j for j in range(3) if p[j] != q[j])
b, cc = [j for j in range(3) if j != a]
lo = min(p[a], q[a])
ring = []
for db, dc in ((-1, -1), (0, -1), (0, 0), (-1, 0)):
cell = [0, 0, 0]
cell[a], cell[b], cell[cc] = lo, p[b] + db, p[cc] + dc
ring.append(tuple(cell))
for side, start, other in ((1, out, inn), (-1, inn, out)):
k = ring.index(start)
step = 1 if ring[(k - 1) % 4] == other else -1
cur = start
while True:
nxt = ring[(ring.index(cur) + step) % 4]
if (nxt in filled) != (cur in filled):
break
cur = nxt
g = face_of[(cur, nxt)]
gside = -1 if cur in filled else 1
parent[find((f, side))] = find((g, gside))
groups = {}
for x in parent:
groups.setdefault(find(x), set()).add(x)
return sorted(sorted(s) for s in groups.values())
def normalize(shells, ids=None):
back = {v: k for k, v in ids.items()} if ids else None
out = []
for s in shells:
out.append(sorted((back[f] if back else f, side) for f, side in s))
return sorted(out)
class RadialEdgeTests(unittest.TestCase):
def test_cube(self):
pts = box_points(0, 0, 0)
rs, _ = build(pts, CUBE_FACES)
compare(self, rs, pts, CUBE_FACES, [])
e = rs.edge(0, 3)
self.assertEqual(rs.radial_faces(e), [0, 5])
shells = normalize(rs.shells())
self.assertEqual(shells, [[(f, -1) for f in range(6)], [(f, 1) for f in range(6)]])
def test_two_cubes_on_an_edge(self):
pts, faces = two_boxes((1, 1, 0), merge=True) # they share the edge from (1,1,0) to (1,1,1)
rs, _ = build(pts, faces)
compare(self, rs, pts, faces, [])
e = rs.edge(2, 6)
self.assertEqual(len(rs.radial_faces(e)), 4)
self.assertEqual(len(rs.shells()), 3) # outside, and the inside of each cube
def test_two_cubes_at_a_vertex(self):
pts, faces = two_boxes((1, 1, 1), merge=True) # they share the vertex (1,1,1)
rs, _ = build(pts, faces)
compare(self, rs, pts, faces, [])
self.assertEqual(len(rs.vertex_faces(6)), 6)
self.assertEqual(len(rs.shells()), 4) # the outside is joined only through a vertex
def test_sheets_book_and_wire(self):
pts = [(0, 0, 0), (0, 0, 1), (1, 0, 0), (1, 0, 1), (-1, 1, 0), (-1, 1, 1), (0, -1, 0), (0, -1, 1), (3, 3, 3)]
book = [[0, 2, 3, 1], [1, 5, 4, 0], [0, 6, 7, 1]] # three pages on the spine 0-1
rs, _ = build(pts, book, wires=[(3, 8)])
compare(self, rs, pts, book, [(3, 8)])
spine = rs.edge(0, 1)
# page 0 uses the spine from 1 to 0 first, so the edge runs down, along -z
self.assertEqual(rs.edge_vertices(spine), (1, 0))
# the pages are at 0, 135 and 270 degrees about +z, so at 0, 90 and 225 about -z
self.assertEqual(rotation(rs.radial_faces(spine), 0), [0, 2, 1])
self.assertEqual(len(rs.shells()), 1) # free edges join the two sides of each page
self.assertTrue(rs.is_wire(rs.edge(3, 8)))
self.assertEqual(rs.vertex_faces(8), [])
def test_bad_input(self):
pts = box_points(0, 0, 0) + [(0, 5, 5)]
rs = RadialEdge(pts)
rs.add_face([0, 1, 2, 3])
with self.assertRaises(RadialEdgeError):
rs.add_face([0, 1, 2, 3]) # the same half-planes again
with self.assertRaises(RadialEdgeError):
rs.add_face([0, 1, 5, 8]) # not planar
with self.assertRaises(RadialEdgeError):
rs.add_face([0, 4, 0])
rs.add_wire(4, 8)
with self.assertRaises(RadialEdgeError):
rs.add_face([4, 8, 7]) # a face on a wire edge
with self.assertRaises(RadialEdgeError):
rs.add_wire(0, 1) # the edge has a face
rs.check()
self.assertEqual(len(rs.faces), 1)
def test_voxel_complexes(self):
rng = random.Random(1986)
n = 3
cells = [(i, j, k) for i in range(n) for j in range(n) for k in range(n)]
seen_four = 0
for trial in range(60):
filled = {c for c in cells if rng.random() < 0.45}
if not filled:
continue
points, faces, sides = voxel_faces(filled, n)
order = list(range(len(faces)))
rng.shuffle(order)
rot = [rng.randrange(4) for _ in faces]
faces = [c[r:] + c[:r] for c, r in zip(faces, rot)]
rs, ids = build(points, faces, order=order)
# the structure numbers faces in insertion order; renumber the brute force to match
back = [None] * len(faces)
for f, fid in ids.items():
back[fid] = faces[f]
compare(self, rs, points, back, [])
self.assertEqual(normalize(rs.shells(), ids), grid_shells(points, faces, sides, filled))
seen_four += sum(1 for e in range(len(rs.edges)) if len(rs.radial_faces(e)) == 4)
self.assertGreater(seen_four, 20)
if __name__ == "__main__":
unittest.main()
History
Weiler compared the edge-based structures for manifold solids in 1985 and defined the radial edge structure for non-manifold models in his 1986 thesis at Rensselaer Polytechnic Institute. He presented it at the IFIP working conference on geometric modeling in 1986, published in 1988 together with his boundary graph operators. Non-manifold modelers of the late 1980s and the 1990s used it or variants of it, and Lee and Lee gave the compact partial entity structure in 2001.
References
- Kevin J. Weiler, Topological Structures for Geometric Modeling, PhD thesis, Rensselaer Polytechnic Institute, Troy, New York, 1986 (also RPI Center for Interactive Computer Graphics, technical report TR-86032), the non-manifold topology, the faceuse, loopuse, edgeuse and vertexuse elements, and the radial edge structure
- Kevin Weiler, The radial edge structure, a topological representation for non-manifold geometric boundary modeling, in M. J. Wozny, H. W. McLaughlin and J. L. Encarnação (eds.), Geometric Modeling for CAD Applications, North-Holland, 1988, 3 to 36, the elements of the structure, the mate and radial pointers, and the adjacency relations it gives
- 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 edge-based manifold structures that the radial edge structure extends, and the sufficiency of their adjacency relations
- Sang Hun Lee and Kunwoo Lee, Partial entity structure, a compact non-manifold boundary representation based on partial topological entities, Proceedings of the Sixth ACM Symposium on Solid Modeling and Applications, 159 to 170, 2001, the storage of the radial edge structure and a compact variant with about half its size
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 X79HMJ Edit this page History Report an error Markdown