Algorithm Search⌘K

Data structureintro

Constructive solid geometry

Also called CSG, CSG tree.

Represents a solid as a tree whose leaves are primitive solids and whose inner nodes are regularized union, intersection, difference and rigid motions.

Time
O(n) worst
Space
Θ(n) extra
Where
n = the number of nodes of the tree

Constructive solid geometry (CSG) describes a solid as a formula. The leaves of a tree are primitive solids, such as blocks, cylinders and spheres, and each inner node is a regularized union, intersection or difference of its two children, or a rigid motion of its one child. A block with a pocket is the tree A−∗SA -^* S: the block AA minus the box SS of the pocket. The tree is short and easy to edit, and it keeps the design history. But it does not list faces or edges: to answer a question about the solid, an algorithm must evaluate the tree. This page builds CSG trees of axis-aligned boxes with integer corners, and classifies a point as inside, on the boundary of or outside the regularized solid, with exact arithmetic.

In plain words

Think of a workshop. You start from simple blocks, glue blocks together, cut one block out of another, and turn or move a block. A CSG tree writes down these steps as a recipe, not the shape that comes out.

To ask if a point is in the solid, put the question to each block in the recipe, and combine the answers with the same steps. For a point inside the material or out in the air, this is enough. For a point exactly on a surface, the plain answers can be wrong: a cut can remove the floor of a pocket from the solid, though the floor is part of the surface. The fix is to ask about the space very close to the point, in all directions, and to combine those answers.

The abstract type

A CSG tree is built from these constructors:

  • BOX(lo,hi)\mathrm{BOX}(lo, hi): the closed box [lox,hix]×[loy,hiy]×[loz,hiz][lo_x, hi_x] \times [lo_y, hi_y] \times [lo_z, hi_z], with lo<hilo < hi on each axis.
  • A∪∗BA \cup^* B, A∩∗BA \cap^* B and A−∗BA -^* B: the regularized operations of the two subtrees.
  • MOVE(R,t,A)\mathrm{MOVE}(R, t, A): the set {Rx+t:x∈A}\{R x + t : x \in A\}, a rotation RR followed by a translation tt.

The main query is CLASSIFY(T,p)\mathrm{CLASSIFY}(T, p), which returns IN if pp is inside the solid of TT, ON if it is on its boundary, and OUT if not. Other queries, such as ray casting for pictures and the volume, are built on classification, and the set membership classification page gives the general form for lines and surfaces.

The solid of a tree is the regularized value of its formula. By fact 7 of the regularized set operations page, it does not matter whether each node regularizes or only the root does: r(Φ)=Φ∗r(\Phi) = \Phi^*. A CSG tree of r-sets is valid by construction, since the r-sets are closed under the regularized operations, and it is unambiguous, since a tree has one value. It is not unique: A∪∗BA \cup^* B, B∪∗AB \cup^* A and (A−∗B)∪∗B(A -^* B) \cup^* B are different trees for the same solid. To decide whether two trees give the same solid, a program must evaluate them, for example to B-reps, and compare the results.

Representation

A tree node is one of:

node fields
box lolo, hihi: integer corners
operation the kind (union, intersection or difference) and the two children
motion a rotation RR by quarter turns, an integer translation tt, and the child

Here the rotations are the 24 rotations of the cube, the signed permutation matrices with determinant 1. With these, every face of every primitive stays on an axis plane xj=cx_j = c with an integer cc. A tree can also be a directed acyclic graph, where one subtree is used several times; the queries below work the same way on it.

Operations

The idea is to classify the 8 open octants at pp instead of pp itself. For s∈{−1,+1}3s \in \{-1, +1\}^3, let the octant OsO_s be the set of points p+εs′p + \varepsilon s' for small ε>0\varepsilon > 0 and s′s' with the signs of ss. All faces are on axis planes, so for small ε\varepsilon each octant lies inside or outside each primitive as a whole. MASK(TT, pp) is the set of octants that lie inside the ordinary (not regularized) value of TT.

  1. MASK(T, p) ▷ the octants s ∈ {−1, +1}³ near p that are inside T
  2. 1if T = BOX(lo, hi): return {s : for each axis j, lo_j < p_j < hi_j, or p_j = lo_j and s_j = +1, or p_j = hi_j and s_j = −1}
  3. 2if T = MOVE(R, t, A): return {s : Rᵀ s ∈ MASK(A, Rᵀ(p − t))}
  4. 3a ← MASK(left(T), p); b ← MASK(right(T), p)
  5. 4if T is a union: return a ∪ b
  6. 5if T is an intersection: return a ∩ b
  7. 6return a \ b ▷ difference
  8. CLASSIFY(T, p)
  9. 7m ← MASK(T, p)
  10. 8if m = ∅ then return OUT
  11. 9if m has all 8 octants then return IN
  12. 10return ON

A mask is an 8-bit word, so lines L4 to L6 are one OR, AND or AND NOT. Line L2 moves the point and the 8 directions back into the frame of the child, and R−1=RTR^{-1} = R^T for a rotation. All values are integers or fractions, so all tests are exact.

Why the octants are enough. At a point pp, the axis planes through pp cut a small ball around pp into 8 open octants and some pieces of planes. Each octant is wholly inside or wholly outside each primitive, so the ordinary formula gives one answer for each whole octant, and this answer is the regularized one, because the octants are open. The interior of the solid near pp is the union of the inside octants and the plane pieces between them, so pp is in the closure of the interior exactly when at least one octant is inside. If all 8 are inside, the whole ball is inside, and pp is an interior point.

Points in general position. If pp is on no face plane, then pp and all its octants are on the same side of each primitive, so the mask is all or nothing, and CLASSIFY is the ordinary formula at pp. This is the cheap test that many programs use. It is right almost everywhere, and wrong exactly where it matters for a boundary model.

For general primitives, such as cylinders and tilted planes, the octants are not enough, because a face can pass between two octants. Then a classifier keeps a neighbourhood of pp, the set of directions at pp that point into the solid, and combines neighbourhoods with the same Boolean operations. Tilove gives this method, and the set membership classification page describes it.

Example

Take the block A=[0,4]×[0,4]×[0,2]A = [0, 4] \times [0, 4] \times [0, 2] and the pocket S=[1,3]×[1,3]×[1,3]S = [1, 3] \times [1, 3] \times [1, 3], and let T=A−∗ST = A -^* S, a block with a square pocket of depth 1 in its top. The table gives the number of inside octants of each node, the size of its mask, and the result:

point where octants in AA octants in SS octants in TT CLASSIFY ordinary formula
(2,2,12)(2, 2, \tfrac12) under the pocket 8 0 8 IN in
(2,2,1)(2, 2, 1) the floor of the pocket 8 4 4 ON not in
(2,2,32)(2, 2, \tfrac32) in the pocket 8 8 0 OUT not in
(1,1,1)(1, 1, 1) a lower corner of the pocket 8 1 7 ON not in
(1,2,2)(1, 2, 2) the rim of the pocket 4 4 2 ON not in
(0,0,0)(0, 0, 0) a corner of the block 1 0 1 ON in

At (2,2,1)(2, 2, 1), the point is on the closed box SS, so the ordinary difference removes it. But the floor of the pocket is part of the surface of the solid, and the 4 octants below it are inside. At (1,2,2)(1, 2, 2) on the rim, only the 2 octants with sx=−1s_x = -1 and sz=−1s_z = -1 are inside: the edge of the rim is convex. At (1,1,1)(1, 1, 1), 7 of the 8 octants are inside, which is a concave corner.

Correctness

MASK(TT, pp) is the set of octants at pp that lie inside the ordinary value of TT. For a box this follows from line L1, axis by axis. For an operation it follows because an octant lies in A∪BA \cup B, A∩BA \cap B or A∖BA \setminus B exactly when it lies in AA or BB, in both or in AA but not BB, as each octant is wholly in or out of each set. For a motion, the point p+εsp + \varepsilon s is in {Rx+t:x∈A}\{Rx + t : x \in A\} exactly when RT(p−t)+εRTsR^T(p - t) + \varepsilon R^T s is in AA, and RTsR^T s is again a sign vector. Fact 7 of the regularized operations page says that the regularized value differs from the ordinary one only on the faces of the primitives, which have no volume, so the inside octants are the same for both. CLASSIFY then reads IN, ON or OUT from the mask as explained above. The recursion visits each node of the tree once, so it stops. The full proof is in the proof file.

The tests check CLASSIFY and MASK against a voxel brute force. All corners are integers, so the regularized solid is a union of closed unit cells, and a cell belongs to it exactly when its centre is in the ordinary formula. For random trees of depth 4 with motions, the tests compare the mask at points of the half-integer grid with the cells that the 8 points p+s/4p + s/4 fall in, and the class at points on no plane with the ordinary formula.

Proof: The octant mask classifies every point exactly against the regularized solid of a CSG tree of axis-aligned boxesfull

We use the pseudocode of the page. A tree TT is built from closed boxes with lo<hilo < hi on each axis and integer corners, the operations ∪\cup, ∩\cap, ∖\setminus and motions x↦Rx+tx \mapsto R x + t with RR a signed permutation matrix of determinant 1 and tt an integer vector. Write [T][T] for the ordinary value of the formula, with the ordinary set operations on closed boxes, and T∗T^* for the regularized value. The point pp has rational coordinates. For s∈{−1,+1}3s \in \{-1, +1\}^3 and ε>0\varepsilon > 0 let ps(ε)=p+εsp_s(\varepsilon) = p + \varepsilon s.

Lemma 1 (the leaf planes). Every face of every box, moved by the motions above it, lies on a plane xj=cx_j = c with cc an integer. So [T][T] is a finite union of sets of the form ∏jIj\prod_j I_j where each IjI_j is a point, an open interval or a closed interval with integer ends, and its value changes only across such planes.

Proof. A signed permutation maps the plane xj=cx_j = c to a plane xj′=±cx_{j'} = \pm c, and an integer translation keeps the right side an integer. The faces of a box lie on such planes. The rest follows by induction on the tree, since unions, intersections and differences of products of intervals with integer ends are finite unions of such products. □\square

Let δ(p)>0\delta(p) > 0 be the distance from pp to the nearest integer plane xj=cx_j = c that does not contain pp; it exists because the coordinates of pp are rational, and for 0<ε<δ(p)0 < \varepsilon < \delta(p) the point ps(ε)p_s(\varepsilon) is on no integer plane and on the same side of each integer plane through pp as every other ps′(ε′)p_{s'}(\varepsilon') with s′s' having the signs of ss and 0<ε′<δ(p)0 < \varepsilon' < \delta(p). Call the set of such points the octant OsO_s. It is open, and by Lemma 1 it is wholly inside or wholly outside [T][T] for every tree TT, because no plane on which [T][T] can change crosses it.

Lemma 2 (MASK). MASK(TT, pp) ={s:Os⊆[T]}= \{s : O_s \subseteq [T]\}.

Proof. By induction on TT. For a box, Os⊆[lo,hi]O_s \subseteq [lo, hi] holds exactly when for each axis jj, the points pj+εsjp_j + \varepsilon s_j with 0<ε<δ(p)0 < \varepsilon < \delta(p) lie in [loj,hij][lo_j, hi_j]. If loj<pj<hijlo_j < p_j < hi_j this is true for both signs, since lojlo_j and hijhi_j are integers and so at distance at least δ(p)\delta(p) from pjp_j or equal to it. If pj=lojp_j = lo_j, it is true only for sj=+1s_j = +1, because loj<hijlo_j < hi_j; if pj=hijp_j = hi_j, only for sj=−1s_j = -1; and if pjp_j is outside [loj,hij][lo_j, hi_j], it is false. This is line L1. For an operation, each OsO_s is wholly in or out of [A][A] and of [B][B], so Os⊆[A]∪[B]O_s \subseteq [A] \cup [B] exactly when Os⊆[A]O_s \subseteq [A] or Os⊆[B]O_s \subseteq [B], and similarly for ∩\cap and ∖\setminus, which are lines L3 to L6. For a motion, p+εs∈{Rx+t:x∈[A]}p + \varepsilon s \in \{R x + t : x \in [A]\} exactly when RT(p−t)+εRTs∈[A]R^T(p - t) + \varepsilon R^T s \in [A], since R−1=RTR^{-1} = R^T. The vector RTsR^T s is again in {−1,+1}3\{-1, +1\}^3, the point RT(p−t)R^T(p - t) is rational, and the octant of RTsR^T s at RT(p−t)R^T(p - t) is the image of OsO_s under the inverse motion, so the induction hypothesis for AA gives line L2. □\square

Lemma 3 (the regularized value near pp). Let UU be the open ball of radius δ(p)\delta(p) around pp. Then int⁡[T]∩U\operatorname{int} [T] \cap U and int⁡T∗∩U\operatorname{int} T^* \cap U contain the same octants, and p∈T∗p \in T^* exactly when some Os⊆[T]O_s \subseteq [T], and p∈int⁡T∗p \in \operatorname{int} T^* exactly when all eight Os⊆[T]O_s \subseteq [T].

Proof. Let NN be the union of the integer planes through pp; U∖NU \setminus N is the union of the eight octants. By fact 7 of the regularized set operations page, T∗=r([T])T^* = r([T]), where r(X)=cl⁡(int⁡X)r(X) = \operatorname{cl}(\operatorname{int} X). An octant is open, so if it lies in [T][T] it lies in int⁡[T]\operatorname{int}[T], and so in r([T])r([T]). If an octant does not lie in [T][T], it is disjoint from [T][T], so it is an open set disjoint from int⁡[T]\operatorname{int}[T], and it is disjoint from cl⁡(int⁡[T])\operatorname{cl}(\operatorname{int}[T]) too. So inside U∖NU \setminus N, T∗T^* is the union of the octants in MASK. Now N∩UN \cap U has empty interior, so int⁡[T]∩U⊆cl⁡(int⁡[T]∩(U∖N))\operatorname{int} [T] \cap U \subseteq \operatorname{cl}(\operatorname{int}[T] \cap (U \setminus N)), which is the closure of the union of the inside octants, intersected with UU. If some octant is inside, pp is in its closure, so p∈T∗p \in T^*. If none is, int⁡[T]∩U=∅\operatorname{int}[T] \cap U = \emptyset, so p∉cl⁡(int⁡[T])=T∗p \notin \operatorname{cl}(\operatorname{int}[T]) = T^*. If all eight are inside, the closure of their union contains UU, so U⊆T∗U \subseteq T^* and p∈int⁡T∗p \in \operatorname{int} T^*. If some octant OsO_s is not inside, it is disjoint from T∗T^* by the argument above, and pp is in its closure, so pp is a limit of points outside T∗T^*, and p∉int⁡T∗p \notin \operatorname{int} T^*. □\square

Theorem. CLASSIFY(TT, pp) returns IN if p∈int⁡T∗p \in \operatorname{int} T^*, ON if p∈∂T∗p \in \partial T^*, and OUT if p∉T∗p \notin T^*. It stops after O(n)O(n) steps for a tree of nn nodes.

Proof. By Lemma 2, line L7 computes {s:Os⊆[T]}\{s : O_s \subseteq [T]\}. By Lemma 3, the mask is empty exactly when p∉T∗p \notin T^*, full exactly when p∈int⁡T∗p \in \operatorname{int} T^*, and otherwise p∈T∗∖int⁡T∗=∂T∗p \in T^* \setminus \operatorname{int} T^* = \partial T^*, since T∗T^* is closed. Lines L8 to L10 return these answers. Each call of MASK on a node makes at most two calls on its children and a constant amount of other work, and the tree is finite, so the recursion stops after one visit per node. □\square

Corollary (general position). If pp is on no integer plane, then MASK(TT, pp) is empty or full, and CLASSIFY(TT, pp) is IN exactly when p∈[T]p \in [T].

Proof. Then no integer plane passes through pp, so the ball UU meets no plane on which [T][T] changes, and UU is wholly in or out of [T][T]; the mask is full or empty by Lemma 2, and p∈[T]p \in [T] exactly when it is full. □\square

The tests check the theorem against an independent brute force. By Lemma 1 the regularized solid is the union of the closed unit cells c+[0,1]3c + [0, 1]^3 whose centres lie in [T][T], and the octant OsO_s at a point pp of the half-integer grid lies in the cell that contains p+s/4p + s/4. The tests compare the mask with these cells at random half-integer points of random trees, and the class with the ordinary formula at random points with denominator 7, which lie on no integer plane. ■\blacksquare

Complexity

Let nn be the number of nodes.

  • CLASSIFY and MASK take O(n)O(n) time: each node does a constant amount of work on 8-bit words and exact numbers. On a directed acyclic graph with shared subtrees, the time is linear in the size of the tree that the graph unfolds to, unless the masks are cached per node.
  • The tree takes Θ(n)\Theta(n) space.
  • Classifying qq points takes O(qn)O(qn) time. Programs that classify many points, as in ray casting or volume estimation, prune the tree with bounding boxes: a subtree whose box does not contain pp gives the empty mask at once.

Variants

  • General primitives. Real CSG systems use half-spaces, cylinders, cones, spheres, tori and swept solids. Points in general position are classified by the sign of each surface function, and boundary points by neighbourhoods.
  • Ray casting. CSG ray casting classifies whole rays: it intersects the ray with each primitive and combines the intervals by the tree, which gives pictures and volumes.
  • Boundary evaluation. Boundary evaluation computes the B-rep of the solid of a tree by classifying the faces of the primitives. The reverse, B-rep to CSG conversion, finds a tree for a given B-rep.
  • Function representation. In F-rep, each primitive is a real function, and union and intersection become max and min or smooth versions of them. The tree is the same, but the result is one function for the whole solid.
  • Voxels and octrees. A tree can be converted to a spatial occupancy enumeration by classifying the cells, as the tests do.

When to use it

Use CSG when solids are made from simple primitives and the design history matters: in mechanical design front ends, in parametric models whose dimensions change, in ray-traced pictures of designs and in teaching. CSG trees are small and always valid, and Booleans on them are free, since a Boolean is just a new node. Use a B-rep when the application needs the faces and edges themselves, for example for tool paths and drawings, and evaluate the tree to a B-rep once.

Pitfalls

  • Ordinary operations at boundary points. The ordinary formula at a point on a face can be wrong, as the floor of the pocket in the example shows. Classify the neighbourhood, not the point, or move the point off all faces first.
  • Coincident faces. Many CSG models have faces of two primitives on the same plane, for example a pocket whose top is level with the top of the block. With floating-point faces, the two planes can differ by a rounding error, and a thin sheet or slot appears. Exact coordinates or a common tolerance avoid this.
  • Not unique. Two trees can give the same solid. Do not compare solids by comparing trees, and do not expect a tree from a B-rep to be the tree the user built.
  • Dangling results are empty. Two blocks that touch along a face have an empty regularized intersection, though the ordinary intersection is that face. A program that expects a face there gets nothing.
  • Unbounded primitives. Half-spaces are useful leaves, but a tree that is not bounded is not an r-set, for example the complement of a block. Check that the root is bounded.

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.

constructive_solid_geometry.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constructive-solid-geometry/. The authors are listed in prov/QD8QB3.jsonl.

"""A CSG tree of axis-aligned boxes with regularized point membership.

The leaves are closed boxes with integer corners. The inner nodes are union,
intersection, difference and rigid motions that keep the axes: a rotation by
quarter turns (a signed permutation matrix with determinant 1) followed by an
integer translation. The tree describes the regularized result.

CLASSIFY(p) returns IN, ON or OUT for the regularized solid at any point with
integer or Fraction coordinates. It evaluates the tree at p + e*s for the 8
directions s in {-1, +1}^3 and all small e > 0 at once. All planes of all
leaves are axis planes, so each of these 8 open octants at p lies wholly inside
or wholly outside each leaf, and the ordinary set operations on the octants
give the regularized result.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Sequence, Union as TUnion

Num = TUnion[int, Fraction]
ALL = 0xFF  # the 8 octants
IN, ON, OUT = "in", "on", "out"


def octant(i: int) -> tuple[int, int, int]:
    """The direction s of octant i: bit j of i says s_j = +1."""
    return tuple(1 if i >> j & 1 else -1 for j in range(3))  # type: ignore[return-value]


def index(s: Sequence[int]) -> int:
    return sum(1 << j for j in range(3) if s[j] > 0)


class Node:
    def mask(self, p: Sequence[Num]) -> int:
        raise NotImplementedError

    def classify(self, p: Sequence[Num]) -> str:
        m = self.mask(p)  # @line L7
        if m == 0:  # @line L8
            return OUT
        if m == ALL:  # @line L9
            return IN
        return ON  # @line L10

    def raw(self, p: Sequence[Num]) -> bool:
        """The ordinary, not regularized, membership of p in the closed sets."""
        raise NotImplementedError

    def bound(self) -> tuple[tuple[int, ...], tuple[int, ...]]:
        """A box that contains the solid."""
        raise NotImplementedError

    def __or__(self, other: "Node") -> "Node":
        return Op("union", self, other)

    def __and__(self, other: "Node") -> "Node":
        return Op("intersection", self, other)

    def __sub__(self, other: "Node") -> "Node":
        return Op("difference", self, other)


class Box(Node):
    def __init__(self, lo: Sequence[int], hi: Sequence[int]) -> None:
        if any(a >= b for a, b in zip(lo, hi)):
            raise ValueError("a box needs lo < hi on every axis")
        self.lo, self.hi = tuple(lo), tuple(hi)

    def mask(self, p: Sequence[Num]) -> int:
        m = ALL  # @line L1
        for j in range(3):
            if p[j] == self.lo[j]:
                m &= sum(1 << i for i in range(8) if i >> j & 1)  # only s_j = +1 enters the box
            elif p[j] == self.hi[j]:
                m &= sum(1 << i for i in range(8) if not i >> j & 1)  # only s_j = -1
            elif not self.lo[j] < p[j] < self.hi[j]:
                return 0
        return m

    def raw(self, p: Sequence[Num]) -> bool:
        return all(self.lo[j] <= p[j] <= self.hi[j] for j in range(3))

    def bound(self):
        return self.lo, self.hi


class Op(Node):
    def __init__(self, kind: str, a: Node, b: Node) -> None:
        if kind not in ("union", "intersection", "difference"):
            raise ValueError(kind)
        self.kind, self.a, self.b = kind, a, b

    def mask(self, p: Sequence[Num]) -> int:
        ma, mb = self.a.mask(p), self.b.mask(p)  # @line L3
        if self.kind == "union":
            return ma | mb  # @line L4
        if self.kind == "intersection":
            return ma & mb  # @line L5
        return ma & ~mb & ALL  # @line L6

    def raw(self, p: Sequence[Num]) -> bool:
        a, b = self.a.raw(p), self.b.raw(p)
        if self.kind == "union":
            return a or b
        if self.kind == "intersection":
            return a and b
        return a and not b

    def bound(self):
        (alo, ahi), (blo, bhi) = self.a.bound(), self.b.bound()
        if self.kind == "union":
            return tuple(map(min, alo, blo)), tuple(map(max, ahi, bhi))
        if self.kind == "intersection":
            lo, hi = tuple(map(max, alo, blo)), tuple(map(min, ahi, bhi))
            if any(x > y for x, y in zip(lo, hi)):
                return alo, alo  # empty: any degenerate box will do
            return lo, hi
        return alo, ahi


def rotation(axis: int, quarter_turns: int) -> tuple[tuple[int, ...], ...]:
    """The matrix of a rotation by quarter_turns * 90 degrees about an axis, counterclockwise."""
    r = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
    b, c = (axis + 1) % 3, (axis + 2) % 3
    for _ in range(quarter_turns % 4):
        # multiply on the right by the quarter turn e_b -> e_c, e_c -> -e_b
        new = [row[:] for row in r]
        for i in range(3):
            new[i][b] = r[i][c]
            new[i][c] = -r[i][b]
        r = new
    return tuple(tuple(row) for row in r)


def mat_vec(r, v):
    return tuple(sum(r[i][j] * v[j] for j in range(3)) for i in range(3))


def transpose(r):
    return tuple(tuple(r[j][i] for j in range(3)) for i in range(3))


class Move(Node):
    """The set {R x + t : x in child}, R a rotation by quarter turns and t an integer vector."""

    def __init__(self, child: Node, r=None, t: Sequence[int] = (0, 0, 0)) -> None:
        self.child = child
        self.r = r if r is not None else rotation(0, 0)
        self.rt = transpose(self.r)
        self.t = tuple(t)
        self.perm = [index(mat_vec(self.rt, octant(i))) for i in range(8)]

    def _back(self, p):
        return mat_vec(self.rt, tuple(p[j] - self.t[j] for j in range(3)))

    def mask(self, p: Sequence[Num]) -> int:
        m = self.child.mask(self._back(p))  # @line L2
        return sum(1 << i for i in range(8) if m >> self.perm[i] & 1)

    def raw(self, p: Sequence[Num]) -> bool:
        return self.child.raw(self._back(p))

    def bound(self):
        lo, hi = self.child.bound()
        a, b = mat_vec(self.r, lo), mat_vec(self.r, hi)
        return (tuple(min(x, y) + t for x, y, t in zip(a, b, self.t)),
                tuple(max(x, y) + t for x, y, t in zip(a, b, self.t)))


def neighbourhood(node: Node, p: Sequence[Num]) -> list[tuple[int, int, int]]:
    """The octant directions at p that are inside the regularized solid."""
    m = node.mask(p)
    return [octant(i) for i in range(8) if m >> i & 1]
test_constructive_solid_geometry.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constructive-solid-geometry/. The authors are listed in prov/QD8QB3.jsonl.

import itertools
import random
import unittest
from fractions import Fraction

from constructive_solid_geometry import ALL, IN, ON, OUT, Box, Move, Op, mat_vec, octant, rotation

HALF = Fraction(1, 2)
QUARTER = Fraction(1, 4)


def det(r):
    return (r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1])
            - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0])
            + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]))


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        lo = [rng.randrange(0, 5) for _ in range(3)]
        hi = [a + rng.randrange(1, 4) for a in lo]
        return Box(lo, hi)
    r = rng.random()
    if r < 0.15:
        rot = rotation(rng.randrange(3), rng.randrange(4))
        t = [rng.randrange(-2, 3) for _ in range(3)]
        return Move(random_tree(rng, depth - 1), rot, t)
    kind = "union" if r < 0.55 else "intersection" if r < 0.7 else "difference"
    return Op(kind, random_tree(rng, depth - 1), random_tree(rng, depth - 1))


def cells_of(tree):
    """The brute force: the unit cells whose centres are in the ordinary set.
    Every leaf plane is an integer plane, so no centre is on a plane, and the
    regularized solid is the union of these closed cells."""
    lo, hi = tree.bound()
    out = set()
    for c in itertools.product(*(range(lo[j] - 1, hi[j] + 1) for j in range(3))):
        if tree.raw(tuple(x + HALF for x in c)):
            out.add(c)
    return out


def cell_of(q):
    return tuple(int(x // 1) for x in q)


def brute_classify(cells, p):
    """IN, ON or OUT from the closed cells that contain p."""
    around = [cell_of(tuple(p[j] + s[j] * QUARTER for j in range(3))) for s in map(octant, range(8))]
    n = sum(1 for c in around if c in cells)
    return IN if n == 8 else OUT if n == 0 else ON


class CSGTests(unittest.TestCase):
    def test_rotations(self):
        self.assertEqual(mat_vec(rotation(2, 1), (1, 0, 0)), (0, 1, 0))
        self.assertEqual(mat_vec(rotation(0, 1), (0, 1, 0)), (0, 0, 1))
        self.assertEqual(mat_vec(rotation(1, 1), (0, 0, 1)), (1, 0, 0))
        mats = set()
        for a, k, b, l in itertools.product(range(3), range(4), range(3), range(4)):
            r1, r2 = rotation(a, k), rotation(b, l)
            m = tuple(tuple(sum(r1[i][x] * r2[x][j] for x in range(3)) for j in range(3)) for i in range(3))
            self.assertEqual(det(m), 1)
            mats.add(m)
        self.assertEqual(len(mats), 24)  # the rotation group of the cube

    def test_regularized_difference(self):
        a = Box((0, 0, 0), (2, 2, 2))
        b = Box((1, 0, 0), (3, 2, 2))
        t = a - b
        p = (1, 1, 1)
        self.assertFalse(t.raw(p))  # the ordinary difference loses the face x = 1
        self.assertEqual(t.classify(p), ON)  # the regularized one keeps it
        self.assertEqual(t.classify((HALF, 1, 1)), IN)
        self.assertEqual(t.classify((Fraction(3, 2), 1, 1)), OUT)

    def test_dangling_face(self):
        a = Box((0, 0, 0), (2, 2, 2))
        c = Box((2, 0, 0), (4, 2, 2))
        t = a & c
        self.assertTrue(t.raw((2, 1, 1)))  # the ordinary intersection is the face x = 2
        for p in itertools.product(*(range(0, 5) for _ in range(3))):
            self.assertEqual(t.mask(p), 0)
            self.assertEqual(t.classify(p), OUT)

    def test_not_unique(self):
        a = Box((0, 0, 0), (2, 2, 2))
        b = Box((1, 0, 0), (3, 2, 2))
        trees = [a | b, b | a, (a - b) | b, Box((0, 0, 0), (3, 2, 2)),
                 Move(Box((0, -3, 0), (2, 0, 2)), rotation(2, 1), (0, 0, 0)) | b]
        for p in itertools.product(*(range(-2, 9) for _ in range(3))):
            p = tuple(Fraction(x, 2) for x in p)
            self.assertEqual(len({t.classify(p) for t in trees}), 1, p)

    def test_vertex_neighbourhood(self):
        a = Box((0, 0, 0), (2, 2, 2))
        notch = a - Box((1, 1, 1), (3, 3, 3))  # a cube with one corner cut out
        self.assertEqual(notch.mask((1, 1, 1)), ALL & ~(1 << 7))  # all octants but (+,+,+)
        self.assertEqual(notch.classify((1, 1, 1)), ON)
        self.assertEqual(notch.classify((2, 2, 2)), OUT)
        self.assertEqual(notch.classify((2, 1, 1)), ON)

    def test_random_trees(self):
        rng = random.Random(1980)
        on_seen = in_seen = 0
        for trial in range(40):
            tree = random_tree(rng, 4)
            cells = cells_of(tree)
            lo, hi = tree.bound()
            for _ in range(300):
                p = tuple(Fraction(rng.randrange(2 * (lo[j] - 1), 2 * (hi[j] + 1) + 1), 2) for j in range(3))
                want = brute_classify(cells, p)
                got = tree.classify(p)
                self.assertEqual(got, want, (trial, p))
                mask = tree.mask(p)
                for i in range(8):
                    s = octant(i)
                    c = cell_of(tuple(p[j] + s[j] * QUARTER for j in range(3)))
                    self.assertEqual(bool(mask >> i & 1), c in cells)
                on_seen += got == ON
                in_seen += got == IN
            for _ in range(100):  # points on no plane: CLASSIFY is the ordinary formula
                p = tuple(Fraction(7 * rng.randrange(lo[j] - 1, hi[j] + 1) + rng.randrange(1, 7), 7) for j in range(3))
                got = tree.classify(p)
                self.assertIn(got, (IN, OUT))
                self.assertEqual(got == IN, tree.raw(p))
            for c in cells:
                self.assertTrue(all(lo[j] <= c[j] and c[j] + 1 <= hi[j] for j in range(3)))
        self.assertGreater(on_seen, 500, (on_seen, in_seen))
        self.assertGreater(in_seen, 100, (on_seen, in_seen))


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

History

Voelcker and Requicha's Production Automation Project at the University of Rochester developed CSG in the 1970s, with the PADL modelers as its systems. Requicha and Tilove gave the regularized operations in 1978. Requicha's survey of 1980 put CSG and the B-rep into one theory of representation schemes, with validity, unambiguity and uniqueness as properties of a scheme. In the same year, Tilove gave set membership classification, the method that classifies points, lines and faces against a tree with neighbourhoods. Roth's ray casting of 1982 made pictures of CSG trees, and boundary evaluation turned CSG trees into B-reps in the modelers of the 1980s.

References

  1. Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the sections on representation schemes, their validity, unambiguity and uniqueness, and on CSG
  2. Robert B. Tilove, Set membership classification, a unified approach to geometric intersection problems, IEEE Transactions on Computers C-29(10), 874 to 883, 1980, the classification of points and of other candidate sets against a CSG tree, and the neighbourhoods that the regularized operations need
  3. Aristides A. G. Requicha and Robert B. Tilove, Mathematical foundations of constructive solid geometry, general topology of closed regular sets, Production Automation Project Technical Memorandum 27, University of Rochester, 1978, the closed regular sets, the regularized operations and their Boolean algebra
  4. Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on constructive models, CSG trees and the algorithms on them
  5. Aristides A. G. Requicha and Herbert B. Voelcker, Boolean operations in solid modeling, boundary evaluation and merging algorithms, Proceedings of the IEEE 73(1), 30 to 44, 1985, the sections on set membership classification and on neighbourhoods

Where this leads

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)
WritingW4 complete
  • a review of the text: no review record reviews/QD8QB3/text.yaml