Data structureadvanced
Selective geometric complex
Also called SGC, Rossignac-O'Connor complex.
Rossignac and O'Connor's model of non-manifold and mixed-dimensional objects as a cell complex whose cells are each marked in or out, closed under Booleans.
- Time
- O((n + k)^2) worst
- Space
- O(n + k) extra
- Where
- k = the number of crossing points between the segments; n = the number of segments and points that cut the plane, over both operands
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
A selective geometric complex (SGC) stores a geometric object as a cell complex in which every cell is marked in or out. The cells are disjoint, connected and relatively open: points, open curve pieces, open surface pieces and open volumes, of any dimension and on curved supports. The object is the union of the marked cells. So one structure holds solids, solids with cracks or missing boundary, dangling faces and wires, and isolated points: every non-manifold and mixed-dimensional case that the r-sets of classical solid modeling exclude. Jarek Rossignac and Michael O'Connor introduced the SGC in 1989, with Boolean operations in three steps: subdivide both complexes until they are compatible, select the cells of the result by the Boolean rule, and simplify by merging cells whose marks agree. The set of objects that an SGC represents is closed under the Boolean operations and under interior, closure and boundary, with no regularization. This page builds the planar case from straight segments and points, with exact rational arithmetic, and proves that the operations are exact.
In plain words
Draw some straight strokes and dots on paper. They cut the paper into pieces: the dots and stroke ends, the bits of stroke between them, and the open regions between the strokes. Colour some pieces. The coloured pieces are the object. A coloured region with uncoloured edges is an open area; one coloured stroke is a wire; one coloured dot is a point.
To combine two objects, draw both sets of strokes on one sheet, so every new piece lies inside one piece of each object. Colour a new piece if the rule says so: in both, in either, in the first only. Then rub out every stroke and dot that has the same colour as everything around it. What is left is a small drawing of the answer. The inside of an object keeps a piece only if everything touching it is coloured too.
The abstract type
An SGC value is a point set in the plane, given with a complex that cuts the plane into cells. The operations are:
- Build a simple polygon, open or closed, a segment, open or closed, or a point.
- Booleans: union, intersection, difference, symmetric difference and complement, with no regularization.
- Topology: interior, closure, boundary, and regularization .
- Queries: does contain a point ; is empty; how many marked vertices, edges and faces it has.
- Simplify: merge the cells that need not be separate.
Two descriptions of the same set give equal values: after simplification they have the same marked cells, and emptiness of the symmetric difference tests equality in any case.
Representation
A complex is given by a finite set of segments and points. The code splits every segment at its endpoints, at its crossings with other segments, and at the given points that lie on it. The pieces are the edges, each an open segment, and their endpoints and the given points are the vertices. The faces are the connected components of the plane minus all edges and vertices. Faces may have holes, and a face may contain isolated vertices and dangling edges.
The face structure is that of a doubly connected edge list. Each edge gives two half-edges. At each vertex, the outgoing half-edges are sorted counterclockwise by an exact angle key. The next half-edge after is the one that leaves just clockwise of , so each traced cycle has its face on the left. A cycle of positive signed area is the outer boundary of a bounded face, and every bounded face has exactly one. Each other cycle, and each isolated vertex, is a hole and is placed in the face whose outer cycle is the innermost one around it, by winding numbers. Face 0 is the unbounded face. For each edge, the code records the faces on its two sides.
The star of a cell is the set of other cells whose closure contains . The star of an edge is the faces on its two sides. The star of a vertex is the edges that end at it with their faces, or, for an isolated vertex, the face around it. A face has an empty star. An SGC is a complex together with its set of marked cells.
Operations
COMBINE(A, B, op) ▷ op is or, and, minus or xor- 1
segs ← the edges of A and of B; pts ← the vertices of A and of B - 2
C ← the complex cut out by segs and pts ▷ every cell of C lies in one cell of A and one of B - 3
for each cell c of C do - 4
p ← a point inside c - 5
mark c if op(A contains p, B contains p) - 6
return SIMPLIFY(C, marks) SIMPLIFY(S)- 7
keep each edge whose mark differs from one of its two faces - 8
keep each vertex unless its kept edges are two collinear edges marked like it, or it has no kept edge and is marked like its whole star- 9
C' ← the complex cut out by the kept edges, merged along lines, and the kept vertices - 10
mark each cell c' of C' if S contains a point inside c'
Points inside cells. A vertex is its own point, and an edge gives its midpoint. For the unbounded face, the code takes a point to the right of every vertex. For a bounded face, it takes the first edge of the outer cycle, so the face is on the left of . It starts at the midpoint of and moves along the left normal. It finds the first edge or vertex that the ray meets, at parameter , and takes the point at .
Containment locates the cell of , checking vertices, then edges, then the innermost outer cycle that winds around . Then it looks up the mark.
Complement flips every mark on the same complex. Interior keeps the marked cells whose whole star is marked. Closure marks every cell that is marked or has a marked cell in its star. Both are simplified afterwards. Boundary is the closure minus the interior, and regularization is the closure of the interior.
Primitives. A polygon is the complex of its sides, with each cell marked by a direct test of its sample point: inside by winding number, or on a side if the polygon is closed. Segments and points are built the same way.
Example
Take the closed square and remove the open segment from to , a crack inside it. The result keeps the two crack ends, which are not in the open segment. Its complex has 6 vertices, 5 edges and 2 faces. The faces are the outside and the square minus the crack. The crack is a hole in the square's face, a cycle of zero area. The marks are 6 vertices, 4 edges and 1 face.
| set | vertices, edges, faces in the complex | marked vertices, edges, faces |
|---|---|---|
| 6, 5, 2 | 6, 4, 1 | |
| 6, 5, 2 | 0, 0, 1 | |
| 4, 4, 2 | 4, 4, 1 | |
| 6, 5, 2 | 6, 5, 0 | |
| 4, 4, 2 | 4, 4, 1 | |
| complement of | 6, 5, 2 | 0, 1, 1 |
The interior drops the crack ends, whose stars contain the unmarked crack. The closure fills the crack back in, and simplification removes it, since it is now marked like the face on both sides. The boundary is the square's outline, the crack and its two ends.
Unlike a Nef polygon, the SGC does not extend the crack to a full line. A Nef polygon for needs the lines , and across the whole plane, besides the four lines of the square. That is 7 lines, which cut the plane into 20 cells, against 2 faces here.
A second example shows the three steps. Take the closed squares and , which share the edge . The overlay at L2 has 6 vertices, 7 edges and 3 faces. For , all cells but the outside are marked. L7 drops the shared edge, whose mark equals both faces. L8 drops and , each between two collinear kept edges marked like it. The result is one rectangle: 4 vertices, 4 edges, 2 faces. For , the marked cells are the shared edge and its two ends, a segment, and its regularization is empty, as a regularized modeler would return.
Correctness
The proof file proves the following for the planar code.
- The complex is a cell decomposition. The vertices, open edges and faces are disjoint, connected and cover the plane. The traced cycles, with outer cycles and holes, give every face exactly once. Every point of a cell has a disc around it that meets only and the cells of its star.
- The overlay refines both inputs. The skeleton of , its edges and vertices, is contained in the skeleton of . So every cell of lies inside exactly one cell of and one of , and it is entirely in or entirely out of each. Lines L4 and L5 test one point, which decides the whole cell, so COMBINE returns exactly .
- Simplification keeps the set and is minimal. Every cell of the new complex is a union of old cells. All of those old cells have the same mark: they are joined through removed edges and vertices, and L7 and L8 remove only cells marked like their neighbours. So L10 reproduces the set. After one pass, every edge separates differently marked cells, and every vertex is a bend, an end, a junction, or marked unlike its star. So a second pass changes nothing.
- Interior and closure follow the star. This is the local structure of point 1, as for Nef polyhedra. So the sets that SGCs represent are closed under complement, the Booleans, interior, closure and boundary. The r-sets are not closed under these operations and need regularized operations.
The tests compare the code with the defining formula. They build a random formula of depth up to 3 over triangles, segments and points with integer corners in , each open or closed, combined by union, intersection, difference, symmetric difference and complement. They evaluate the formula directly at every point of a grid with step around the box, and at every vertex of the complex. Interior, closure and boundary are checked against an oracle that evaluates the formula at and at , for a fixed set of directions with one direction in every possible wedge. The tests also check that every simplified complex meets the minimality conditions, and that simplifying twice changes nothing.
Proof: The planar selective geometric complex is a cell decomposition, and its Booleans, topological operations and simplification are exactfull
We use the notation and the pseudocode of the page. A complex is cut out by a finite set of segments with distinct endpoints and a finite set of points. Its skeleton is the union of the closed segments and the points. Its cells are the vertices, the open edges and the faces, which are the connected components of . An SGC is a complex and a set of marked cells, and it represents the set .
Lemma 1 (cells). The vertices, edges and faces are pairwise disjoint, each is connected and they cover the plane. Two edges meet at most in a common endpoint, and no vertex lies on an open edge. The skeleton is the union of the vertices and edges.
Proof. A segment is cut at every point of that is an endpoint of , a crossing with a segment that is not parallel to it, an endpoint of another segment, or a point of . Let be consecutive cuts on . The open segment contains no point of . Suppose it meets another segment . If is not parallel to , the meeting point is their crossing, which is a cut. If is parallel, it lies on the same line, and the overlap is a segment whose endpoints are endpoints of or of . These are cuts, so the overlap cannot contain a point of without containing and . In that case is also a piece of between consecutive cuts: a cut of inside it would be a crossing, an endpoint or a point of , and so a cut of . Edges are stored with sorted endpoints in a set, so the two copies are one edge. Hence distinct edges are disjoint, and no vertex lies on an open edge. The vertices and the open edges cover . The faces are the components of the complement, which is open. Every cell is connected.
Lemma 2 (local structure). Let be a point of a cell . There is a disc around that meets only and the cells of its star, the cells with . Every cell of the star meets every such disc.
Proof. If is a face, take a disc in the open set . If is an edge, take a disc that misses every edge and vertex other than , possible because those closed sets do not contain by Lemma 1. The line of cuts into two open half-discs. Each is connected and misses , so it lies in one face, the face on that side. These are the faces of the star of . If is a vertex, take a disc that misses every closed edge not ending at and every other vertex. The edges that end at cut into open sectors, each in one face, and meets exactly , those edges and those faces. If no edge ends at , then is connected and lies in one face. Conversely, a face whose closure contains meets every disc around , and the cells met by small discs are exactly these.
Lemma 3 (faces from cycles). The half-edge cycles of the code, with the faces assigned as in the code, give each face of the complex exactly once. side[e] is the pair of faces beside , and star[c] is the star of .
Proof. Split the skeleton into its connected components , as plane graphs, with isolated points as single-vertex components. The rule , where is the half-edge just clockwise of around , is the face-tracing rule of a doubly connected edge list. For a connected plane graph with at least one edge, it traces each face of once, with the face on the left. The bounded faces of give cycles of positive signed area, equal to the area of the face. The unbounded face gives one cycle of signed area , with area when is a tree. (This is the standard result on boundary cycles, as in de Berg et al., chapter 2.) So the positive cycles are the outer boundaries of the bounded faces of the components. Let be the open region, the bounded face of its component, that a positive cycle bounds.
Now take two components and their positive cycles , . They are disjoint, so lies in one face of . Then , or , or the two are disjoint, because each is simply connected. So the regions around any point that come from components other than its own form a chain under inclusion, and the smallest has the least area. A face of the full complex is bounded by parts of some components. If is bounded, its outer boundary is a positive cycle of one component with . Every other boundary component of is a component inside , seen from outside through its non-positive cycle, or an isolated point. For a point of such a , is the smallest region around among the components other than , since any smaller one would separate from . The code assigns 's outer cycle and isolated points by exactly this rule: the innermost positive cycle with nonzero winding around , among the cycles not through . If no region contains , the hole lies in the unbounded face 0. So each face is listed once, as face 0 or as one positive cycle. Every half-edge gets the face on its left, so side is correct. The star of an edge is its two side faces. The star of a vertex is its incident edges with their sides, or the face around it if it is isolated. These are the stars of Lemma 2.
Lemma 4 (locate and sample). locate(p) returns the cell that contains , and sample(c) returns a point of .
Proof. For locate: the vertex and edge tests are direct. Otherwise is in a face. If that face is bounded with outer cycle , then . Every other positive cycle around has a region that is nested with , by the chain property of Lemma 3. A region strictly inside that contains would have its boundary inside 's outer boundary, separating from , which contradicts bounding . So is the innermost cycle. If no positive cycle winds around , then is in face 0.
For sample: a vertex is its own point. The midpoint of an open edge lies on it. For face 0, the point lies to the right of every vertex, and so of the whole skeleton, and it joins infinity by a horizontal ray that misses . For a bounded face, let be the first half-edge of its outer cycle. The face is on the left of , so the points for small lie in it, where is the midpoint and the left normal. The code collects the parameters at which the ray meets another edge or a vertex. It checks every edge, collinear edges by their endpoints and the others by a crossing test on a long prefix of the ray, and it checks every vertex on the ray line. Let be the least such parameter. Then the segment from to , without its end, misses , so the point at is in the face. If no hit lies within the prefix, the point at , which is inside the prefix, is in the face for the same reason.
Theorem 1 (Booleans). COMBINE returns an SGC that represents .
Proof. Every edge of is one of the segments of L1, and every vertex of is one of the points, so . Let be a cell of . If is a vertex, it is either a vertex of , a point of an open edge of , or a point of a face of . If is an open edge, then it lies on an edge of , and so inside it, because it contains no vertex of the vertices of . Otherwise it misses : it can meet a closed edge of only at a point that would be a cut (Lemma 1). Then, being connected, it lies in one face of . If is a face, it is connected and misses , so it lies in one face of . So every cell of lies in exactly one cell of . It is therefore contained in or disjoint from it, and the same holds for . Line L4 takes a point of (Lemma 4), and line L5 marks exactly when holds at that point, which is when . The cells partition the plane, so the marked cells form . Line L6 keeps the set by Theorem 3.
Theorem 2 (topological operations). For an SGC with marks , a cell lies in exactly when and its whole star are marked, and in exactly when or a cell of its star is marked. So interior, closure, boundary and regularization return the stated sets.
Proof. Let and let be the disc of Lemma 2. If and its star are marked, then . If some cell among them is unmarked, it meets every smaller disc around (Lemma 2), so is not interior. The rule depends only on , so the interior is a union of cells. The closure is the complement of the interior of the complement, which gives the second rule. The boundary is the closure minus the interior, computed by Theorem 1, and regularization composes the two. Simplification keeps the set (Theorem 3).
So the sets represented by planar SGCs are closed under complement, the four Booleans, interior, closure and boundary, with no regularization. The r-sets are not: two closed squares that share an edge are r-sets, and their intersection, the segment, is not.
Theorem 3 (simplification). SIMPLIFY returns an SGC that represents the same set. Its result satisfies the two conditions:
- (E) every edge has a mark that differs from that of one of its side faces;
- (V) every vertex either has a number of edges other than two, or two edges that are not collinear, or a mark that differs from that of one of its star cells.
So a second simplification keeps every cell.
Proof. The new skeleton is part of the old one. merge_collinear joins kept edges that lie on one line and share an endpoint. So the union of the merged segments is the union of the closed kept edges, and the new skeleton is the union of the closed kept edges and the kept vertices. It is a union of old cells, and every old cell lies in one new cell, by the argument of Theorem 1 with . An old open edge that is not kept is not in , since it meets other closed edges only at its ends.
Each new cell is uniformly marked. Let be a new cell and the old cells inside it.
- If is a new face, every old edge in was not kept, so by L7 it is marked like both its side faces. Every old vertex in is neither kept nor the end of a kept edge, so it had no kept edges and was not kept. By L8, it is marked like its whole star. Join two cells of when one is in the star of the other, which gives a graph on . Joined cells have equal marks. The union of the cells in a connected component of this graph is open in : around a point of a cell , a small disc inside meets only and its star (Lemma 2), and these cells are in and joined to . Since is connected, the graph is connected, and all cells of share one mark.
- If is a new edge, it is a run of kept collinear old edges and the old vertices between them. Such a vertex is not a new vertex. So it is not kept, and it has no third kept edge, which would be a cut. So it has exactly two kept edges, which are collinear. By L8, both are marked like . Walking along , the marks are all equal.
- If is a new vertex, it is one old vertex.
Line L10 marks by a point inside it (Lemma 4), so gets the common mark of , and the set is unchanged.
(E) and (V). A new edge contains a kept old edge , and the new faces beside it contain the old faces beside , with their marks. By L7, one of those differs from the mark of . A new vertex is an old vertex that is kept. Its new edges are the merged runs through its kept old edges, with the same directions and marks. If had no kept edges, it was kept because some star cell is marked unlike . All of its old star cells lie in the one new face around , which has their common mark, so (V) holds. If had two kept edges that are not collinear, or marked unlike , then the two new edges are the same. If had one kept edge or three or more, then so does the new vertex. By (E) and (V), L7 keeps every edge and L8 keeps every vertex on a second pass, so the complex and marks are rebuilt unchanged.
Termination. Every loop in the code runs over a finite list: segments, cuts, half-edges, cycles, cells or vertices. Cycle tracing stops because each step marks a new half-edge and there are finitely many. SIMPLIFY is a single pass and does not recurse. The topological operations call COMBINE and SIMPLIFY a bounded number of times.
Complexity
For the planar code, with input segments and points and crossings, the complex has cells. The bounds below are proved by counting the loops of the code:
- Building the complex takes time to find the cuts on each segment, and time to sort the half-edges around the vertices and the cuts along the segments. Placing holes and isolated vertices in faces, and finding a point in each face, take time per cycle, so in all.
- Containment takes time.
- COMBINE takes time: one containment query per cell, with and counted over both operands. SIMPLIFY has the same bound.
- Complement takes linear time. Interior and closure take time linear in the total star size, which is , plus a simplification.
A production kernel avoids the quadratic terms. It overlays two subdivisions by a plane sweep in time, for inputs of total size with crossings, and carries the face of each cell through the sweep instead of testing a point. The general SGC of Rossignac and O'Connor works in any dimension with curved cells, and its cost is set by the subdivision step, that is, by surface intersection. The original papers give no general bound, and this page does not state one.
Variants
- Any dimension, curved cells. In the original SGC, each cell lies on an extent, a curve, surface or volume carrying the geometry, and the boundary of every cell is a union of cells. Subdivision intersects extents. Selection marks cells by classifying them against the operands, by set membership classification. Simplification merges a cell into a neighbour of higher dimension when both have the same mark and the same extent.
- Selective Nef complex. Hachenberger, Kettner and Mehlhorn store linear sets in three dimensions as a complex of vertices, edges, facets and volumes with marks, with a sphere map at each vertex for the local picture. This is the Nef polyhedron structure. Both store sets bounded by straight pieces with marks on all cells. The Nef sets are generated from half-spaces, so they include unbounded sets such as half-planes, which the segment-based code on this page cannot build.
- Non-manifold boundary structures. The radial edge data structure of Weiler and later non-manifold B-reps store the same mixed-dimensional objects by their boundaries, with the faces around each edge in radial order. They usually store only the marked cells and their boundaries, not a complete cell decomposition of space.
- Regularized use. A modeler that needs only solids can regularize after each operation and keep only the boundary, which gives a classical B-rep.
When to use it
Use an SGC when the lower-dimensional and non-manifold parts are part of the model. Examples are mid-surface and wire-frame models, meshes with internal faces between materials, cracks and cuts, analysis models that mix shells, beams and solids, and intermediate results that the next operation must not lose. Use it also when exact closure under Booleans matters more than size: an SGC operation never needs a special case for touching faces or coincident edges. For plain solids, a B-rep with regularized Booleans is smaller and faster. For linear objects with exact arithmetic, the Nef structure is the tested implementation of the same idea.
Pitfalls
- Overlapping collinear segments. Two collinear segments that overlap must be split at each other's endpoints, so that both give the same edges. A crossing routine that ignores parallel segments misses this. The code adds every endpoint that lies on a segment as a cut, and stores edges with sorted endpoints, so duplicates merge.
- Holes and isolated points. A face can have several boundary cycles, and an isolated point has no cycle. The face around them must be found by containment, not from the half-edge structure alone, or the hole joins the wrong face.
- Sampling a face. The centroid of an outer cycle need not lie in the face: the face may be non-convex or have holes. Move off a boundary edge along its normal, and stop before the first crossing, as the code does.
- Over-simplification. Removing a vertex between two collinear edges is safe only if the edges carry the same mark as the vertex. Removing a vertex where edges bend changes the geometry, even if all marks agree.
- Inexact arithmetic. The marks depend on exact containment of sample points in cells. With floating point, a sample may land on the wrong side of a nearby edge. Use rational coordinates, or exact predicates as in exact geometric computation.
- Growth without simplification. Each overlay adds all edges of both operands. Without simplification, the complex grows with the length of the modeling history, not with the complexity of the object.
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/selective-geometric-complex/. The authors are listed in prov/TH7Q2X.jsonl.
"""A planar selective geometric complex (SGC) with exact Boolean operations.
The plane is cut by a set of segments and points into cells: vertices, open
edges and faces, where a face is a connected component of the plane minus
all segments and points. Every cell has a mark, in or out, and the object
is the union of the marked cells. So an object may have any mix of
dimensions: areas with or without their boundary, cracks, dangling edges and
isolated points.
Booleans follow the three steps of Rossignac and O'Connor:
subdivide overlay the two complexes, so every new cell lies in one cell
of each input;
select mark each new cell by the Boolean rule on its two parents,
found from a point inside the new cell;
simplify remove the edges and vertices that separate cells with the
same mark, and merge what they separated.
Interior, closure and boundary read the star of each cell: the cells whose
closure contains it.
All coordinates are Fractions, so every test is exact.
Precondition: segments have distinct endpoints.
Cost: for n segments and points with k crossings the complex has O(n + k)
cells. Building it takes O(n^2) for the crossings, O((n + k) log(n + k))
for the angular sorts, and O((n + k)^2) to place holes in faces and to find
a point inside each face. A Boolean or a simplification classifies one point
per cell in O(n + k) time each, so it takes O((n + k)^2) time.
"""
from __future__ import annotations
from fractions import Fraction
from typing import Callable, Iterable, Sequence
Point = tuple[Fraction, Fraction]
Seg = tuple[Point, Point]
def P(x, y) -> Point:
return (Fraction(x), Fraction(y))
def cross(o: Point, a: Point, b: Point) -> Fraction:
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def on_segment(p: Point, a: Point, b: Point) -> bool:
return (cross(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def seg_meet(a: Point, b: Point, c: Point, d: Point) -> Point | None:
"""The crossing point of two segments that are not parallel, if any."""
den = (b[0] - a[0]) * (d[1] - c[1]) - (b[1] - a[1]) * (d[0] - c[0])
if den == 0:
return None
t = ((c[0] - a[0]) * (d[1] - c[1]) - (c[1] - a[1]) * (d[0] - c[0])) / den
u = ((c[0] - a[0]) * (b[1] - a[1]) - (c[1] - a[1]) * (b[0] - a[0])) / den
if 0 <= t <= 1 and 0 <= u <= 1:
return (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))
return None
def half_plane_of(d: Point) -> int:
"""0 for directions with angle in [0, pi), 1 for [pi, 2 pi)."""
return 0 if d[1] > 0 or (d[1] == 0 and d[0] > 0) else 1
def angle_key(o: Point, p: Point):
"""A key that sorts the directions p - o counterclockwise from angle 0."""
d = (p[0] - o[0], p[1] - o[1])
h = half_plane_of(d)
# within a half-plane, compare by the cotangent, which falls as the angle grows
if d[1] == 0:
return (h, -float("inf"), Fraction(0))
return (h, Fraction(0), -d[0] / d[1])
def winding(p: Point, cyc: Sequence[Point]) -> int:
"""The winding number of a closed polygonal chain around p (p not on it)."""
w = 0
for i in range(len(cyc)):
a, b = cyc[i], cyc[(i + 1) % len(cyc)]
if a[1] <= p[1] < b[1] and cross(a, b, p) > 0:
w += 1
elif b[1] <= p[1] < a[1] and cross(a, b, p) < 0:
w -= 1
return w
def area2(cyc: Sequence[Point]) -> Fraction:
return sum(cyc[i][0] * cyc[(i + 1) % len(cyc)][1] - cyc[(i + 1) % len(cyc)][0] * cyc[i][1]
for i in range(len(cyc)))
Cell = tuple
def merge_collinear(edges: Iterable[tuple[Point, Point]]) -> list[Seg]:
"""Join edges that lie on one line and share an endpoint. The edges are
given with their endpoints in sorted order and do not overlap."""
groups: dict[tuple, list[tuple[Point, Point]]] = {}
for u, v in edges:
a, b = v[1] - u[1], u[0] - v[0] # the line a x + b y = c
k = a if a != 0 else b
a, b = a / k, b / k
groups.setdefault((a, b, a * u[0] + b * u[1]), []).append((u, v))
out: list[Seg] = []
for es in groups.values():
es.sort()
cur = list(es[0])
for u, v in es[1:]:
if u == cur[1]:
cur[1] = v
else:
out.append((cur[0], cur[1]))
cur = [u, v]
out.append((cur[0], cur[1]))
return out
class Complex:
"""The cells cut out by segments and points, with their stars."""
def __init__(self, segments: Iterable[Seg], points: Iterable[Point] = ()):
segs = [(P(*a), P(*b)) for a, b in segments]
pts = {P(*p) for p in points}
# 1. split every segment at endpoints, crossings and points on it
edges: set[tuple[Point, Point]] = set()
for i, (a, b) in enumerate(segs):
cuts = {a, b}
for j, (c, d) in enumerate(segs):
if i == j:
continue
m = seg_meet(a, b, c, d)
if m is not None:
cuts.add(m)
for e in (c, d):
if on_segment(e, a, b):
cuts.add(e)
cuts |= {p for p in pts if on_segment(p, a, b)}
cs = sorted(cuts)
for u, v in zip(cs, cs[1:]):
edges.add((u, v))
self.edges = sorted(edges)
verts = {v for e in self.edges for v in e} | pts
self.vertices = sorted(verts)
# 2. half-edges and the next pointer: face on the left
out: dict[Point, list[Point]] = {v: [] for v in self.vertices}
for u, v in self.edges:
out[u].append(v)
out[v].append(u)
for v in out:
out[v].sort(key=lambda w, v=v: angle_key(v, w))
pos = {(v, w): i for v in out for i, w in enumerate(out[v])}
def nxt(h):
a, b = h
i = pos[(b, a)]
return (b, out[b][i - 1])
# 3. trace the boundary cycles
cyc_of: dict[tuple[Point, Point], int] = {}
cycles: list[list[Point]] = []
for u, v in self.edges:
for h in ((u, v), (v, u)):
if h in cyc_of:
continue
k = len(cycles)
cyc = []
while h not in cyc_of:
cyc_of[h] = k
cyc.append(h[0])
h = nxt(h)
cycles.append(cyc)
# 4. faces: face 0 is unbounded; each counterclockwise cycle bounds one more
outer = [k for k, c in enumerate(cycles) if area2(c) > 0]
self.outer_cycles = {k + 1: cycles[c] for k, c in enumerate(outer)}
face_of_cycle = {c: k + 1 for k, c in enumerate(outer)}
for k, c in enumerate(cycles):
if k not in face_of_cycle:
face_of_cycle[k] = self._face_strictly_around(c[0], set(c))
self.faces = [0] + sorted(self.outer_cycles)
# 5. stars
self.star: dict[Cell, set[Cell]] = {}
self.side: dict[tuple[Point, Point], tuple[int, int]] = {}
for u, v in self.edges:
fl, fr = face_of_cycle[cyc_of[(u, v)]], face_of_cycle[cyc_of[(v, u)]]
self.side[(u, v)] = (fl, fr)
self.star[("e", (u, v))] = {("f", fl), ("f", fr)}
for v in self.vertices:
s: set[Cell] = set()
if not out[v]:
s.add(("f", self._face_strictly_around(v, {v})))
for w in out[v]:
e = (min(v, w), max(v, w))
s.add(("e", e))
s |= self.star[("e", e)]
self.star[("v", v)] = s
for f in self.faces:
self.star[("f", f)] = set()
def _face_strictly_around(self, p: Point, on: set[Point]) -> int:
"""The face whose outer cycle is the innermost one around p, among the
cycles that do not pass through the points of `on`."""
best, best_area = 0, None
for f, cyc in self.outer_cycles.items():
if on & set(cyc):
continue
if winding(p, cyc) != 0:
a = area2(cyc)
if best_area is None or a < best_area:
best, best_area = f, a
return best
def cells(self) -> list[Cell]:
return ([("v", v) for v in self.vertices] + [("e", e) for e in self.edges]
+ [("f", f) for f in self.faces])
def locate(self, p: Point) -> Cell:
"""The cell that contains p."""
p = P(*p)
if ("v", p) in self.star:
return ("v", p)
for u, v in self.edges:
if on_segment(p, u, v):
return ("e", (u, v))
best, best_area = 0, None
for f, cyc in self.outer_cycles.items():
if winding(p, cyc) != 0:
a = area2(cyc)
if best_area is None or a < best_area:
best, best_area = f, a
return ("f", best)
def sample(self, c: Cell) -> Point:
"""A point inside the cell c."""
kind, x = c
if kind == "v":
return x
if kind == "e":
return ((x[0][0] + x[1][0]) / 2, (x[0][1] + x[1][1]) / 2)
if x == 0:
if not self.vertices:
return P(0, 0)
return (max(v[0] for v in self.vertices) + 1, Fraction(0))
cyc = self.outer_cycles[x]
a, b = cyc[0], cyc[1]
m = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
n = (a[1] - b[1], b[0] - a[0]) # left normal of a -> b
far = (m[0] + n[0], m[1] + n[1])
hits = []
for u, v in self.edges:
if (u, v) in ((a, b), (b, a)):
continue
if cross(m, far, u) == 0 and cross(m, far, v) == 0:
cand = [u, v]
else:
q = seg_meet(m, (m[0] + 4 * n[0] * 10**6, m[1] + 4 * n[1] * 10**6), u, v)
cand = [q] if q is not None else []
for q in cand:
t = ((q[0] - m[0]) * n[0] + (q[1] - m[1]) * n[1]) / (n[0] ** 2 + n[1] ** 2)
if t > 0:
hits.append(t)
for v in self.vertices:
if cross(m, far, v) == 0:
t = ((v[0] - m[0]) * n[0] + (v[1] - m[1]) * n[1]) / (n[0] ** 2 + n[1] ** 2)
if t > 0:
hits.append(t)
t = min(hits) / 2 if hits else Fraction(1)
return (m[0] + t * n[0], m[1] + t * n[1])
class SGC:
"""A selective geometric complex: a complex and its marked cells."""
def __init__(self, cx: Complex, marks: Iterable[Cell]):
self.cx = cx
self.marks = frozenset(marks)
# primitives
@staticmethod
def from_predicate(segments, points, pred: Callable[[Point], bool]) -> "SGC":
cx = Complex(segments, points)
return SGC(cx, [c for c in cx.cells() if pred(cx.sample(c))])
@staticmethod
def polygon(pts: Sequence, closed: bool) -> "SGC":
"""A simple polygon, with its boundary when closed."""
q = [P(*p) for p in pts]
segs = [(q[i], q[(i + 1) % len(q)]) for i in range(len(q))]
def pred(p):
if any(on_segment(p, a, b) for a, b in segs):
return closed
return winding(p, q) != 0
return SGC.from_predicate(segs, [], pred)
@staticmethod
def segment(a, b, closed: bool) -> "SGC":
a, b = P(*a), P(*b)
return SGC.from_predicate([(a, b)], [], lambda p: on_segment(p, a, b) and (closed or p not in (a, b)))
@staticmethod
def point(p) -> "SGC":
p = P(*p)
return SGC.from_predicate([], [p], lambda q: q == p)
# queries
def contains(self, p) -> bool:
return self.cx.locate(p) in self.marks
def is_empty(self) -> bool:
return not self.marks
def count_by_dimension(self) -> tuple[int, int, int]:
return tuple(sum(1 for c in self.marks if c[0] == k) for k in "vef")
def size(self) -> tuple[int, int, int]:
return (len(self.cx.vertices), len(self.cx.edges), len(self.cx.faces))
# subdivide, select, simplify
def combine(self, other: "SGC", op: Callable[[bool, bool], bool]) -> "SGC":
segs = self.cx.edges + other.cx.edges # @line L1
pts = self.cx.vertices + other.cx.vertices
cx = Complex(segs, pts) # @line L2
marks = []
for c in cx.cells(): # @line L3
p = cx.sample(c) # @line L4
if op(self.contains(p), other.contains(p)): # @line L5
marks.append(c)
return SGC(cx, marks).simplify() # @line L6
def __or__(self, o):
return self.combine(o, lambda x, y: x or y)
def __and__(self, o):
return self.combine(o, lambda x, y: x and y)
def __sub__(self, o):
return self.combine(o, lambda x, y: x and not y)
def __xor__(self, o):
return self.combine(o, lambda x, y: x != y)
def complement(self) -> "SGC":
return SGC(self.cx, [c for c in self.cx.cells() if c not in self.marks])
def simplify(self) -> "SGC":
"""Drop every edge whose mark equals the marks of its two faces, and
every vertex whose mark equals the marks of its whole star; rebuild
the complex from what is left and copy the marks back."""
m, cx = self.marks, self.cx
keep_edges = []
for e in cx.edges: # @line L7
mark = ("e", e) in m
if any((("f", f) in m) != mark for f in cx.side[e]):
keep_edges.append(e)
kept = set(keep_edges)
keep_points = []
for v in cx.vertices: # @line L8
mark = ("v", v) in m
es = [c[1] for c in cx.star[("v", v)] if c[0] == "e" and c[1] in kept]
if not es: # alone in a face: needed if marked otherwise
needed = any((c in m) != mark for c in cx.star[("v", v)])
elif len(es) == 2: # inside a straight edge: needed if marked otherwise
(a,), (b,) = [[x for x in e if x != v] for e in es]
needed = cross(a, v, b) != 0 or any((("e", e) in m) != mark for e in es)
else:
needed = True
if needed:
keep_points.append(v)
new = Complex(merge_collinear(keep_edges), keep_points) # @line L9
return SGC(new, [c for c in new.cells() if self.contains(new.sample(c))]) # @line L10
def interior(self) -> "SGC":
return SGC(self.cx, [c for c in self.marks if self.cx.star[c] <= self.marks]).simplify()
def closure(self) -> "SGC":
return SGC(self.cx, [c for c in self.cx.cells()
if c in self.marks or self.cx.star[c] & self.marks]).simplify()
def boundary(self) -> "SGC":
return self.closure() - self.interior()
def regularization(self) -> "SGC":
return self.interior().closure()
test_selective_geometric_complex.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/selective-geometric-complex/. The authors are listed in prov/TH7Q2X.jsonl.
import random
import unittest
from fractions import Fraction as Fr
from math import atan2, gcd
from selective_geometric_complex import SGC
# Directions for the neighbourhood oracle: the primitive vectors with entries
# in [-4, 4] contain the direction of every segment between grid points of
# [0, 4]^2, and the sum of two neighbours in angular order lies strictly
# inside every wedge between two such directions.
S4 = sorted({(x, y) for x in range(-4, 5) for y in range(-4, 5) if (x, y) != (0, 0) and gcd(x, y) == 1},
key=lambda d: atan2(d[1], d[0]))
DIRS = [(0, 0)] + S4 + [(S4[i][0] + S4[(i + 1) % len(S4)][0], S4[i][1] + S4[(i + 1) % len(S4)][1])
for i in range(len(S4))]
EPS0 = Fr(1, 10000)
def orient(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def in_closed_segment(p, a, b):
if orient(a, b, p) != 0:
return False
t = ((p[0] - a[0]) * (b[0] - a[0]) + (p[1] - a[1]) * (b[1] - a[1]))
return 0 <= t <= (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
def prim_contains(prim, p):
"""Membership in a primitive, straight from its definition."""
kind = prim[0]
if kind == "tri":
_, a, b, c, closed = prim
s = [orient(a, b, p), orient(b, c, p), orient(c, a, p)]
if orient(a, b, c) < 0:
s = [-x for x in s]
if all(x > 0 for x in s):
return True
return closed and all(x >= 0 for x in s)
if kind == "seg":
_, a, b, closed = prim
return in_closed_segment(p, a, b) and (closed or p not in (a, b))
return p == prim[1]
def ev(node, p, eps=EPS0):
k = node[0]
if k in ("tri", "seg", "pt"):
return prim_contains(node, p)
if k == "not":
return not ev(node[1], p, eps)
if k in ("and", "or", "minus", "xor"):
x, y = ev(node[1], p, eps), ev(node[2], p, eps)
return {"and": x and y, "or": x or y, "minus": x and not y, "xor": x != y}[k]
near = [ev(node[1], (p[0] + eps * d[0], p[1] + eps * d[1]), eps / 100) for d in DIRS]
return {"int": all(near), "cl": any(near), "bd": any(near) and not all(near)}[k]
def build(node):
k = node[0]
if k == "tri":
return SGC.polygon(node[1:4], node[4])
if k == "seg":
return SGC.segment(node[1], node[2], node[3])
if k == "pt":
return SGC.point(node[1])
if k == "not":
return build(node[1]).complement()
if k in ("and", "or", "minus", "xor"):
a, b = build(node[1]), build(node[2])
return {"and": a & b, "or": a | b, "minus": a - b, "xor": a ^ b}[k]
a = build(node[1])
return {"int": a.interior(), "cl": a.closure(), "bd": a.boundary()}[k]
def rpt(rng):
return (rng.randint(0, 4), rng.randint(0, 4))
def random_primitive(rng):
r = rng.random()
if r < 0.6:
while True:
a, b, c = rpt(rng), rpt(rng), rpt(rng)
if orient(a, b, c) != 0:
return ("tri", a, b, c, rng.random() < 0.5)
if r < 0.85:
while True:
a, b = rpt(rng), rpt(rng)
if a != b:
return ("seg", a, b, rng.random() < 0.5)
return ("pt", rpt(rng))
def random_formula(rng, depth, topo):
if depth == 0 or rng.random() < 0.25:
return random_primitive(rng)
r = rng.random()
if topo and r < 0.3:
return (rng.choice(["int", "cl", "bd"]), random_formula(rng, depth - 1, False))
if r < 0.35:
return ("not", random_formula(rng, depth - 1, topo))
return (rng.choice(["and", "or", "minus", "xor"]), random_formula(rng, depth - 1, topo),
random_formula(rng, depth - 1, topo))
def sample_points(s):
pts = [(Fr(x, 2), Fr(y, 2)) for x in range(-1, 10) for y in range(-1, 10)]
return pts + list(s.cx.vertices)
class TestHandCases(unittest.TestCase):
def test_square_with_a_crack(self):
sq = SGC.polygon([(0, 0), (4, 0), (4, 4), (0, 4)], True)
crack = SGC.segment((1, 2), (3, 2), False)
s = sq - crack
self.assertEqual(s.size(), (6, 5, 2)) # 1 bounded face, plus the outside
self.assertEqual(s.count_by_dimension(), (6, 4, 1))
self.assertFalse(s.contains((2, 2)))
self.assertTrue(s.contains((1, 2)))
r = s.regularization()
self.assertEqual(r.size(), (4, 4, 2))
self.assertTrue(r.contains((2, 2)))
def test_shared_edge(self):
a = SGC.polygon([(0, 0), (2, 0), (2, 2), (0, 2)], True)
b = SGC.polygon([(2, 0), (4, 0), (4, 2), (2, 2)], True)
self.assertEqual((a & b).count_by_dimension(), (2, 1, 0))
self.assertTrue((a & b).regularization().is_empty())
u = a | b
self.assertEqual(u.size(), (4, 4, 2)) # the inner edge is simplified away
self.assertEqual(u.count_by_dimension(), (4, 4, 1))
def test_dangling_edge_and_point(self):
sq = SGC.polygon([(0, 0), (2, 0), (2, 2), (0, 2)], True)
s = sq | SGC.segment((2, 1), (3, 1), True) | SGC.point((4, 4))
self.assertEqual(s.count_by_dimension(), (7, 6, 1))
self.assertEqual(s.boundary().count_by_dimension(), (7, 6, 0))
self.assertEqual(s.interior().count_by_dimension(), (0, 0, 1))
class TestAgainstFormula(unittest.TestCase):
def test_boolean_formulas(self):
rng = random.Random(1)
checked = 0
for _ in range(30):
f = random_formula(rng, 3, False)
s = build(f)
for p in sample_points(s):
self.assertEqual(s.contains(p), ev(f, p), (f, p))
checked += 1
self.assertGreater(checked, 500)
def test_topological_operators(self):
rng = random.Random(2)
checked = 0
for _ in range(15):
f = (rng.choice(["int", "cl", "bd"]), random_formula(rng, 2, False))
s = build(f)
pts = sample_points(s)
for p in rng.sample(pts, 35):
self.assertEqual(s.contains(p), ev(f, p), (f, p))
checked += 1
self.assertGreater(checked, 500)
class TestSimplification(unittest.TestCase):
def test_minimal_and_stable(self):
"""After simplification no edge or vertex separates cells with equal
marks, and simplifying again changes nothing."""
rng = random.Random(3)
for _ in range(20):
s = build(random_formula(rng, 3, False))
cx, m = s.cx, s.marks
for e in cx.edges:
self.assertTrue(any((("f", f) in m) != (("e", e) in m) for f in cx.side[e]))
for v in cx.vertices:
star = cx.star[("v", v)]
needed = any((c in m) != (("v", v) in m) for c in star)
edges = [c for c in star if c[0] == "e"]
bend = len(edges) != 2 or orient(*[x for c in edges for x in c[1] if x != v][:2], v) != 0
self.assertTrue(needed or bend)
t = s.simplify()
self.assertEqual(t.size(), s.size())
self.assertEqual(t.count_by_dimension(), s.count_by_dimension())
if __name__ == "__main__":
unittest.main()
History
Rossignac and O'Connor, at IBM Research, circulated the selective geometric complex as a research report in 1989. It was published in the proceedings of an IFIP working conference, Geometric Modeling for Product Engineering, edited by Wozny, Turner and Preiss (North-Holland, 1990). The aim was a single dimension-independent model for objects with internal structure and incomplete boundaries. These are the cases of mixed-dimensional models, non-manifold models and models in mid-construction, which the r-sets of Requicha's theory exclude. The SGC came at the same time as other non-manifold representations, such as the radial edge structure of Weiler's 1986 thesis. Rossignac and Requicha then argued, in 1991, for constructive non-regularized geometry built on such sets. The linear case was later made exact and fully implemented as the selective Nef complex of Hachenberger, Kettner and Mehlhorn (2007), building on Walter Nef's 1978 theory of polyhedra.
References
- Jarek R. Rossignac and Michael A. O'Connor, SGC: a dimension-independent model for pointsets with internal structures and incomplete boundaries, in M. J. Wozny, J. U. Turner and K. Preiss (eds.), Geometric Modeling for Product Engineering, North-Holland, 1990, pages 145 to 180 (also an IBM research report, 1989), the definition of the selective geometric complex as a set of disjoint, relatively open, connected cells with in-or-out marks, and the Boolean operations by subdivision, selection and simplification
- Jarek R. Rossignac and Aristides A. G. Requicha, Constructive non-regularized geometry, Computer-Aided Design 23(1), 21 to 32, 1991, Boolean and topological operations on non-regularized sets, and their use in solid modeling
- Peter Hachenberger, Lutz Kettner and Kurt Mehlhorn, Boolean operations on 3D selective Nef complexes, data structure, algorithms, optimized implementation and experiments, Computational Geometry 38(1-2), 64 to 99, 2007, the selective Nef complex, a selective complex for linear sets in three dimensions with the same overlay, selection and simplification steps
- Mark de Berg, Otfried Cheong, Marc van Kreveld and Mark Overmars, Computational Geometry, Algorithms and Applications, 3rd edition, Springer, 2008, chapter 2, the doubly connected edge list, its boundary cycles and holes, and the overlay of two subdivisions
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 TH7Q2X Edit this page History Report an error Markdown