Algorithm Search⌘K

Algorithmadvanced

Vertex neighborhood classification

Also called Mantyla Boolean algorithm.

Mantyla's B-rep Boolean algorithm that intersects the two boundaries, classifies the neighbourhood of each new vertex by sectors and joins the kept faces with Euler operators.

Time
O(n^2 log n) worst
Space
O(n^2) extra
Where
n = the number of edges of the two boundaries
Properties
deterministicofflineiterative
Origin
Martti Mäntylä, 1986

Vertex neighborhood classification is Mäntylä's algorithm for Boolean operations on two solids given as boundary representations. It cuts the two boundaries along their intersection, so that the new vertices lie on both solids. At each such vertex it looks at the neighborhood: the sectors between the faces of one solid around the vertex, each classified as inside, outside or on the other solid. These local decisions settle every coincident case, such as two faces in one plane or a vertex on a face. The kept faces are then joined with Euler operators into a valid B-rep of the regularized result.

In plain words

Take two solids and their skins. Find every place where the two skins cross and cut both skins there. Now every part of one skin is inside the other solid, outside it, or lies exactly on it.

Most parts are easy: follow a skin from a part you know, and the answer stays the same until you reach a cut. The hard places are the cuts. There, look closely at a tiny ball around the cut point and ask, for each wedge of the ball, whether it is inside the other solid.

Then keep the parts that you need. For a union, keep the outside parts. For an intersection, keep the inside parts. For a difference, keep the first skin outside the second, and the second skin inside the first, turned around. Join the kept parts at the cuts.

The problem

The input is two solids AA and BB given by boundary representations of manifold solids and an operation op⁡\operatorname{op} among ∪∗\cup^*, ∩∗\cap^* and −∗-^*. The output is a boundary representation of Aop⁡∗BA \operatorname{op}^* B, in the sense of the regularized set operations. This is solid Boolean operations with B-rep input. The code on this page solves the planar case: AA and BB are simple polygons with rational vertices, given counterclockwise, and the output is the set of boundary loops of the result with the region on the left of every edge.

The algorithm

The planar form has the four steps of Mäntylä's algorithm. In the plane, the neighborhood of a boundary vertex has two sectors, the inside one and the outside one, between its outgoing edge and its incoming edge.

  1. BOOLEAN(A, B, op)
  2. 1split the edges of A where they meet the boundary of B, and the edges of B likewise
  3. 2classify every edge of A against B and every edge of B against A:
  4. 3if the edge is also an edge of the other loop then on-same or on-opposite
  5. 4else if its tail v is on the other boundary then in or out by the sector of the other polygon at v that holds it
  6. 5else the class of the previous edge of the loop ▷ a loop that never meets: point in polygon
  7. 6S ← the edges that the table SELECT keeps for op, the edges of B reversed for a difference
  8. 7return CONNECT(S)
  9. CONNECT(S)
  10. 8for each edge e of S that is in no loop yet do
  11. 9start a loop with e
  12. 10at the head of the current edge, go on with the edge of S that starts there and is first clockwise from the current edge
  13. 11stop when the loop is back at e

The table SELECT says which classes each operation keeps:

operation edges of AA edges of BB
A∪∗BA \cup^* B out, on-same out
A∩∗BA \cap^* B in, on-same in
A−∗BA -^* B out, on-opposite in, reversed

An edge that lies on both boundaries is taken from AA only. When the two solids lie on the same side of a shared edge, it is on-same and stays for a union or an intersection. When they lie on opposite sides, it is on-opposite and stays only for a difference.

Line L4 is the vertex neighborhood test. Let doutd_{\text{out}} be the direction of the outgoing edge of BB at vv and dbackd_{\text{back}} the direction from vv back along its incoming edge. The inside sector of BB at vv is the counterclockwise sweep from doutd_{\text{out}} to dbackd_{\text{back}}, and the edge of AA is in when its direction falls in this sweep. The code compares angles with a rational pseudo-angle, so the test is exact.

The solid version. In three dimensions the steps are the same, with sectors between faces in place of sectors between edges:

  1. Generate. Intersect each edge of AA with the faces of BB and each edge of BB with the faces of AA. Split the edges at the intersection points, and record each new vertex as a vertex of one solid on a face of the other, or as a vertex of both.
  2. Classify. At a vertex on a face of the other solid, classify each sector of the vertex neighborhood as above, below or on the plane of that face. At a vertex of both solids, classify the pairs of sectors against each other. Reclassify the on sectors by the operation, with rules like the table above, and insert null edges between the in and out sectors.
  3. Connect. Join the null edges into loops, which become new null faces along the intersection curve.
  4. Finish. Cut each solid along its null faces, keep the pieces that the operation selects, and glue them along the null faces with Euler operators.

The planar code covers steps 1 to 3. It does not build the 3D B-rep or use Euler operators.

Example

Let AA be the square [0,2]2[0, 2]^2 and BB the square [1,3]2[1, 3]^2. The boundary of BB crosses the edges of AA at (2,1)(2, 1) and (1,2)(1, 2), so line L1 splits both loops there:

  • AA: (0,0),(2,0),(2,1),(2,2),(1,2),(0,2)(0, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2)
  • BB: (1,1),(2,1),(3,1),(3,3),(1,3),(1,2)(1, 1), (2, 1), (3, 1), (3, 3), (1, 3), (1, 2)

At (2,1)(2, 1) the outgoing edge of BB points in the direction (1,0)(1, 0) and its incoming edge goes back in the direction (−1,0)(-1, 0), so the inside sector of BB is the upper half-plane. The edge of AA from (2,1)(2, 1) to (2,2)(2, 2) points up, so it is in. The next edge, from (2,2)(2, 2) to (1,2)(1, 2), starts at a vertex that is not on BB, so line L5 gives it the class in as well. At (1,2)(1, 2) the inside sector of BB is the right half-plane, and the edge of AA toward (0,2)(0, 2) points left, so it is out.

loop edges in edges out
AA (2,1)→(2,2)→(1,2)(2, 1) \to (2, 2) \to (1, 2) the other four
BB (1,2)→(1,1)→(2,1)(1, 2) \to (1, 1) \to (2, 1) the other four

For A−∗BA -^* B, SELECT keeps the four out edges of AA and the two in edges of BB reversed, (2,1)→(1,1)→(1,2)(2, 1) \to (1, 1) \to (1, 2). CONNECT joins them into one loop with six vertices, (0,0),(2,0),(2,1),(1,1),(1,2),(0,2)(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2), the square with its upper right corner removed. Its area is 33. The union keeps the eight out edges, area 77, and the intersection keeps the four in edges, the unit square of area 11.

Touching squares show the on cases. The squares [0,2]2[0, 2]^2 and [2,4]×[0,2][2, 4] \times [0, 2] share the segment x=2x = 2. Each one has it as an edge, in opposite directions, so it is on-opposite: the union drops it and gives one loop around [0,4]×[0,2][0, 4] \times [0, 2], and the intersection is empty. The squares [0,2]2[0, 2]^2 and [2,4]2[2, 4]^2 touch at the single vertex (2,2)(2, 2). Their union has two outgoing edges at that vertex, and line L10 picks the one that keeps each square in its own loop. The result is two loops that share a vertex, which is a non-manifold point of the result.

Correctness

After line L1, an edge of AA and an edge of BB are equal or meet only at end points. So the inside of each split edge is all in the other polygon, all out of it, or on it, and the neighborhood test at line L4 reads which sector of the other polygon holds the edge near its tail. A vertex that is not on the other boundary does not change the class, which justifies line L5. Near a point inside an edge, each polygon is a whole disk, an empty disk or a half-disk, and the table SELECT lists exactly the cases where the regularized result is a half-disk. At every vertex the kept edges alternate between incoming and outgoing around the vertex, so CONNECT closes the loops. The full proof shows that the winding number of the output is 11 inside the result and 00 outside.

Proof: Vertex neighborhood classification returns the boundary of the regularized resultfull

The proof is for the planar form of the algorithm on the page. Let AA and BB be simple polygons, each given as a counterclockwise loop, so that the polygon is on the left of each edge. Let X=Aop⁡∗BX = A \operatorname{op}^* B for op in union, intersection and difference. All coordinates are rational and all signs are exact.

Lemma 1 (generate). After line L1, two edges, one of AA and one of BB, are equal as point sets or meet at most in common end points. Every point of ∂A∩∂B\partial A \cap \partial B is a vertex of both split loops or lies on a pair of equal edges.

Proof. If two original edges cross at one point, that point is a cut of both. If they overlap along a segment, the ends of the overlap are cuts of both. So after the cuts, a split edge of AA meets a split edge of BB only at an end of both, or the two edges have the same two ends and lie on one line, which makes them equal. □\square

Lemma 2 (classify). Let e=(u,w)e = (u, w) be a split edge of AA with relative interior ri⁡e\operatorname{ri} e. Exactly one of these holds, and line L3, L4 or L5 returns it: ri⁡e⊆int⁡B\operatorname{ri} e \subseteq \operatorname{int} B (in), ri⁡e∩B=∅\operatorname{ri} e \cap B = \emptyset (out), ee is an edge of BB in the same direction (on-same), or in the opposite direction (on-opposite).

Proof. If ee is not an edge of BB, then by Lemma 1 the set ri⁡e\operatorname{ri} e misses ∂B\partial B. It is connected, so it lies in int⁡B\operatorname{int} B or outside BB. This is the dichotomy. Line L3 detects the two on cases. For line L4, let uu be on ∂B\partial B. By Lemma 1, uu is a vertex of the split loop of BB, with outgoing direction doutd_{\text{out}} and the direction dbackd_{\text{back}} toward the previous vertex. Since BB is on the left of both of its edges at uu, a small disk around uu meets int⁡B\operatorname{int} B exactly in the open sector swept counterclockwise from doutd_{\text{out}} to dbackd_{\text{back}}. The direction d=w−ud = w - u differs from both, since otherwise ee would overlap an edge of BB and, by Lemma 1, be equal to it. So the points of ee near uu are in int⁡B\operatorname{int} B exactly when dd is inside the sector, which is the test of line L4 with the pseudo-angle, a strictly increasing function of the angle. For line L5, the tail uu is not on ∂B\partial B, so a small disk around uu is inside BB or outside BB, and the previous edge, which ends at uu, has the same class. The walk starts at a vertex on ∂B\partial B, so every edge reached by line L5 follows an edge already classified. If no vertex of the loop is on ∂B\partial B, then by Lemma 1 the loop misses ∂B\partial B, so the whole loop is in int⁡B\operatorname{int} B or outside BB, and one point in polygon test decides it. □\square

The same lemma holds for the edges of BB against AA.

Lemma 3 (select). Call SS the list of directed edges built at line L6. A point xx in the relative interior of a split edge lies on ∂X\partial X if and only if it lies on an edge of SS. Each such xx lies on exactly one edge of SS, and XX is on the left of that edge near xx.

Proof. Take x∈ri⁡ex \in \operatorname{ri} e for a split edge ee of AA, and a small disk UU around xx that meets no other split edge, except a copy of ee in BB. Then A∩UA \cap U is the closed half-disk HH on the left of ee. By Lemma 2, B∩UB \cap U is UU (in), ∅\emptyset (out), HH (on-same) or the closed half-disk H′H' on the right (on-opposite). The regularized result in UU for each case:

class of ee A∪∗BA \cup^* B A∩∗BA \cap^* B A−∗BA -^* B
in UU HH ∅\emptyset
out HH ∅\emptyset HH
on-same HH HH ∅\emptyset
on-opposite UU ∅\emptyset HH

For on-opposite, H∩H′H \cap H' is the segment, whose regularization is empty, and H∖H′H \setminus H' is HH without the segment, whose regularization is HH. The point xx is on ∂X\partial X exactly in the cells with HH, and then XX is on the left of ee. These cells are the classes that the table SELECT keeps from AA. Now take x∈ri⁡ex \in \operatorname{ri} e for a split edge ee of BB that is not an edge of AA. Then B∩UB \cap U is the half-disk GG on the left of ee, and A∩UA \cap U is UU or ∅\emptyset. The result is UU or GG for the union, GG or ∅\emptyset for the intersection, and for the difference it is the closed half-disk on the right of ee when ee is in AA, and ∅\emptyset when ee is out of AA. These are the classes kept from BB, and for the difference the edge is reversed, which puts the result on its left. The on edges of BB are equal to edges of AA and are never kept from BB, so each boundary point is on one edge of SS only. □\square

Lemma 4 (connect). At every vertex vv, the edges of SS that start at vv and those that end at vv alternate in angular order around vv, and there are as many of each. So the rule of line L10 is a bijection from the edges that end at vv to the edges that start at vv, and CONNECT splits SS into closed loops that use each edge once.

Proof. Let χ\chi be the indicator of XX. Walk counterclockwise on a small circle around vv that meets only the split edges at vv. By Lemma 3, χ\chi changes exactly where the circle crosses an edge of SS, and XX is on the left of that edge. An edge that starts at vv has its left side counterclockwise from it, so the walk enters XX there. An edge that ends at vv has its left side clockwise from it, so the walk leaves XX there. Since χ\chi takes only the values 00 and 11, entries and exits alternate around the circle, which gives the claim. Rotating clockwise from the direction of an incoming edge, the next edge met is an outgoing one, so line L10 picks the outgoing edge next to it in clockwise order, which is a bijection. A bijection at each vertex makes the successor map a permutation of SS, so each traced loop returns to its first edge. □\square

Theorem. BOOLEAN(A,B,op⁡)(A, B, \operatorname{op}) returns loops whose union is ∂X\partial X, with XX on the left of every edge. For every point xx not on the loops, the winding number of the loops around xx is 11 if x∈Xx \in X and 00 otherwise.

Proof. By Lemma 3, every point of ∂X\partial X in the relative interior of a split edge is on an edge of SS, and every edge of SS lies in ∂X\partial X. The rest of ∂X\partial X is a finite set of vertices, which are end points of edges of SS because ∂X\partial X has no isolated points for a regular closed set. By Lemma 4, the loops use exactly the edges of SS. For the winding number ww, both ww and χ\chi are 00 far away, both are constant off the edges of SS and off ∂X\partial X, and both jump by +1+1 when a path crosses an edge of SS from its right to its left at a relative interior point, by Lemma 3. Any two points off the edges can be joined by a path that crosses edges only at such points, since the vertices are finite. So w=χw = \chi off the loops. ■\blacksquare

Termination. GENERATE and CLASSIFY loop over finite lists. Each step of CONNECT marks one new edge as used, so it ends after ∣S∣|S| steps.

From the plane to space. In three dimensions, Lemma 2 becomes the classification of the sectors around a vertex: the cones between consecutive faces at that vertex, each in, out, or on a face of the other solid with the same or the opposite normal. Lemma 3 becomes the same table for the face pieces, and Lemma 4 becomes the step that joins the cut edges of the two solids into the new faces. The planar proof does not cover the Euler operator steps of the solid version.

Complexity

The costs are in the real RAM, for the planar code with nn edges in all.

  • Generate. All pairs of edges are tested, O(n2)O(n^2), and there are k=O(n2)k = O(n^2) cut points. Sorting the cuts along each edge costs O(n2log⁡n)O(n^2 \log n) in all.
  • Classify. Each of the O(n+k)O(n + k) split edges costs one lookup and one sector test. With the vertices kept in a sorted table, this is O((n+k)log⁡n)O((n + k) \log n).
  • Connect. Each kept edge is chosen once, among the edges at its vertex.

So the time is O(n2log⁡n)O(n^2 \log n) and the space is O(n2)O(n^2). With a sweep that reports only the kk actual crossings, the generate step costs O((n+k)log⁡n)O((n + k) \log n). For solids, generate tests edges against faces, and practical systems cut the work with bounding boxes.

Properties

  • Local decisions. Each in, out or on answer comes from the sectors around one vertex, so coincident faces and edges need no global special case.
  • Regularized. The table SELECT drops shared faces that the result does not bound, such as the face between two touching solids in a union.
  • Exact when the signs are exact. All decisions are signs of orientation tests. With rational input they are exact, and the output is the exact boundary.
  • The result may be non-manifold. Two solids that touch along an edge or at a vertex give a result whose boundary is not a 2-manifold there. A B-rep for 2-manifolds must split such a vertex or edge into copies.

Variants and improvements

  • Polygon clipping. In the plane the same problem is polygon clipping. Vatti clipping uses a sweep instead of vertex neighborhoods and works on any number of polygons with holes.
  • Robust set operations. Hoffmann, Hopcroft and Karasick worked in floating point and kept the topological decisions consistent with each other, so that a sign that cannot be trusted is derived from decisions already made.
  • Meshes. For triangle meshes, mesh Boolean operations use the same generate and classify plan, with a winding number or a ray test as the classifier.
  • Non-manifold structures. With a radial edge data structure, the result can keep the shared edges and vertices of touching solids instead of splitting them.

When to use it

Use it to combine two solids that are already B-reps, which is the usual case in a modeler that stores B-reps and applies one Boolean at a time. It fits faceted models with exact or filtered predicates. For a solid given as a CSG tree, boundary evaluation builds the B-rep from the whole tree at once. For triangle soups with self-intersections, use a mesh method.

Pitfalls

  • Classifying by a sample point only. A test at the midpoint of an edge says on for both on-same and on-opposite. The decision needs the direction, which only the neighborhood gives. With the touching squares, a midpoint test cannot tell that the shared edge goes for a union and stays for a difference.
  • Taking an on edge twice. If the shared edges are kept from both polygons, the output has a doubled edge and a loop that runs back along itself.
  • The wrong exit at a touching vertex. At a vertex with two outgoing edges, taking the first one counterclockwise instead of clockwise joins the two touching squares into one loop that passes the vertex twice. The area and the winding numbers are still right, but the loop does not match the two faces that a B-rep needs, and a later Euler operator that splits the loop at the vertex is required.
  • Inconsistent rounded signs. In floating point, the cut point of two edges may be classified differently from each of the two edges, and the loops then do not close. Compute the cut points and the signs exactly, or derive the uncertain signs from earlier ones as Hoffmann, Hopcroft and Karasick do. See the geometric robustness problem.

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.

vertex_neighborhood_classification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-neighborhood-classification/. The authors are listed in prov/QA5D08.jsonl.

"""Mantyla's Boolean operation by vertex neighborhood classification, in the plane.

This is the two-dimensional form of the algorithm. A solid is a simple polygon,
a list of points in counterclockwise order. Its boundary is a closed loop of
edges, and the neighborhood of a boundary vertex is a set of two sectors
between the incoming and the outgoing edge: the inside sector and the outside
sector. In three dimensions the sectors lie between the faces around a vertex,
and the same four steps apply: generate, classify, select, connect.

The result of boolean(A, B, op) is the boundary of the regularized set
A op* B, as a list of loops. Each loop is a list of points, the region is on
the left of every edge, so outer loops are counterclockwise and holes are
clockwise. Coordinates are int or Fraction, and every sign is exact.
"""

from fractions import Fraction
from typing import Union

Num = Union[int, Fraction]
Point = tuple

IN, OUT, ON_SAME, ON_OPPOSITE = "in", "out", "on-same", "on-opposite"

# Which edges each operation keeps: (classes kept from A, classes kept from B, B reversed?)
SELECT = {
    "union": ({OUT, ON_SAME}, {OUT}, False),
    "intersection": ({IN, ON_SAME}, {IN}, False),
    "difference": ({OUT, ON_OPPOSITE}, {IN}, True),
}


def cross(o: Point, a: Point, b: Point) -> Num:
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def pseudo_angle(x: Num, y: Num) -> Fraction:
    """A rational number in [0, 4) that increases with the angle of (x, y)."""
    if y >= 0 and x > 0 or (x == 0 and y > 0):
        return Fraction(y) / (x + y)
    if x <= 0 and y >= 0:
        return 1 + Fraction(-x) / (-x + y)
    if x < 0 or (x == 0 and y < 0):
        return 2 + Fraction(-y) / (-x - y)
    return 3 + Fraction(x) / (x - y)


def turn(d0: Point, d1: Point) -> Fraction:
    """The counterclockwise rotation from direction d0 to direction d1, in (0, 4] pseudo-angle units."""
    r = (pseudo_angle(*d1) - pseudo_angle(*d0)) % 4
    return r if r != 0 else Fraction(4)


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 _meet(p: Point, q: Point, r: Point, s: Point) -> list:
    """The points where the segments pq and rs meet: none, one, or the two ends of an overlap."""
    d1, d2, d3, d4 = cross(r, s, p), cross(r, s, q), cross(p, q, r), cross(p, q, s)
    if d1 == d2 == 0:  # collinear: the ends that lie on the other segment
        return [x for x in (p, q, r, s) if _on_segment(x, p, q) and _on_segment(x, r, s)]
    if (d1 > 0) == (d2 > 0) and d1 != 0 and d2 != 0:
        return []
    if (d3 > 0) == (d4 > 0) and d3 != 0 and d4 != 0:
        return []
    t = Fraction(d1) / (d1 - d2)
    return [(p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1]))]


def generate(P: list, Q: list) -> list:
    """Split the edges of polygon P at every point where they meet the boundary of Q."""
    out = []
    n, m = len(P), len(Q)
    for i in range(n):
        p, q = P[i], P[(i + 1) % n]
        cuts = set()
        for j in range(m):
            cuts.update(_meet(p, q, Q[j], Q[(j + 1) % m]))
        d = (q[0] - p[0], q[1] - p[1])
        key = lambda x: (x[0] - p[0]) * d[0] + (x[1] - p[1]) * d[1]
        inner = sorted((x for x in cuts if x != p and x != q), key=key)
        out.append(p)
        out.extend(inner)
    return out


def point_in_polygon(x: Point, P: list) -> bool:
    """Crossing number test for a point that is not on the boundary of P."""
    inside = False
    for i in range(len(P)):
        a, b = P[i], P[(i + 1) % len(P)]
        if (a[1] > x[1]) != (b[1] > x[1]):
            if (cross(a, b, x) > 0) == (b[1] > a[1]):
                inside = not inside
    return inside


def classify(P: list, Q: list) -> list:
    """The class of each edge of the split loop P with respect to the split loop Q."""
    n, m = len(P), len(Q)
    edges_q = {(Q[j], Q[(j + 1) % m]) for j in range(m)}
    where = {Q[j]: j for j in range(m)}
    cls = [None] * n
    starts = [i for i in range(n) if P[i] in where]
    if not starts:  # the loops do not meet: one containment test for the whole loop
        mid = tuple((P[0][k] + P[1][k]) / Fraction(2) for k in range(2))
        return [IN if point_in_polygon(mid, Q) else OUT] * n
    for step in range(n):
        i = (starts[0] + step) % n
        u, w = P[i], P[(i + 1) % n]
        if (u, w) in edges_q:  # @line L3
            cls[i] = ON_SAME
        elif (w, u) in edges_q:
            cls[i] = ON_OPPOSITE
        elif u in where:  # @line L4
            j = where[u]
            nxt, prv = Q[(j + 1) % m], Q[j - 1]
            d_out = (nxt[0] - u[0], nxt[1] - u[1])
            d_back = (prv[0] - u[0], prv[1] - u[1])
            d = (w[0] - u[0], w[1] - u[1])
            cls[i] = IN if turn(d_out, d) < turn(d_out, d_back) else OUT  # the inside sector of Q at u
        else:
            cls[i] = cls[i - 1]  # @line L5
    return cls


def connect(edges: list) -> list:
    """Join directed edges into loops; at a vertex with two exits take the first one clockwise."""
    out_of = {}
    for e in edges:
        out_of.setdefault(e[0], []).append(e)
    used = set()
    loops = []
    for e in edges:  # @line L8
        if e in used:
            continue
        loop, cur = [e[0]], e  # @line L9
        used.add(e)
        while True:
            v = cur[1]
            back = (cur[0][0] - v[0], cur[0][1] - v[1])
            nxt = min(out_of[v], key=lambda f: turn((f[1][0] - v[0], f[1][1] - v[1]), back))  # @line L10
            if nxt == e:  # @line L11
                break
            if nxt in used:
                raise ValueError("the selected edges do not form loops")
            loop.append(v)
            used.add(nxt)
            cur = nxt
        loops.append(loop)
    return loops


def boolean(A: list, B: list, op: str) -> list:
    """The boundary loops of A op* B for counterclockwise simple polygons A and B."""
    SA, SB = generate(A, B), generate(B, A)  # @line L1
    ca, cb = classify(SA, SB), classify(SB, SA)  # @line L2
    keep_a, keep_b, reverse_b = SELECT[op]
    S = [(SA[i], SA[(i + 1) % len(SA)]) for i in range(len(SA)) if ca[i] in keep_a]  # @line L6
    for i in range(len(SB)):
        if cb[i] in keep_b:
            u, w = SB[i], SB[(i + 1) % len(SB)]
            S.append((w, u) if reverse_b else (u, w))
    return connect(S)  # @line L7


def winding_number(x: Point, loops: list) -> int:
    """The winding number of the loops around a point that is on none of them."""
    w = 0
    for P in loops:
        for i in range(len(P)):
            a, b = P[i], P[(i + 1) % len(P)]
            if a[1] <= x[1] < b[1] and cross(a, b, x) > 0:
                w += 1
            elif b[1] <= x[1] < a[1] and cross(a, b, x) < 0:
                w -= 1
    return w


def area(loops: list) -> Fraction:
    """The signed area of the region bounded by the loops (shoelace formula)."""
    s = Fraction(0)
    for P in loops:
        for i in range(len(P)):
            a, b = P[i], P[(i + 1) % len(P)]
            s += a[0] * b[1] - a[1] * b[0]
    return s / 2
test_vertex_neighborhood_classification.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-neighborhood-classification/. The authors are listed in prov/QA5D08.jsonl.

import random
import unittest
from fractions import Fraction

from vertex_neighborhood_classification import area, boolean, classify, generate, winding_number

F = Fraction
OPS = {
    "union": lambda a, b: a or b,
    "intersection": lambda a, b: a and b,
    "difference": lambda a, b: a and not b,
}


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


def inside(x, P):
    """Even-odd test for a point off the boundary, written apart from the module under test."""
    c = 0
    for i in range(len(P)):
        a, b = P[i], P[(i + 1) % len(P)]
        if (a[0] > x[0]) != (b[0] > x[0]):
            y = a[1] + F(x[0] - a[0]) * (b[1] - a[1]) / (b[0] - a[0])
            c += y > x[1]
    return c % 2 == 1


def on_boundary(x, P):
    for i in range(len(P)):
        a, b = P[i], P[(i + 1) % len(P)]
        if cross(a, b, x) == 0 and min(a[0], b[0]) <= x[0] <= max(a[0], b[0]) \
                and min(a[1], b[1]) <= x[1] <= max(a[1], b[1]):
            return True
    return False


def slice_length(x, A, B, op):
    """Length of the vertical line at x inside A op B, by the plain formula at midpoints."""
    ys = set()
    for P in (A, B):
        for i in range(len(P)):
            a, b = P[i], P[(i + 1) % len(P)]
            if a[0] != b[0] and min(a[0], b[0]) <= x <= max(a[0], b[0]):
                ys.add(a[1] + F(x - a[0]) * (b[1] - a[1]) / (b[0] - a[0]))
    ys = sorted(ys)
    total = F(0)
    for y0, y1 in zip(ys, ys[1:]):
        m = (x, (y0 + y1) / 2)
        if OPS[op](inside(m, A), inside(m, B)):
            total += y1 - y0
    return total


def brute_area(A, B, op):
    """Area of A op B: the slice length is linear between event abscissas, so midpoints are exact."""
    xs = {p[0] for p in A + B}
    for i in range(len(A)):
        p, q = A[i], A[(i + 1) % len(A)]
        for j in range(len(B)):
            r, s = B[j], B[(j + 1) % len(B)]
            d = (q[0] - p[0]) * (s[1] - r[1]) - (q[1] - p[1]) * (s[0] - r[0])
            if d != 0:
                t = F((r[0] - p[0]) * (s[1] - r[1]) - (r[1] - p[1]) * (s[0] - r[0])) / d
                u = F((r[0] - p[0]) * (q[1] - p[1]) - (r[1] - p[1]) * (q[0] - p[0])) / d
                if 0 <= t <= 1 and 0 <= u <= 1:
                    xs.add(p[0] + t * (q[0] - p[0]))
    xs = sorted(xs)
    return sum((x1 - x0) * slice_length((x0 + x1) / 2, A, B, op) for x0, x1 in zip(xs, xs[1:]))


DIRS = [(1, 0), (2, 1), (1, 1), (1, 2), (0, 1), (-1, 2), (-1, 1), (-2, 1),
        (-1, 0), (-2, -1), (-1, -1), (-1, -2), (0, -1), (1, -2), (1, -1), (2, -1)]  # by angle


def random_polygon(rng):
    """A star-shaped simple polygon around an integer center, counterclockwise."""
    while True:
        idx = sorted(rng.sample(range(16), rng.randint(3, 7)))
        dirs = [DIRS[i] for i in idx]
        if all(cross((0, 0), dirs[k], dirs[(k + 1) % len(dirs)]) > 0 for k in range(len(dirs))):
            break
    c = (rng.randint(2, 4), rng.randint(2, 4))
    pts = []
    for d in dirs:
        r = rng.choice([1, 1, 2]) if max(abs(d[0]), abs(d[1])) == 1 else 1
        pts.append((c[0] + r * d[0], c[1] + r * d[1]))
    return pts


SQ1 = [(0, 0), (2, 0), (2, 2), (0, 2)]
SQ2 = [(1, 1), (3, 1), (3, 3), (1, 3)]


class TestVertexNeighborhoodClassification(unittest.TestCase):
    def test_worked_example(self):
        SA, SB = generate(SQ1, SQ2), generate(SQ2, SQ1)
        self.assertEqual(SA, [(0, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2)])
        self.assertEqual(SB, [(1, 1), (2, 1), (3, 1), (3, 3), (1, 3), (1, 2)])
        self.assertEqual(classify(SA, SB), ["out", "out", "in", "in", "out", "out"])
        self.assertEqual(classify(SB, SA), ["in", "out", "out", "out", "out", "in"])
        self.assertEqual(area(boolean(SQ1, SQ2, "union")), 7)
        self.assertEqual(area(boolean(SQ1, SQ2, "intersection")), 1)
        self.assertEqual(area(boolean(SQ1, SQ2, "difference")), 3)
        self.assertEqual(len(boolean(SQ1, SQ2, "difference")[0]), 6)

    def test_touching_squares(self):
        R = [(2, 0), (4, 0), (4, 2), (2, 2)]  # shares the edge x = 2 with SQ1
        self.assertEqual(classify(generate(SQ1, R), generate(R, SQ1))[1], "on-opposite")
        self.assertEqual(boolean(SQ1, R, "intersection"), [])
        self.assertEqual(area(boolean(SQ1, R, "union")), 8)
        self.assertEqual(sorted(boolean(SQ1, R, "difference")[0]), sorted(SQ1))
        C = [(2, 2), (4, 2), (4, 4), (2, 4)]  # touches SQ1 at one corner
        loops = boolean(SQ1, C, "union")
        self.assertEqual(len(loops), 2)
        self.assertEqual(area(loops), 8)
        self.assertEqual(boolean(SQ1, C, "intersection"), [])

    def test_same_and_nested(self):
        self.assertEqual(area(boolean(SQ1, SQ1, "union")), 4)
        self.assertEqual(boolean(SQ1, SQ1, "difference"), [])
        inner = [(F(1, 2), F(1, 2)), (F(3, 2), F(1, 2)), (F(3, 2), F(3, 2)), (F(1, 2), F(3, 2))]
        loops = boolean(SQ1, inner, "difference")
        self.assertEqual(len(loops), 2)  # an outer loop and a clockwise hole
        self.assertEqual(sorted(area([lp]) for lp in loops), [-1, 4])

    def test_random_against_point_membership_and_area(self):
        rng = random.Random(1986)
        grid = [(F(i, 4), F(j, 4)) for i in range(-1, 30, 3) for j in range(-1, 30, 3)]
        degenerate = 0
        for _ in range(150):
            A, B = random_polygon(rng), random_polygon(rng)
            degenerate += any(on_boundary(p, B) for p in A)
            for op in OPS:
                loops = boolean(A, B, op)
                self.assertEqual(area(loops), brute_area(A, B, op))
                for x in grid:
                    if on_boundary(x, A) or on_boundary(x, B):
                        continue
                    w = winding_number(x, loops)
                    self.assertEqual(w, int(OPS[op](inside(x, A), inside(x, B))))
        self.assertGreater(degenerate, 20)


if __name__ == "__main__":
    unittest.main()

History

Mäntylä published vertex neighborhood classification in 1986 for 2-manifold boundary models, and his book of 1988 treats Boolean operations on half-edge models. Requicha and Voelcker's merging algorithms of 1985 combined a B-rep with a new primitive by classification with neighborhoods, and Hoffmann, Hopcroft and Karasick turned to the consistency of the decisions in floating point in 1989.

References

  1. Martti Mäntylä, Boolean operations of 2-manifolds through vertex neighborhood classification, ACM Transactions on Graphics 5(1), 1 to 29, 1986, the whole paper (the generate, classify and connect steps, the vertex neighborhoods and their sectors, and the reclassification of the on sectors for each operation)
  2. Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on Boolean set operations for the half-edge data structure (chapter number not confirmed)
  3. Christoph M. Hoffmann, Geometric and Solid Modeling, An Introduction, Morgan Kaufmann, 1989, Chapter 3, Boolean operations on boundary representations
  4. Christoph M. Hoffmann, John E. Hopcroft and Michael S. Karasick, Robust set operations on polyhedral solids, IEEE Computer Graphics and Applications 9(6), 50 to 59, 1989, the whole paper (set operations on polyhedra in floating point that keep the topological decisions consistent)

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.worst
  • a full proof of space.extra
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
  • a scene preset for the example