Algorithm Search⌘K

Algorithmcore

Subdivision surface intersection

Also called recursive subdivision intersection.

Intersects two Bezier patches by splitting them with de Casteljau's algorithm and dropping pairs whose boxes do not overlap, until the pieces are flat.

Time
O(16^k n d) worst
Space
O(k n + r) extra
Where
d = the sum of the two degrees of a patch; k = the number of halvings after which every piece is flat; n = the number of control points of a patch; r = the number of output leaves
Properties
deterministicnot exactrecursive
Origin
J. M. Lane, R. F. Riesenfeld, 1980

Subdivision intersects two Bézier patches by divide and conquer. It compares the bounding boxes of the two control nets: if they do not overlap, the patches cannot meet, by the convex hull property, and the pair is dropped. Otherwise the larger patch is split into four quarters with de Casteljau's algorithm, and the method recurses on the new pairs, until both pieces are flat and their corner triangles can be intersected directly. Lane and Riesenfeld developed the method in 1980, and it is the robust partner of marching: it never drops a piece that holds an intersection point, but its output is a set of short segments, not an ordered curve.

In plain words

Two curved sheets are each held inside a box that is easy to compute from their control points. If the two boxes do not touch, the sheets do not touch, and there is nothing more to do. If the boxes touch, cut one sheet into four smaller sheets. Each small sheet has a smaller box, so now more of the empty space can be thrown away.

Keep cutting the pairs that still touch. Pieces become flatter as they get smaller, and when both pieces of a pair are nearly flat, treat them as two flat tiles and intersect the tiles. The little segments from all the tiles, put together, approximate the curve where the sheets cross.

A piece of the curve can never be thrown away, because a box is only dropped when it is empty of the other sheet.

The problem

The input is two tensor-product Bézier patches P(u,v)P(u, v) and Q(s,t)Q(s, t) over [0,1]2[0, 1]^2, given by their control nets, and a flatness tolerance ε>0\varepsilon > 0. The output is a list of leaves: pairs of parameter rectangles (RP,RQ)(R_P, R_Q) whose pieces still overlap, each with the segments where the corner triangles of the two pieces meet. The task is the surface surface intersection problem, with the requirement that no intersection point is lost: every point P(u,v)=Q(s,t)P(u, v) = Q(s, t) must have (u,v)∈RP(u, v) \in R_P and (s,t)∈RQ(s, t) \in R_Q for some leaf. Coincident and touching patches are allowed inputs. The page uses exact rational control points, so every comparison is decided without error.

The algorithm

  1. SUBDIVIDE(P, Q, ε)
  2. 1if box(P) and box(Q) do not overlap then return ▷ convex hull property
  3. 2if P is not flat and (Q is flat or box(P) is at least as large as box(Q)) then
  4. 3for each quarter P_k of P, by de Casteljau at the midpoints, do SUBDIVIDE(P_k, Q, ε)
  5. 4else if Q is not flat then
  6. 5for each quarter Q_k of Q do SUBDIVIDE(P, Q_k, ε)
  7. 6else intersect the two corner triangles of P with the two of Q
  8. 7output the leaf (R_P, R_Q) with the segments found at L6

The box of a piece is the axis-aligned box of its control points; two boxes overlap when their coordinate ranges overlap in all three axes, with touching counted as overlap. A piece is flat when every control point lies within ε\varepsilon of the plane through three of its corners, a=P00a = P_{00}, b=Pp0b = P_{p0} and c=P0qc = P_{0q}. The normal of that plane is n=(b−a)×(c−a)n = (b - a) \times (c - a), by the right-hand rule, which points the same way as the outward normal Pu×PvP_u \times P_v of the patch. A quarter is computed by splitting each column of the control net at u=1/2u = 1/2 and then each row at v=1/2v = 1/2; the four new nets describe the patch over the four quarters of its rectangle, exactly.

Line L2 splits the piece with the larger box, so the two pieces stay of similar size, and never splits a flat piece. A flat piece is never split again, so a plane patch stays whole. The corner triangles of a piece with corners a,b,c,da, b, c, d are abcabc and acdacd. Line L6 intersects each triangle of one piece with each triangle of the other by the standard test: the signs of n1⋅(x−a1)n_1 \cdot (x - a_1) at the vertices of the second triangle, and the other way round, decide whether the planes separate them, and the cut segments are clipped against each other along the line n1×n2n_1 \times n_2. Two coplanar triangles are flagged instead of cut. The implementation also stops at a depth cap and outputs such pieces as leaves marked not flat, so that a degenerate input cannot recurse for ever.

Example

Let PP be the saddle z=uvz = uv, the bilinear patch with control points (0,0,0)(0, 0, 0), (1,0,0)(1, 0, 0), (0,1,0)(0, 1, 0) and (1,1,1)(1, 1, 1), and let QQ be the plane patch z=1/4z = 1/4 over the unit square. They meet in the hyperbola arc uv=1/4uv = 1/4 for 1/4≤u≤11/4 \le u \le 1. Take ε=1/16\varepsilon = 1/16. Because PP is bilinear, the zz range of its box over [u0,u1]×[v0,v1][u_0, u_1] \times [v_0, v_1] is exactly [u0v0,u1v1][u_0 v_0, u_1 v_1], so the trace can be checked by hand.

level pairs tested at L1 dropped result
0 the whole PP with QQ 0 QQ is flat; PP is not: (1,1,1)(1, 1, 1) is at distance 11 from the plane z=0z = 0 of the other corners; split PP
1 four quarters of side 1/21/2 0 the zz ranges [0,1/4][0, 1/4], [0,1/2][0, 1/2], [0,1/2][0, 1/2] and [1/4,1][1/4, 1] all reach z=1/4z = 1/4; in each quarter the fourth corner is 1/41/4 above the plane of the other three in zz, and more than 1/161/16 from it; split all
2 sixteen pieces of side 1/41/4 8 eight boxes reach z=1/4z = 1/4; the fourth corner is now 1/161/16 above the plane in zz, so at most 1/161/16 from it, and all eight are flat leaves

The eight dropped pieces include [0,1/4]2[0, 1/4]^2, with z≤1/16z \le 1/16, and [3/4,1]2[3/4, 1]^2, with z≥9/16z \ge 9/16. Three kept pieces only touch the plane, at the points (1/2,1/2)(1/2, 1/2), (1/4,1)(1/4, 1) and (1,1/4)(1, 1/4) of the curve, and are kept because touching counts as overlap. In all, line L1 runs 2121 times and line L6 runs 8×4=328 \times 4 = 32 triangle tests, which give 2222 segments. For the leaf [1/4,1/2]×[1/2,3/4][1/4, 1/2] \times [1/2, 3/4] the segments run from (1/2,1/2,1/4)(1/2, 1/2, 1/4) to (3/8,5/8,1/4)(3/8, 5/8, 1/4) to (1/3,3/4,1/4)(1/3, 3/4, 1/4). The end points are on the curve, and the middle point has xy=15/64xy = 15/64, off by 1/641/64. With ε=1/64\varepsilon = 1/64 and 1/2561/256 the method keeps 1414 and 2626 leaves of side 1/81/8 and 1/161/16, and the largest error ∣xy−1/4∣|xy - 1/4| of a segment point is 1/2561/256 and 1/10241/1024, a quarter of ε\varepsilon in each case.

Correctness

The pieces of a patch over a rectangle are Bézier patches whose control nets come from de Casteljau's algorithm, and each lies in the convex hull of its control points, because the Bernstein polynomials are nonnegative and sum to one. So if a point x=P(u,v)=Q(s,t)x = P(u, v) = Q(s, t) has its parameters in the rectangles of a pair, xx is in both boxes, and line L1 does not drop the pair. The four quarters cover the rectangle, so the parameters of xx are in one of the new pairs. By induction on the recursion, every intersection point is in the rectangles of an output leaf, whatever the input, as long as the recursion ends. It ends because of the depth cap, and for regular patches, where Pu×Pv≠0P_u \times P_v \ne 0, it ends without the cap: a piece of side hh is within Ch2C h^2 of its corner plane, so pieces become flat after a bounded number of halvings. In a flat leaf, both pieces lie within ε\varepsilon of their corner planes. The full proof gives the details.

What is proved is that no intersection point is lost and that the recursion ends. How close the segments are to the true curve is measured on the example, not proved: a leaf can hold no intersection at all, because boxes are larger than the pieces, and its triangles can still meet or miss.

Proof: Subdivision loses no intersection point and ends for regular patchesfull

Let PP and QQ be tensor-product Bézier patches of degrees (p,q)(p, q) and (p′,q′)(p', q') over [0,1]2[0, 1]^2. A piece of PP is a pair (N,R)(N, R) of a control net and a closed rectangle R=[u0,u1]×[v0,v1]R = [u_0, u_1] \times [v_0, v_1]; it represents PP on RR if the patch of NN at (a,b)∈[0,1]2(a, b) \in [0, 1]^2 equals P(u0+a(u1−u0),v0+b(v1−v0))P(u_0 + a(u_1 - u_0), v_0 + b(v_1 - v_0)). A witness for a pair of pieces (NP,RP)(N_P, R_P), (NQ,RQ)(N_Q, R_Q) is a quadruple (u,v,s,t)(u, v, s, t) with (u,v)∈RP(u, v) \in R_P, (s,t)∈RQ(s, t) \in R_Q and P(u,v)=Q(s,t)P(u, v) = Q(s, t). The arithmetic is exact, so every comparison in SUBDIVIDE is decided correctly.

Lemma 1 (quarters). If (N,R)(N, R) represents PP on RR, the four quarters computed by L3 represent PP on the four quarters of RR.

Proof. For a Bézier curve, the two halves of the de Casteljau scheme at t=1/2t = 1/2 are the control polygons of the curve on [0,1/2][0, 1/2] and on [1/2,1][1/2, 1], each reparametrized over [0,1][0, 1]; this is the subdivision property of the de Casteljau algorithm. Write the patch as ∑iBi(a)ci(b)\sum_i B_i(a) c_i(b), with ci(b)=∑jBj(b)Nijc_i(b) = \sum_j B_j(b) N_{ij}. For fixed bb the patch is a Bézier curve in aa with control points ci(b)c_i(b), and these depend linearly on the columns N⋅jN_{\cdot j}, so splitting every column at a=1/2a = 1/2 splits the patch in aa. Splitting every row of each half at b=1/2b = 1/2 splits it in bb in the same way. Composing the affine maps of the parameters gives the claim. □\square

Lemma 2 (hull). If (N,R)(N, R) represents PP on RR, then P(R)P(R) lies in the convex hull of the points of NN, and so in box(N)(N).

Proof. The Bernstein polynomials of each degree are nonnegative on [0,1][0, 1] and sum to one, so the products Bi(a)Bj(b)B_i(a) B_j(b) are nonnegative and sum to one, and each value of the patch is a convex combination of the control points. The convex hull of a finite set lies in its axis-aligned box. □\square

Lemma 3 (no witness is dropped). If a pair of pieces has a witness (u,v,s,t)(u, v, s, t), then line L1 keeps the pair, and if the pair is split at L3 or L5, one of the new pairs has the same witness.

Proof. The point x=P(u,v)=Q(s,t)x = P(u, v) = Q(s, t) lies in box(NP)(N_P) and in box(NQ)(N_Q) by Lemma 2, so the boxes share xx and overlap; L1 counts touching as overlap, so it keeps the pair. The four quarters of RPR_P cover RPR_P, so one of them contains (u,v)(u, v), and by Lemma 1 it is a piece that represents PP there. The same holds for QQ at L5. □\square

Lemma 4 (flat pieces). Assume Pu×Pv≠0P_u \times P_v \ne 0 on [0,1]2[0, 1]^2. There is a constant CC such that, for every piece of PP over a square of side h≤1h \le 1 made by Lemma 1, every control point lies within Ch2C h^2 of the plane through the corners N00N_{00}, Np0N_{p0} and N0qN_{0q}, and these corners are not collinear when hh is small.

Proof. Let the square be [α,α+h]×[β,β+h][\alpha, \alpha + h] \times [\beta, \beta + h], and let B\mathcal{B} be the blossom of PP, the unique function that is symmetric and affine in each of its pp first and qq last arguments and agrees with PP on the diagonal. The control points of the piece are the blossom values Nij=B(α⟨p−i⟩,(α+h)⟨i⟩;β⟨q−j⟩,(β+h)⟨j⟩)N_{ij} = \mathcal{B}(\alpha^{\langle p - i \rangle}, (\alpha + h)^{\langle i \rangle}; \beta^{\langle q - j \rangle}, (\beta + h)^{\langle j \rangle}). Expand B\mathcal{B} around (α,…;β,…)(\alpha, \ldots; \beta, \ldots). Since it is a polynomial of degree one in each argument, Nij=P(α,β)+ihpPu+jhqPv+EijN_{ij} = P(\alpha, \beta) + \tfrac{i h}{p} P_u + \tfrac{j h}{q} P_v + E_{ij}, where the partial derivatives are taken at (α,β)(\alpha, \beta) and ∣Eij∣≤C1h2|E_{ij}| \le C_1 h^2, with C1C_1 a bound on the mixed second partial derivatives of B\mathcal{B} over [0,1][0, 1], which is finite because B\mathcal{B} is a polynomial. So every control point is within C1h2C_1 h^2 of the tangent plane Π\Pi at (α,β)(\alpha, \beta). Let m>0m > 0 be the minimum of ∣Pu×Pv∣|P_u \times P_v| on [0,1]2[0, 1]^2 and let ν\nu be the unit normal of Π\Pi. The three corners are a=P(α,β)a = P(\alpha, \beta), b=a+hPu+O(h2)b = a + h P_u + O(h^2) and c=a+hPv+O(h2)c = a + h P_v + O(h^2), so (b−a)×(c−a)=h2(Pu×Pv)+O(h3)(b - a) \times (c - a) = h^2 (P_u \times P_v) + O(h^3). Its length is at least h2m−O(h3)>0h^2 m - O(h^3) > 0 for small hh, so the corners are not collinear, and its unit vector ν′\nu' satisfies ∣ν′−ν∣=O(h)|\nu' - \nu| = O(h). For each control point, Nij−a=ihpPu+jhqPv+EijN_{ij} - a = \tfrac{ih}{p} P_u + \tfrac{jh}{q} P_v + E_{ij} has length O(h)O(h), and ν⋅(Nij−a)=ν⋅Eij=O(h2)\nu \cdot (N_{ij} - a) = \nu \cdot E_{ij} = O(h^2). Hence ∣ν′⋅(Nij−a)∣≤∣ν⋅(Nij−a)∣+∣ν′−ν∣ ∣Nij−a∣=O(h2)|\nu' \cdot (N_{ij} - a)| \le |\nu \cdot (N_{ij} - a)| + |\nu' - \nu| \, |N_{ij} - a| = O(h^2). All OO constants depend only on bounds of the derivatives of PP and on mm, so they are uniform over all squares. □\square

Lemma 5 (termination). Under the depth cap, SUBDIVIDE ends on every input. If both patches satisfy the assumption of Lemma 4, it also ends without the cap, and every output leaf is flat.

Proof. With the cap, every path of the recursion has length at most the cap, and each call makes at most four calls, so the tree is finite. Without the cap, let k0k_0 be such that C4−k0≤εC 4^{-k_0} \le \varepsilon and the corners are not collinear at side 2−k02^{-k_0}, for both patches (Lemma 4). Every piece is a square of side 2−j2^{-j} after jj splits of its patch, and a piece with j≥k0j \ge k_0 is flat. Line L2 splits PP only when PP is not flat, and L4 splits QQ only when QQ is not flat. So along a path, PP is split at most k0k_0 times and QQ at most k0k_0 times, the depth is at most 2k02 k_0, and the tree is finite. A call that reaches L6 has two flat pieces, so its leaf is flat. □\square

Theorem. SUBDIVIDE(P,Q,ε)(P, Q, \varepsilon) ends, and for every intersection point P(u,v)=Q(s,t)P(u, v) = Q(s, t) there is an output leaf (RP,RQ)(R_P, R_Q) with (u,v)∈RP(u, v) \in R_P and (s,t)∈RQ(s, t) \in R_Q. If both patches are regular, the leaves are flat without the depth cap, and every intersection point xx of a leaf lies within ε\varepsilon of the corner planes of both pieces.

Proof. Termination is Lemma 5. The root pair, the two patches over [0,1]2[0, 1]^2, has every intersection point as a witness. By Lemma 3, a pair with a witness is never dropped at L1, and when it is split, the witness passes to a child. The recursion is finite, so following the witness from the root ends at a call that neither drops the pair nor splits it, and that call outputs a leaf, at L7 or at the depth cap; that leaf has the witness. For the last claim, the control points of a flat piece lie in the closed slab of half width ε\varepsilon around its corner plane, and the slab is convex, so the convex hull of the control points, and by Lemma 2 the piece, lie in the slab. An intersection point of the leaf is on both pieces, so it is in both slabs. ■\blacksquare

What is not claimed. The theorem does not say that a leaf holds an intersection point: boxes are larger than the pieces, so a leaf can be empty. It does not bound the distance from the segments of line L6 to the curve; on the example of the page that distance is measured, a quarter of ε\varepsilon in ∣xy−1/4∣|xy - 1/4|. And it does not say that the leaves of a regular input are few: if the patches touch along a curve, the number of leaves grows like ε−1\varepsilon^{-1}. The proof needs exact comparisons at L1: with boxes that are rounded inward, Lemma 3 fails.

Complexity

The costs are in the real RAM. Splitting a patch with nn control points and degrees pp and qq costs O(n(p+q))=O(nd)O(n(p + q)) = O(nd), and a box or a flatness test costs O(n)O(n). The pair tree has four children at each split, and each of the two patches is split at most kk times along a path, so it has at most 16k16^k nodes in the worst case, which gives O(16knd)O(16^k n d) time. This worst case is reached by coincident patches, where every pair overlaps. For two regular patches that cross along a curve, only the pairs near the curve survive, and the number of leaves grows like the length of the curve divided by the side of a leaf, about ε−1/2\varepsilon^{-1/2}, as the example shows. The extra space is O(kn)O(kn) for the recursion and O(r)O(r) for the rr leaves. With rational arithmetic, each halving adds a few bits to each coordinate.

Properties

  • Nothing is lost. Every intersection point is in some leaf, for every input, including touching and coincident patches. This is the main reason to use subdivision.
  • Unordered output. The leaves come in the order of the recursion, not along the curve. Joining the segments into curves is a separate step.
  • False leaves. A leaf can hold no intersection, because a box can overlap the other piece while the patch does not. The triangle test of line L6 usually removes such leaves from the curve, since it finds no segment.
  • Exact decisions, approximate curve. With rational control points every box test and every sign is decided exactly, but the segments are only an approximation of the curve, with error that shrinks like the square of the leaf size.

Variants and improvements

  • Better bounding volumes. Axis-aligned boxes are cheap but loose; a large tilted flat patch has a box that covers much empty space. Oriented boxes, slabs normal to a fixed direction, or the convex hull itself drop more pairs. Bézier clipping uses a fat plane around one patch to cut away a range of the other patch's parameters at each step, not just a half.
  • A hierarchy. Storing the pieces of each patch in a bounding volume hierarchy lets one patch be tested against many others, as in a Boolean operation on two models.
  • Hybrid with marching. Subdivide only until the loop test of Sederberg and Meyers shows that no pair holds a closed loop, then intersect the boundaries of the pieces to get start points, and trace the curve with marching. This gives an ordered, accurate curve that has no missed branch.
  • B-splines and NURBS. Insert knots to split a B-spline patch into Bézier patches, or split it directly by knot insertion; for rational patches the convex hull property holds when all weights are positive.
  • Interval and exact versions. In floating point, round the boxes outward with interval arithmetic, so that the convex hull argument still holds.

When to use it

Use subdivision when no part of the intersection may be missed: to find all components and small loops, to find start points for marching, or for coincident and touching patches, where marching fails. Use marching when start points are known and the curve must be accurate and ordered, and use the problem page for the full list of methods. Plain subdivision to a fine tolerance is slow and gives a large unordered output, so production systems use it as the first stage of a hybrid.

Pitfalls

  • Rounding drops pieces. The convex hull argument holds only if the box contains the control points exactly. A box computed in floating point can be slightly too small and drop a pair that only touches, like the three touching pieces of the example, and the point where they touch is then lost. Round the boxes outward, or use exact arithmetic as here.
  • Signs in the triangle test. Line L6 branches on the signs of n1⋅(x−a1)n_1 \cdot (x - a_1), which is an orientation test, and in floating point near-zero values suffer from catastrophic cancellation. The fix is exact rational arithmetic, as in the implementation, or a floating-point filter that falls back to exact arithmetic when the value is too close to zero.
  • Degenerate corners. When three corners of a piece are collinear, for example at a collapsed edge, the corner plane is not defined, the piece is never flat, and the recursion runs to the depth cap. Use the best-fitting plane of the control points, or a cap and a flag as here.
  • Tangential contact. Where the patches touch along a curve, every pair along it overlaps at every level, and the number of leaves grows like ε−1\varepsilon^{-1}, not ε−1/2\varepsilon^{-1/2}.
  • Gaps between segments. Segments from adjacent leaves need not share end points, since each leaf uses its own triangles. A curve fit from the segments must join them within a tolerance.

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.

subdivision_surface_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subdivision-surface-intersection/. The authors are listed in prov/V3H0YK.jsonl.

"""Intersection of two tensor-product Bezier patches by recursive subdivision, exactly.

A patch is a control net net[i][j] of 3D points with int or Fraction
coordinates, i = 0..p in the u direction and j = 0..q in the v direction,
together with its parameter rectangle (u0, u1, v0, v1) in the original
patch. The method discards a pair of patches whose bounding boxes of the
control points do not overlap, splits a patch that is not flat into four
quarters by de Casteljau's algorithm at the midpoints, and intersects the
corner triangles of two flat patches. All arithmetic is exact, so every
box test and every sign in the triangle test is decided without error.

The result is a list of leaves. A leaf is a pair of parameter rectangles,
one in each patch, whose boxes overlap, together with the segments where
the corner triangles of the two flat pieces meet. A leaf that was reached at
max_depth without being flat has no segments and is flagged.
"""

from fractions import Fraction

Vec = tuple
HALF = Fraction(1, 2)


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def dot(a: Vec, b: Vec):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


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


def lerp(a: Vec, b: Vec, t) -> Vec:
    return tuple(a[k] + t * (b[k] - a[k]) for k in range(3))


def casteljau_split(points: list, t=HALF):
    """Split a Bezier curve at t; return the control points of the two halves."""
    left, right = [points[0]], [points[-1]]
    cur = list(points)
    while len(cur) > 1:
        cur = [lerp(cur[i], cur[i + 1], t) for i in range(len(cur) - 1)]
        left.append(cur[0])
        right.append(cur[-1])
    return left, right[::-1]


def evaluate(net: list, u, v) -> Vec:
    """De Casteljau evaluation of the patch at (u, v) in [0, 1]^2."""

    def point(points, t):
        cur = list(points)
        while len(cur) > 1:
            cur = [lerp(cur[i], cur[i + 1], t) for i in range(len(cur) - 1)]
        return cur[0]

    return point([point(row, v) for row in net], u)


def split_u(net: list):
    cols = [casteljau_split([net[i][j] for i in range(len(net))]) for j in range(len(net[0]))]
    left = [[cols[j][0][i] for j in range(len(cols))] for i in range(len(net))]
    right = [[cols[j][1][i] for j in range(len(cols))] for i in range(len(net))]
    return left, right


def split_v(net: list):
    halves = [casteljau_split(row) for row in net]
    return [h[0] for h in halves], [h[1] for h in halves]


def quarters(patch):
    """The four quarters of a patch (net, rect) at the midpoints of its rectangle."""
    net, (u0, u1, v0, v1) = patch
    um, vm = (u0 + u1) / 2, (v0 + v1) / 2
    lo, hi = split_u(net)
    out = []
    for half, (a, b) in ((lo, (u0, um)), (hi, (um, u1))):
        n0, n1 = split_v(half)
        out.append((n0, (a, b, v0, vm)))
        out.append((n1, (a, b, vm, v1)))
    return out


def box(net: list):
    pts = [p for row in net for p in row]
    return tuple(min(p[k] for p in pts) for k in range(3)), tuple(max(p[k] for p in pts) for k in range(3))


def boxes_overlap(a, b) -> bool:
    return all(a[0][k] <= b[1][k] and b[0][k] <= a[1][k] for k in range(3))


def diagonal2(bx):
    return sum((bx[1][k] - bx[0][k]) ** 2 for k in range(3))


def is_flat(net: list, eps) -> bool:
    """True when every control point is within eps of the plane of three corners."""
    a, b, c = net[0][0], net[-1][0], net[0][-1]
    n = cross(sub(b, a), sub(c, a))
    nn = dot(n, n)
    if nn == 0:
        return False
    return all(dot(n, sub(p, a)) ** 2 <= eps * eps * nn for row in net for p in row)


def corner_triangles(net: list):
    a, b, c, d = net[0][0], net[-1][0], net[-1][-1], net[0][-1]
    return [(a, b, c), (a, c, d)]


def plane_cut(tri, n, o):
    """The points where the edges of tri meet the plane n . (x - o) = 0."""
    s = [dot(n, sub(p, o)) for p in tri]
    pts = [tri[i] for i in range(3) if s[i] == 0]
    for i in range(3):
        j = (i + 1) % 3
        if (s[i] < 0 < s[j]) or (s[j] < 0 < s[i]):
            pts.append(lerp(tri[i], tri[j], s[i] / (s[i] - s[j])))
    return s, pts


def triangle_triangle(t1, t2):
    """The segment where two triangles meet, None, or "coplanar"."""
    n1 = cross(sub(t1[1], t1[0]), sub(t1[2], t1[0]))
    n2 = cross(sub(t2[1], t2[0]), sub(t2[2], t2[0]))
    s2, cut2 = plane_cut(t2, n1, t1[0])
    if all(x > 0 for x in s2) or all(x < 0 for x in s2):
        return None
    if all(x == 0 for x in s2):
        return "coplanar"
    s1, cut1 = plane_cut(t1, n2, t2[0])
    if all(x > 0 for x in s1) or all(x < 0 for x in s1):
        return None
    D = cross(n1, n2)
    i1 = sorted(cut1, key=lambda p: dot(D, p))
    i2 = sorted(cut2, key=lambda p: dot(D, p))
    lo = max(i1[0], i2[0], key=lambda p: dot(D, p))
    hi = min(i1[-1], i2[-1], key=lambda p: dot(D, p))
    if dot(D, lo) > dot(D, hi):
        return None
    return (lo, hi)


def intersect(P, Q, eps, max_depth: int = 40, depth: int = 0, out=None):
    """All leaves of the subdivision of the pair of patches P and Q, each (net, rect)."""
    if out is None:
        out = []
    bp, bq = box(P[0]), box(Q[0])
    if not boxes_overlap(bp, bq):  # @line L1
        return out
    flat_p, flat_q = is_flat(P[0], eps), is_flat(Q[0], eps)
    if depth >= max_depth and not (flat_p and flat_q):
        out.append({"rects": (P[1], Q[1]), "segments": [], "flat": False})
        return out
    if not flat_p and (flat_q or diagonal2(bp) >= diagonal2(bq)):  # @line L2
        for Pk in quarters(P):  # @line L3
            intersect(Pk, Q, eps, max_depth, depth + 1, out)
        return out
    if not flat_q:  # @line L4
        for Qk in quarters(Q):  # @line L5
            intersect(P, Qk, eps, max_depth, depth + 1, out)
        return out
    segments, coplanar = [], False
    for t1 in corner_triangles(P[0]):  # @line L6
        for t2 in corner_triangles(Q[0]):
            s = triangle_triangle(t1, t2)
            if s == "coplanar":
                coplanar = True
            elif s is not None:
                segments.append(s)
    out.append({"rects": (P[1], Q[1]), "segments": segments, "flat": True, "coplanar": coplanar})  # @line L7
    return out


def patch(net: list):
    """Wrap a control net as a patch over the unit square."""
    one = Fraction(1)
    return ([[tuple(Fraction(x) for x in p) for p in row] for row in net], (Fraction(0), one, Fraction(0), one))
test_subdivision_surface_intersection.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subdivision-surface-intersection/. The authors are listed in prov/V3H0YK.jsonl.

import random
import unittest
from fractions import Fraction as F

from subdivision_surface_intersection import dot, evaluate, intersect, patch, quarters

SADDLE = [[(0, 0, 0), (0, 1, 0)], [(1, 0, 0), (1, 1, 1)]]  # z = u v
LEVEL = [[(0, 0, F(1, 4)), (0, 1, F(1, 4))], [(1, 0, F(1, 4)), (1, 1, F(1, 4))]]  # z = 1/4


def in_rect(rect, u, v) -> bool:
    u0, u1, v0, v1 = rect
    return u0 <= u <= u1 and v0 <= v <= v1


def crossings(g, n, bits=24):
    """Brute force: the grid edges of [0, 1]^2 with n cells a side on which g changes
    sign, each narrowed by exact bisection to a segment of length 2^-bits."""
    out = []
    for i in range(n + 1):
        for j in range(n + 1):
            a = (F(i, n), F(j, n))
            for b in ((F(i + 1, n), F(j, n)), (F(i, n), F(j + 1, n))):
                if b[0] > 1 or b[1] > 1:
                    continue
                ga, gb = g(*a), g(*b)
                if ga == 0:
                    out.append((a, a))
                    continue
                if gb == 0 or (ga > 0) == (gb > 0):
                    continue
                lo, hi = a, b
                for _ in range(bits):
                    mid = ((lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2)
                    gm = g(*mid)
                    if gm == 0:
                        lo = hi = mid
                        break
                    if (gm > 0) == (ga > 0):
                        lo = mid
                    else:
                        hi = mid
                out.append((lo, hi))
    return out


def hits(rect, seg) -> bool:
    """True when the closed rectangle meets the short axis-parallel segment."""
    (a, b) = seg
    u0, u1, v0, v1 = rect
    return min(a[0], b[0]) <= u1 and max(a[0], b[0]) >= u0 and min(a[1], b[1]) <= v1 and max(a[1], b[1]) >= v0


class TestSubdivision(unittest.TestCase):
    def test_quarters_reproduce_the_patch(self):
        rng = random.Random(11)
        net = [[(F(i, 3), F(j, 3), F(rng.randint(-8, 8), 8)) for j in range(4)] for i in range(3)]
        P = patch(net)
        for Pk in quarters(quarters(P)[2]):
            u0, u1, v0, v1 = Pk[1]
            for a in (F(0), F(1, 3), F(1)):
                for b in (F(0), F(2, 5), F(1)):
                    self.assertEqual(evaluate(Pk[0], a, b), evaluate(net, u0 + a * (u1 - u0), v0 + b * (v1 - v0)))

    def test_saddle_and_level_plane(self):
        P, Q = patch(SADDLE), patch(LEVEL)
        for eps in (F(1, 16), F(1, 64)):
            leaves = intersect(P, Q, eps)
            self.assertTrue(leaves)
            for leaf in leaves:
                self.assertTrue(leaf["flat"])
                u0, u1, v0, v1 = leaf["rects"][0]
                # The z range of the piece is [u0 v0, u1 v1]: every kept piece meets the curve.
                self.assertTrue(u0 * v0 <= F(1, 4) <= u1 * v1)
                for seg in leaf["segments"]:
                    for x in seg:
                        self.assertEqual(x[2], F(1, 4))
                        self.assertLessEqual(abs(x[0] * x[1] - F(1, 4)), eps)
            # Completeness against the brute force grid of sign changes of u v - 1/4.
            for seg in crossings(lambda u, v: u * v - F(1, 4), 16):
                self.assertTrue(any(hits(leaf["rects"][0], seg) and hits(leaf["rects"][1], seg) for leaf in leaves))

    def test_two_curved_patches(self):
        # Q is the height field z = 1/4 + (s - 1/2)^2 over the unit square, of degree (2, 1).
        Q = patch([[(0, 0, F(1, 2)), (0, 1, F(1, 2))], [(F(1, 2), 0, 0), (F(1, 2), 1, 0)], [(1, 0, F(1, 2)), (1, 1, F(1, 2))]])
        P = patch(SADDLE)
        eps = F(1, 32)
        leaves = intersect(P, Q, eps)
        g = lambda u, v: u * v - F(1, 4) - (u - F(1, 2)) ** 2  # noqa: E731
        # A point (x, y) of both surfaces has parameters (x, y) in P and in Q.
        for seg in crossings(g, 16):
            self.assertTrue(any(hits(leaf["rects"][0], seg) and hits(leaf["rects"][1], seg) for leaf in leaves))
        for leaf in leaves:
            for seg in leaf["segments"]:
                for x in seg:
                    self.assertLessEqual(abs(g(x[0], x[1])), 4 * eps)

    def test_random_bicubic_against_planes(self):
        rng = random.Random(5)
        for _ in range(6):
            net = [[(F(i, 3) + F(rng.randint(-1, 1), 16), F(j, 3) + F(rng.randint(-1, 1), 16), F(rng.randint(-8, 8), 8)) for j in range(4)] for i in range(4)]
            P = patch(net)
            n = (F(rng.randint(-2, 2), 4), F(rng.randint(-2, 2), 4), F(1))
            # The plane n . x = d passes through a point of P, so the curve is not empty.
            d = dot(n, evaluate(net, F(rng.randint(1, 5), 6), F(rng.randint(1, 5), 6)))
            # A planar quadrilateral on n . x = d that covers the box of P.
            corner = lambda x, y: (F(x), F(y), d - n[0] * x - n[1] * y)  # noqa: E731
            Q = patch([[corner(-1, -1), corner(-1, 2)], [corner(2, -1), corner(2, 2)]])
            leaves = intersect(P, Q, F(1, 16))
            for leaf in leaves:
                self.assertTrue(leaf["flat"])
                self.assertEqual(leaf["rects"][1], Q[1])  # a flat patch is never split
            g = lambda u, v: dot(n, evaluate(P[0], u, v)) - d  # noqa: E731
            segs = crossings(g, 12, bits=16)
            self.assertTrue(segs)
            self.assertTrue(any(leaf["segments"] for leaf in leaves))
            for seg in segs:
                self.assertTrue(any(hits(leaf["rects"][0], seg) for leaf in leaves))
            for leaf in leaves:
                for seg in leaf["segments"]:
                    for x in seg:
                        self.assertEqual(dot(n, x), d)

    def test_near_miss_keeps_nothing(self):
        # z = u v stays below 1/16 where x, y <= 1/4, so it misses the small square at z = 1/4,
        # although the boxes of the whole patches overlap.
        Q = patch([[(0, 0, F(1, 4)), (0, F(1, 4), F(1, 4))], [(F(1, 4), 0, F(1, 4)), (F(1, 4), F(1, 4), F(1, 4))]])
        self.assertEqual(intersect(patch(SADDLE), Q, F(1, 64)), [])
        far = patch([[(5, 5, 0), (5, 6, 0)], [(6, 5, 0), (6, 6, 1)]])
        self.assertEqual(intersect(patch(SADDLE), far, F(1, 64)), [])

    def test_coincident_patches_are_flagged(self):
        leaves = intersect(patch(LEVEL), patch(LEVEL), F(1, 64))
        self.assertEqual(len(leaves), 1)
        self.assertTrue(leaves[0]["coplanar"])


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

History

Lane and Riesenfeld published the theory of subdivision for Bézier and B-spline curves and surfaces in 1980, and showed that it gives algorithms for curve and surface intersection as well as for display. Sederberg and Meyers added the loop test in 1988, so that a subdivision could stop as soon as no closed loop could hide in a pair. Patrikalakis's survey of 1993 compared subdivision with lattice, analytic and marching methods and with hybrids that combine them.

References

  1. J. M. Lane and R. F. Riesenfeld, A theoretical development for the computer generation and display of piecewise polynomial surfaces, IEEE Transactions on Pattern Analysis and Machine Intelligence 2(1), 35 to 46, 1980, the whole paper (subdivision of Bezier and B-spline curves and surfaces, the convex hull test, and the intersection algorithms that follow from them)
  2. Nicholas M. Patrikalakis, Surface-to-surface intersections, IEEE Computer Graphics and Applications 13(1), 89 to 95, 1993, the section on subdivision methods and their comparison with marching
  3. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Intersection problems, Section 5.8 on surface to surface intersection, the part on subdivision methods
  4. Thomas W. Sederberg and Ray J. Meyers, Loop detection in surface patch intersections, Computer Aided Geometric Design 5(2), 161 to 171, 1988, the normal cone test, which tells when a pair of pieces from a subdivision can hold no closed loop

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