Algorithm Search⌘K

Algorithmresearch

Mesh arrangements for solid geometry

Also called Zhou mesh arrangement.

Zhou, Grinspun, Zorin and Jacobson's method that computes the exact arrangement of all input triangles, labels each cell by winding numbers and extracts any Boolean.

Time
O(n^2) output_worstO(n^2 + (n + K) log n) planar_code
Space
O(n + K) arrangement
Where
K = the number of intersection points; n = the number of input edges (triangles in 3D)
Properties
deterministicexactiterative
Origin
Qingnan Zhou, Eitan Grinspun, Denis Zorin, Alec Jacobson, 2016

Mesh arrangements is a method for Boolean operations on triangle meshes that works even when the input meshes cut themselves, overlap, touch along faces, or are not closed. It cuts every triangle of every input against every other with exact arithmetic, so that the pieces meet only along shared edges. The pieces divide space into cells. Each cell gets one winding number per input mesh, found by starting outside, where all winding numbers are 0, and adding the multiplicity of each face crossed. A Boolean is then a rule on these numbers, for example "inside A or inside B", and the output is the set of faces between a cell where the rule holds and one where it fails. Qingnan Zhou, Eitan Grinspun, Denis Zorin and Alec Jacobson presented it in 2016. It is the main exact method for the mesh Boolean operations problem. The code of this page implements the same steps one dimension lower, for closed polygons in the plane, with exact rational arithmetic.

In plain words

Draw two overlapping shapes on paper with a pencil. Every place where two lines cross becomes a corner, and the lines cut the paper into many small regions. Now ask, for each region, how many times each shape wraps around it. Outside everything, the answer is zero. Each time you cross a line of a shape going inward, the count for that shape goes up by one.

When every region has its counts, a Boolean is just a choice of regions. The union keeps the regions where either count is positive, the intersection keeps those where both are. The answer is the outline of the chosen regions. Because the counts come from crossing lines, the method does not care if a shape crosses itself or if two shapes share an edge.

The problem

The input is KK meshes, here KK sets of closed polygons, each oriented so that the outward normal follows the right-hand rule; in the plane that means counterclockwise, with the outward normal on the right of each edge. The polygons may cross themselves and each other, overlap along edges and touch at points. A rule ff maps a vector of KK winding numbers to inside or outside, with f(0,…,0)f(0, \dots, 0) outside. The output is the boundary of the region where ff holds, as a set of directed edges with the region on the left, and its area.

The algorithm

Two input edges meet in a single crossing point, or, if they lie on one line, along an overlap. The crossing point of segments p1p2p_1p_2 and q1q2q_1q_2 has the parameter t=cross(q1−p1,q2−q1)/cross(p2−p1,q2−q1)t = \mathrm{cross}(q_1 - p_1, q_2 - q_1) / \mathrm{cross}(p_2 - p_1, q_2 - q_1), which is a rational number for rational input, so the point is exact. Each half-edge u→vu \to v of the result carries a vector mm, the number of input edges of each input that run from uu to vv minus those that run from vv to uu. Crossing that half-edge from its right side to its left side raises the winding numbers by mm.

  1. MESH-ARRANGEMENT-BOOLEAN(polygons with input tags, rule f)
  2. 1for each pair of input edges, add their crossing point or overlap ends to both as cut points
  3. 2split each edge at its sorted cut points; merge equal pieces, adding their signed counts m
  4. 3sort the half-edges around each vertex by angle; next(u → v) is the edge at v just clockwise of v → u
  5. 4for each connected component, take its leftmost lowest vertex v; label the outer half-edge at v with the winding numbers of the other components at v
  6. 5propagate labels: next(h) gets the label of h; the twin of h gets label(h) − m(h)
  7. 6keep each half-edge h with f(label(h)) true and f(label(twin(h))) false
  8. 7return the kept half-edges and their area by the shoelace formula

In 3D, Zhou and coauthors replace L1 and L2 by an exact intersection of all pairs of triangles that a bounding box test finds, followed by a constrained Delaunay triangulation of each triangle with its cut segments, as in mesh self-intersection. L3 becomes the sorting of the patches around each non-manifold edge by an exact orientation test, and the components nested inside each other are placed by finding the outer hull of each. L5 and L6 are the same, with cells and faces in place of faces and edges.

Degenerate cases. A polygon edge of length zero is dropped. Two inputs that share an edge produce one merged piece whose mm counts both, so the shared edge is not duplicated. A piece that one polygon uses in both directions has m=0m = 0; it separates two faces with equal labels and is never output. Points where only two pieces meet in a straight line stay as vertices of the output, so the output can have collinear consecutive edges. A clockwise polygon has winding number −1-1 inside, and with the rule w>0w > 0 it removes area from a counterclockwise polygon of the same input, which is how holes are given.

Example

Let input A be the square [0,2]2[0, 2]^2 and input B the square [1,3]2[1, 3]^2, both counterclockwise.

step value
L1 the boundaries cross at (2,1)(2, 1) and (1,2)(1, 2)
L2 12 pieces and 10 vertices; each piece has m=(±1,0)m = (\pm 1, 0) or (0,±1)(0, \pm 1)
L4 the least vertex is (0,0)(0, 0); its outgoing pieces go to (2,0)(2, 0) and (0,2)(0, 2), and the one with the larger angle, (0,0)→(0,2)(0,0) \to (0,2), has the outside on its left: label (0,0)(0, 0)
L5 A runs (0,2)→(0,0)(0, 2) \to (0, 0), so m((0,0)→(0,2))=(−1,0)m((0,0) \to (0,2)) = (-1, 0) and the twin gets (0,0)−(−1,0)=(1,0)(0,0) - (-1,0) = (1, 0)
L5 the other faces get (1,1)(1, 1) in the overlap and (0,1)(0, 1) in the part of B outside A
L6, union rule wA>0w_A > 0 or wB>0w_B > 0: 8 half-edges, the outer pieces of both squares
L7 union area 7, intersection area 1 (4 half-edges), difference A − B area 3 (6 half-edges)

The tests also check the labels on random closed polylines with integer vertices in [0,6]2[0, 6]^2, which cross themselves and each other and often share vertices and overlapping edges. In 30 such inputs, 110 of the 1950 pieces were shared by more than one input edge, the winding numbers ranged from −2-2 to 33, and the label of the face found by an exact ray from 1155 random points equalled the exact winding number at the point every time.

When the arithmetic is floating point. The method depends on exactness in a way most geometry code does not. If the crossing point of two edges is rounded, it no longer lies on either edge, the pieces can cross again near it, and a piece can end up on the wrong side of a vertex. Then the cycles of L3 do not close, or the labels of L5 disagree, and the code of this page would raise its consistency error. The signs that decide the order around a vertex and the side of a point are orientation tests, and in doubles they suffer from catastrophic cancellation exactly in the degenerate cases that Booleans produce, such as shared edges and coplanar faces. Zhou and coauthors therefore compute the whole arrangement with exact rational numbers, and only filtered exact predicates keep this fast. The output has rational coordinates; rounding them to doubles can create new self-intersections, which is a remaining part of the robustness problem.

Correctness

After the cuts, two pieces meet only at common endpoints, because every point where two input edges meet is a cut point of both, and pieces of collinear overlapping edges coincide and are merged. The winding numbers are constant on each face and jump by mm across a piece, so the propagation rules of L5 hold for the true values. The first label of a component is right: a ray to the left of its leftmost vertex misses the component, which is made of whole closed polygons and winds 0 there, and the other polygons do not pass through the vertex. By induction every label equals the true winding numbers, every half-edge of the component is reached, and the kept half-edges are exactly the boundary of the chosen region, with the region on the left, so the shoelace sum is its area. The full proof is below.

Proof: The planar arrangement version labels every face with its exact winding numbers and returns the exact boundary and area of any Boolean of the inputsfull

Setting. The input is a finite list of closed polygons P1,…,PrP_1, \dots, P_r in the plane with rational vertices, each tagged with an input k∈{0,…,K−1}k \in \{0, \dots, K - 1\}. A polygon is any closed polyline: it may cross itself, overlap other polygons or touch them. Zero-length edges are dropped. For a point pp off all edges, wk(p)w_k(p) is the sum of the winding numbers of the polygons of input kk around pp, and w(p)=(w0(p),…,wK−1(p))w(p) = (w_0(p), \dots, w_{K-1}(p)). A counterclockwise polygon, whose outward normal is on the right of each edge, winds +1+1 around its inside. A rule is a function ff from integer vectors to {true,false}\{\text{true}, \text{false}\} with f(0)=falsef(0) = \text{false}, for example w0>0∨w1>0w_0 > 0 \lor w_1 > 0 for a union. The Boolean is the set RfR_f, the closure of {p:f(w(p))}\{p : f(w(p))\}.

Claim.

  1. After L1 and L2, the subsegments form a planar straight-line graph GG: two distinct subsegments meet at most at a common endpoint. Each subsegment ee carries the vector m(e)m(e) of signed counts of input edges that contain it.
  2. For a half-edge h=(u→v)h = (u \to v), the code's NEXT gives the next half-edge on the boundary of the face of GG to the left of hh.
  3. When the code finishes, the label of every half-edge hh equals w(p)w(p) for the points pp of the face to the left of hh. In particular, the code never finds two different labels for one half-edge.
  4. The half-edges hh whose left label satisfies ff and whose right label does not are exactly the boundary of RfR_f, oriented with RfR_f on the left, and half the sum of cross(u,v)\mathrm{cross}(u, v) over them is the area of RfR_f.

Step 1 (part 1). All points are computed with exact rational arithmetic, so equal points are equal tuples. Every point where two input edges meet is added as a cut point to both: a single crossing point when they are not parallel, and the endpoints of the overlap when they are collinear. Let ss be a subsegment of edge eie_i and tt one of edge eje_j, and let xx be a common point in the interior of ss. Then x∈ei∩ejx \in e_i \cap e_j. If eie_i and eje_j are not parallel, xx is their crossing point, which is a cut point of eie_i, but a subsegment has no cut point in its interior; a contradiction. If they are collinear, xx lies in their overlap, whose endpoints are cut points of both, so ss and tt lie in the overlap. Within the overlap, eie_i and eje_j have the same cut points: a point where a third edge meets eie_i inside the overlap also lies on eje_j, and is added to eje_j by the same rule. So s=ts = t as segments, and L2 merges them into one key and adds their signed counts. Hence distinct subsegments meet only at endpoints.

Step 2 (part 2). At each vertex vv the outgoing directions are sorted counterclockwise with an exact comparison: first by the half-plane, then by the sign of a cross product. No two outgoing subsegments have the same direction, since by part 1 they would overlap. The face to the left of h=(u→v)h = (u \to v) near vv is the wedge between the direction from vv back to uu and the next outgoing direction clockwise from it. So the boundary of that face continues with that outgoing edge, which is what NEXT returns. This is the usual face rule of a doubly connected edge list.

Step 3 (labels are consistent with the winding numbers). Two facts about ww.

(a) ww is constant on each face of GG, because wkw_k changes only across edges of input kk, and each face is a connected open set off all edges.

(b) If pp is just left of a point xx in the interior of a subsegment e=(u→v)e = (u \to v) and qq is just right of it, then w(p)−w(q)=m(u→v)w(p) - w(q) = m(u \to v). For a single polygon edge through xx going from uu toward vv, the half-open crossing count with a ray from pp or qq along the edge's normal direction differs by exactly one crossing of that edge, with sign +1+1 when the edge goes the same way as u→vu \to v and −1-1 when it goes the other way. Edges that do not contain xx do not separate pp from qq. Summing over the input edges that contain ee gives mm.

The code labels each half-edge with ww of its left face. A step to NEXT stays in the same face, so by (a) the label is copied. A step to the twin crosses the edge from left to right, so by (b) the new label is the old one minus m(h)m(h). Both rules hold for the true values, so if the first label of a component is right, every label reached from it is right, and no conflict can appear.

The first label. Let CC be a connected component of GG and vv its least vertex in the order (x, then y). Each polygon is connected, so all its subsegments lie in one component, and CC is the union of whole polygons. Every point of CC has x≥vxx \ge v_x, and the points with x=vxx = v_x have y≥vyy \ge v_y, so all outgoing directions at vv lie in the half-open half-plane from straight down (excluded) to straight up (included), and the direction (−1,0)(-1, 0) lies in the wedge to the left of the outgoing half-edge with the largest angle. That is the half-edge the code picks. Let p=v+ε(−1,0)p = v + \varepsilon(-1, 0) for a small ε>0\varepsilon > 0. The ray from pp to the left meets no point of CC, so the polygons of CC wind 0 around pp. The vertex vv is on no edge of a polygon outside CC (otherwise that polygon would share a vertex with CC by part 1 and be in CC), so the winding numbers of the other polygons are the same at pp as at vv, and the code computes them at vv with the exact half-open rule, which is correct at every point off the counted edges.

Every half-edge of CC is reached: from h=(x→y)h = (x \to y), the twin of hh followed by NEXT is the outgoing half-edge at xx just clockwise of hh, so all half-edges at a vertex are reached, and CC is connected. This proves part 3.

Step 4 (part 4). By part 3, ff of the left label of hh says whether the face left of hh is in RfR_f. An edge is on the boundary of RfR_f exactly when one side is in it and the other is not, and the code keeps the half-edge with RfR_f on its left. The unbounded face has w=0w = 0, so it is not in RfR_f and RfR_f is bounded. For each bounded face FF, the half-edges with FF on the left form its boundary cycles, the outer one counterclockwise and the holes clockwise, and by Green's theorem half the sum of cross(u,v)\mathrm{cross}(u, v) over them is the area of FF; a subsegment with the same face on both sides contributes cross(u,v)+cross(v,u)=0\mathrm{cross}(u, v) + \mathrm{cross}(v, u) = 0. Summing over the faces of RfR_f, an edge between two faces of RfR_f appears in both directions and cancels, which leaves the sum over the boundary half-edges. All operations are rational, so the area is exact.

Termination. L1 compares each pair of input edges once. L2 sorts finitely many cut points per edge. The search of L5 adds a half-edge to the queue only when it gets its first label, so it runs at most twice the number of subsegments times. ■\blacksquare

The 3D method. Zhou and coauthors apply the same argument to triangles in space: the cut of all triangles against each other gives a complex whose faces meet only along shared edges, cells take the place of faces, the patches around a non-manifold edge are sorted by an exact orientation test, and the winding number vector jumps across a face by its multiplicity. This page proves only the planar version that its code implements.

Complexity

For nn input edges, the code of this page tests all pairs, O(n2)O(n^2) time, and then sorts the cut points of each edge and the pieces around each vertex, O((n+K)log⁡n)O((n + K) \log n) for KK crossing points. A sweep finds the crossings in O((n+K)log⁡n)O((n + K) \log n), which is better when KK is small. The search of L5 visits each half-edge once, O(n+K)O(n + K). The arrangement takes O(n+K)O(n + K) space, and KK can be Θ(n2)\Theta(n^2), for example for two grids of long thin rectangles laid across each other, so the output alone can be quadratic. In 3D, the arrangement of nn triangles can have Θ(n2)\Theta(n^2) cut segments, and every step also pays for exact arithmetic, whose cost grows with the bit length of the coordinates.

Properties

  • Exact. With rational input all labels and the output are exact.
  • Robust to bad input. Self-intersections, overlaps, shared faces and nested components are handled by the winding numbers.
  • Any Boolean at once. One arrangement serves union, intersection, difference, symmetric difference, and rules over many inputs, such as "inside at least two of five".
  • Order independent. The result depends only on the input polygons, not on the order of their edges.
  • Needs closed input for integer labels. The labels are integer winding numbers only when each input is closed. An open mesh has no integer winding number, and the propagation can then reach one cell with two different values.

Variants and improvements

  • Planar overlay. The planar case is the overlay of subdivisions with a doubly connected edge list, as in de Berg and coauthors, and polygon clipping methods such as Vatti clipping and the Greiner-Hormann algorithm compute the same Booleans for polygons with less general input.
  • Nef polyhedra. Exact Booleans of general polyhedra with selective Nef complexes, by Granados and coauthors (2003) and in CGAL, are exact too but build a much larger structure.
  • Plane-based and interval methods. Bernstein and Fussell (2009) and Campen and Kobbelt (2010) represent the geometry by planes and use filtered or fixed-precision predicates to get speed with exactness.
  • Generalized winding numbers. For open or broken meshes, the generalized winding number gives a soft inside value per cell instead of an exact integer.
  • Faster exact cuts. Cherchi, Livesu, Scateni and Attene (2020) replaced the rational numbers by indirect predicates on the input coordinates, which avoids the growth of bit length.

When to use it

Use it when the input meshes may be dirty, as scanned or modelled meshes often are, and the Boolean must be watertight and exact: 3D printing, CAD of meshes, and preparing meshes for simulation. For clean input and speed, plane-based or floating point methods may be enough, and for B-rep solids with curved faces, see solid Boolean operations. In the plane, use a polygon clipping library unless the input has the same kinds of degeneracy.

Pitfalls

  • Floating point intersections. Rounded crossing points break the structure, as described above. Keep the arithmetic exact until the end.
  • Wrong orientation. A polygon or mesh with reversed faces has winding number −1-1 inside and is treated as a hole by the rule w>0w > 0. Fix the orientation first, or use w≠0w \ne 0.
  • Rounding the output. The exact output may become self-intersecting when its coordinates are rounded to doubles.
  • Quadratic output. Many long thin parts crossing each other create Θ(n2)\Theta(n^2) pieces, and exact rationals grow in size with each step.

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.

mesh_arrangements.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mesh-arrangements/. The authors are listed in prov/NG1GH7.jsonl.

"""Mesh arrangements for solid geometry (Zhou, Grinspun, Zorin and Jacobson 2016), in the plane.

The 3D method cuts all triangles of all input meshes against each other,
labels every cell of the arrangement with one winding number per input, and
keeps the faces between cells that a Boolean rule puts on different sides.
This file does the same one dimension lower: the input is a list of closed
polygons (any closed polylines, which may cross themselves or each other,
overlap or touch), each tagged with the input it belongs to. Edges play the
role of triangles and faces of the planar arrangement play the role of cells.

All coordinates are int or Fraction and every test is exact. A polygon is
oriented counterclockwise, so its outward normal is on the right of each
edge; this is the 2D form of the right-hand rule for faces.
"""

from collections import deque
from fractions import Fraction
from functools import cmp_to_key

from mp3geom import orient2d, sub


def cross(a, b):
    return a[0] * b[1] - a[1] * b[0]


def segment_split_points(p1, p2, q1, q2):
    """The points where segment p1p2 meets q1q2: one crossing point, or the ends of a collinear overlap."""
    r, s = sub(p2, p1), sub(q2, q1)
    d = cross(r, s)
    qp = sub(q1, p1)
    if d != 0:
        t, u = Fraction(cross(qp, s), d), Fraction(cross(qp, r), d)
        if 0 <= t <= 1 and 0 <= u <= 1:
            return [tuple(a + t * b for a, b in zip(p1, r))]
        return []
    if cross(qp, r) != 0:
        return []                              # parallel, on different lines
    out = []
    for x, (a, b) in ((q1, (p1, p2)), (q2, (p1, p2)), (p1, (q1, q2)), (p2, (q1, q2))):
        if min(a, b) <= x <= max(a, b):        # collinear, so the order of tuples is the order on the line
            out.append(x)
    return out


def input_edges(polygons):
    """(start, end, input) for each nonzero edge of each closed polygon."""
    out = []
    for poly, k in polygons:
        pts = [tuple(Fraction(c) for c in p) for p in poly]
        for i in range(len(pts)):
            a, b = pts[i], pts[(i + 1) % len(pts)]
            if a != b:
                out.append((a, b, k))
    return out


def angle_cmp(d1, d2):
    """Counterclockwise order of directions, starting at the positive x axis. Exact."""
    h1 = 0 if (d1[1] > 0 or (d1[1] == 0 and d1[0] > 0)) else 1
    h2 = 0 if (d2[1] > 0 or (d2[1] == 0 and d2[0] > 0)) else 1
    if h1 != h2:
        return h1 - h2
    c = cross(d1, d2)
    return -1 if c > 0 else (1 if c < 0 else 0)


def winding_at(point, edges, n_inputs, skip=None):
    """Exact winding number of each input around a point not on the counted edges (the half-open crossing rule)."""
    w = [0] * n_inputs
    for a, b, k in edges:
        if skip is not None and skip(a, b, k):
            continue
        if a[1] <= point[1] < b[1] and orient2d(a, b, point) > 0:
            w[k] += 1
        elif b[1] <= point[1] < a[1] and orient2d(a, b, point) < 0:
            w[k] -= 1
    return tuple(w)


class Arrangement:
    """The planar arrangement of the input edges, with a winding number vector for the face left of each half-edge."""

    def __init__(self, polygons, n_inputs):
        self.n = n_inputs
        self.edges = input_edges(polygons)
        cuts = [{a, b} for a, b, _ in self.edges]
        for i in range(len(self.edges)):  # @line L1
            a, b, _ = self.edges[i]
            for j in range(i + 1, len(self.edges)):
                c, d, _ = self.edges[j]
                for x in segment_split_points(a, b, c, d):
                    cuts[i].add(x)
                    cuts[j].add(x)
        # multiplicity m[(u, v)][k]: the number of input-k edges that run from u to v, minus those from v to u
        mult = {}
        for (a, b, k), pts in zip(self.edges, cuts):  # @line L2
            r = sub(b, a)
            chain = sorted(pts, key=lambda x: (x[0] - a[0]) * r[0] + (x[1] - a[1]) * r[1])
            for u, v in zip(chain, chain[1:]):
                key, sgn = ((u, v), 1) if u < v else ((v, u), -1)
                mult.setdefault(key, [0] * n_inputs)[k] += sgn
        self.mult = mult
        out = {}
        for u, v in mult:
            out.setdefault(u, []).append(v)
            out.setdefault(v, []).append(u)
        for u in out:  # @line L3
            out[u].sort(key=cmp_to_key(lambda x, y, u=u: angle_cmp(sub(x, u), sub(y, u))))
        self.out = out
        self.position = {(u, v): i for u in out for i, v in enumerate(out[u])}
        self.label = self.propagate()

    def m(self, u, v):
        """Signed multiplicity vector of the half-edge u -> v."""
        if u < v:
            return self.mult[(u, v)]
        return [-x for x in self.mult[(v, u)]]

    def next(self, u, v):
        """The next half-edge of the face left of u -> v: at v, the outgoing edge just clockwise of v -> u."""
        ring = self.out[v]
        return v, ring[(self.position[(v, u)] - 1) % len(ring)]

    def components(self):
        seen, comps = set(), []
        for s in self.out:
            if s in seen:
                continue
            comp, queue = [], deque([s])
            seen.add(s)
            while queue:
                u = queue.popleft()
                comp.append(u)
                for v in self.out[u]:
                    if v not in seen:
                        seen.add(v)
                        queue.append(v)
            comps.append(comp)
        return comps

    def propagate(self):
        label = {}
        for comp in self.components():
            members = set(comp)
            v = min(comp)                      # leftmost, then lowest: on the outer boundary of the component
            # the outgoing half-edge whose left wedge contains the direction (-1, 0)
            h = max(((v, x) for x in self.out[v]), key=cmp_to_key(lambda e, f: -1 if cross(sub(e[1], v), sub(f[1], v)) > 0 else 1))
            # the component is a union of whole closed polygons, which wind 0 around a point just left of v
            label[h] = winding_at(v, self.edges, self.n, skip=lambda a, b, k: a in members)  # @line L4
            queue = deque([h])
            while queue:  # @line L5
                u, x = queue.popleft()
                w = label[(u, x)]
                twin = tuple(a - b for a, b in zip(w, self.m(u, x)))
                for g, val in ((self.next(u, x), w), ((x, u), twin)):
                    if g in label:
                        if label[g] != val:
                            raise AssertionError("inconsistent winding numbers")
                    else:
                        label[g] = val
                        queue.append(g)
        return label

    def boundary(self, rule):
        """The half-edges with an inside face on the left and an outside face on the right, for a rule on winding vectors."""
        return [(u, v) for (u, v), w in self.label.items() if rule(w) and not rule(self.label[(v, u)])]  # @line L6


def area(halfedges):
    """Area enclosed by a set of boundary half-edges with the inside on the left (the shoelace formula). Exact."""
    return Fraction(sum(cross(u, v) for u, v in halfedges)) / 2


def UNION(w):
    return w[0] > 0 or w[1] > 0


def INTERSECTION(w):
    return w[0] > 0 and w[1] > 0


def DIFFERENCE(w):
    return w[0] > 0 and not w[1] > 0


def boolean(polygons_a, polygons_b, rule):
    """Boolean of two inputs, each a list of closed polygons. Returns the boundary half-edges and the area."""
    arr = Arrangement([(p, 0) for p in polygons_a] + [(p, 1) for p in polygons_b], 2)
    edges = arr.boundary(rule)
    return edges, area(edges)  # @line L7
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small tools for triangle meshes, used by the mp3 pages.

Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""

from fractions import Fraction


def sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


def scale(s, a):
    return tuple(s * x for x in a)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


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 orient2d(a, b, c):
    """Twice the signed area of triangle abc: > 0 if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def orient3d(a, b, c, d):
    """((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
    return dot(cross(sub(b, a), sub(c, a)), sub(d, a))


def sign(x):
    return (x > 0) - (x < 0)


def solve(a, b, tol=0.0):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a list of n rows of length n, b is a list of n rows of length m
    (m right-hand sides). Entries are Fraction (exact) or float. Returns the
    n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
    an exact singular matrix always raises when tol is 0.
    """
    n = len(a)
    m = len(b[0]) if n else 0
    rows = [list(a[i]) + list(b[i]) for i in range(n)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
        if abs(rows[piv][col]) <= tol:
            raise ValueError("singular matrix")
        rows[col], rows[piv] = rows[piv], rows[col]
        pr = rows[col]
        inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = f * inv
                row = rows[r]
                for k in range(col, n + m):
                    if pr[k]:
                        row[k] -= f * pr[k]
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        row = rows[i]
        for k in range(m):
            s = row[n + k]
            for j in range(i + 1, n):
                if row[j]:
                    s -= row[j] * x[j][k]
            x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
    return x


def directed_edges(faces):
    """Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
    out = {}
    for f, tri in enumerate(faces):
        for k in range(3):
            e = (tri[k], tri[(k + 1) % 3])
            if e in out:
                raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
            out[e] = (f, k)
    return out


def neighbours(faces):
    """Map each vertex to the set of its neighbours."""
    nb = {}
    for tri in faces:
        for k in range(3):
            i, j = tri[k], tri[(k + 1) % 3]
            nb.setdefault(i, set()).add(j)
            nb.setdefault(j, set()).add(i)
    return nb


def boundary_loop(faces):
    """The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
    de = directed_edges(faces)
    nxt = {}
    for i, j in de:
        if (j, i) not in de:
            if i in nxt:
                raise ValueError("boundary vertex %r is not manifold" % (i,))
            nxt[i] = j
    if not nxt:
        raise ValueError("the mesh has no boundary")
    start = min(nxt)
    loop = [start]
    while True:
        v = nxt[loop[-1]]
        if v == start:
            break
        loop.append(v)
    if len(loop) != len(nxt):
        raise ValueError("the boundary has more than one loop")
    return loop


def euler_characteristic(faces):
    verts = {v for tri in faces for v in tri}
    edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
    return len(verts) - len(edges) + len(faces)
test_mesh_arrangements.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mesh-arrangements/. The authors are listed in prov/NG1GH7.jsonl.

import random
from fractions import Fraction

from mesh_arrangements import (
    DIFFERENCE,
    INTERSECTION,
    UNION,
    Arrangement,
    area,
    boolean,
    winding_at,
)


def square(x0, y0, size, clockwise=False):
    pts = [(x0, y0), (x0 + size, y0), (x0 + size, y0 + size), (x0, y0 + size)]
    return pts[::-1] if clockwise else pts


def face_label(arr, p):
    """The label of the face that contains p, found by an exact ray to the right; None if the ray meets a vertex or p is on an edge."""
    if any(u[1] == p[1] or v[1] == p[1] for u, v in arr.mult):
        return None
    best = None
    for u, v in arr.mult:
        lo, hi = (u, v) if u[1] < v[1] else (v, u)
        if lo[1] < p[1] < hi[1]:
            x = lo[0] + (p[1] - lo[1]) * (hi[0] - lo[0]) / (hi[1] - lo[1])
            if x == p[0]:
                return None
            if x > p[0] and (best is None or x < best[0]):
                best = (x, (lo, hi))
    if best is None:
        return (0,) * arr.n                    # p is outside every component
    return arr.label[best[1]]                  # an upward edge right of p has p's face on its left


def random_polyline(rng, size=6):
    return [(rng.randint(0, size), rng.randint(0, size)) for _ in range(rng.randint(3, 6))]


def test_two_squares() -> None:
    a, b = [square(0, 0, 2)], [square(1, 1, 2)]
    for rule, want in ((UNION, 7), (INTERSECTION, 1), (DIFFERENCE, 3)):
        assert boolean(a, b, rule)[1] == want
    arr = Arrangement([(a[0], 0), (b[0], 1)], 2)
    half = Fraction(1, 2)
    for p, w in (((half, half), (1, 0)), ((Fraction(3, 2), Fraction(3, 2)), (1, 1)), ((Fraction(5, 2), Fraction(5, 2)), (0, 1)), ((Fraction(7, 2), half), (0, 0))):
        assert face_label(arr, p) == w == winding_at(p, arr.edges, 2)
    # the union boundary has 8 half-edges: the 8 outer pieces of the two squares
    assert len(boolean(a, b, UNION)[0]) == 8


def test_labels_match_the_exact_winding_number() -> None:
    rng = random.Random(2016)
    checked = 0
    for _ in range(30):
        polys = [(random_polyline(rng), k) for k in (0, 0, 1, 1)]
        arr = Arrangement(polys, 2)
        for _ in range(40):
            p = (Fraction(rng.randint(-20, 140), 20), Fraction(2 * rng.randint(-10, 70) + 1, 22))
            got = face_label(arr, p)
            if got is not None:
                assert got == winding_at(p, arr.edges, 2)
                checked += 1
    assert checked > 1000


def test_inclusion_exclusion_on_random_input() -> None:
    rng = random.Random(35)
    for _ in range(25):
        a = [random_polyline(rng) for _ in range(2)]
        b = [random_polyline(rng) for _ in range(2)]
        arr = Arrangement([(p, 0) for p in a] + [(p, 1) for p in b], 2)
        u, i, d = (area(arr.boundary(rule)) for rule in (UNION, INTERSECTION, DIFFERENCE))
        aa = area(arr.boundary(lambda w: w[0] > 0))
        bb = area(arr.boundary(lambda w: w[1] > 0))
        assert u + i == aa + bb
        assert d == aa - i
        assert min(u, i, d) >= 0


def test_coincident_and_touching_squares() -> None:
    a = [square(0, 0, 1)]
    edges, size = boolean(a, [square(0, 0, 1)], UNION)
    assert size == 1 and len(edges) == 4
    assert boolean(a, [square(0, 0, 1)], DIFFERENCE) == ([], 0)
    edges, size = boolean(a, [square(1, 0, 1)], UNION)
    assert size == 2 and len(edges) == 6          # the shared edge is inside and is dropped
    assert boolean(a, [square(1, 0, 1)], INTERSECTION) == ([], 0)


def test_hole_and_self_intersection() -> None:
    ring = [square(0, 0, 4), square(1, 1, 2, clockwise=True)]
    assert boolean(ring, [], UNION)[1] == 12
    # a bow tie winds +1 around its left lobe and -1 around its right lobe
    bowtie = [(0, 0), (2, 2), (2, 0), (0, 2)]
    arr = Arrangement([(bowtie, 0)], 1)
    assert face_label(arr, (Fraction(1, 2), Fraction(9, 10))) == (1,)
    assert face_label(arr, (Fraction(3, 2), Fraction(9, 10))) == (-1,)
    assert area(arr.boundary(lambda w: w[0] > 0)) == 1
    assert area(arr.boundary(lambda w: w[0] != 0)) == 2

History

Booleans of polyhedra go back to the boundary evaluation of solid modelling in the 1970s and 1980s, and exact methods to the Nef polyhedra of Walter Nef (1978) and their implementation in CGAL by Granados, Hachenberger, Hert, Kettner, Mehlhorn and Seel (2003). Winding numbers as the inside rule of polygon fill go back to early computer graphics. Jacobson, Kavan and Sorkine-Hornung used generalized winding numbers for broken meshes in 2013. Zhou, Grinspun, Zorin and Jacobson combined exact arrangements with winding number labels in 2016, and their code in the libigl library made robust mesh Booleans widely available.

References

  1. Qingnan Zhou, Eitan Grinspun, Denis Zorin and Alec Jacobson, Mesh arrangements for solid geometry, ACM Transactions on Graphics 35(4), 2016, Article 39, the exact resolution of self-intersections, the patches and cells of the arrangement, the propagation of winding numbers between cells, and the extraction of Booleans by a winding number rule
  2. M. de Berg, O. Cheong, M. van Kreveld and M. Overmars, Computational Geometry, Algorithms and Applications, third edition, Springer, 2008, Chapter 2, Line Segment Intersection, Sections 2.2 to 2.4 (the doubly connected edge list, the overlay of two subdivisions, and Boolean operations on polygons)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.output_worst
  • a full proof of time.planar_code
  • a full proof of space.arrangement
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example