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
- Model
- Real RAM
- Properties
- deterministicnot exactrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 and over , given by their control nets, and a flatness tolerance . The output is a list of leaves: pairs of parameter rectangles 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 must have and 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
SUBDIVIDE(P, Q, ε)- 1
if box(P) and box(Q) do not overlap then return ▷ convex hull property - 2
if P is not flat and (Q is flat or box(P) is at least as large as box(Q)) then - 3
for each quarter P_k of P, by de Casteljau at the midpoints, do SUBDIVIDE(P_k, Q, ε) - 4
else if Q is not flat then - 5
for each quarter Q_k of Q do SUBDIVIDE(P, Q_k, ε) - 6
else intersect the two corner triangles of P with the two of Q - 7
output 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 of the plane through three of its corners, , and . The normal of that plane is , by the right-hand rule, which points the same way as the outward normal of the patch. A quarter is computed by splitting each column of the control net at and then each row at ; 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 are and . Line L6 intersects each triangle of one piece with each triangle of the other by the standard test: the signs of 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 . 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 be the saddle , the bilinear patch with control points , , and , and let be the plane patch over the unit square. They meet in the hyperbola arc for . Take . Because is bilinear, the range of its box over is exactly , so the trace can be checked by hand.
| level | pairs tested at L1 | dropped | result |
|---|---|---|---|
| 0 | the whole with | 0 | is flat; is not: is at distance from the plane of the other corners; split |
| 1 | four quarters of side | 0 | the ranges , , and all reach ; in each quarter the fourth corner is above the plane of the other three in , and more than from it; split all |
| 2 | sixteen pieces of side | 8 | eight boxes reach ; the fourth corner is now above the plane in , so at most from it, and all eight are flat leaves |
The eight dropped pieces include , with , and , with . Three kept pieces only touch the plane, at the points , and of the curve, and are kept because touching counts as overlap. In all, line L1 runs times and line L6 runs triangle tests, which give segments. For the leaf the segments run from to to . The end points are on the curve, and the middle point has , off by . With and the method keeps and leaves of side and , and the largest error of a segment point is and , a quarter of 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 has its parameters in the rectangles of a pair, is in both boxes, and line L1 does not drop the pair. The four quarters cover the rectangle, so the parameters of 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 , it ends without the cap: a piece of side is within of its corner plane, so pieces become flat after a bounded number of halvings. In a flat leaf, both pieces lie within 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 and be tensor-product Bézier patches of degrees and over . A piece of is a pair of a control net and a closed rectangle ; it represents on if the patch of at equals . A witness for a pair of pieces , is a quadruple with , and . The arithmetic is exact, so every comparison in SUBDIVIDE is decided correctly.
Lemma 1 (quarters). If represents on , the four quarters computed by L3 represent on the four quarters of .
Proof. For a Bézier curve, the two halves of the de Casteljau scheme at are the control polygons of the curve on and on , each reparametrized over ; this is the subdivision property of the de Casteljau algorithm. Write the patch as , with . For fixed the patch is a Bézier curve in with control points , and these depend linearly on the columns , so splitting every column at splits the patch in . Splitting every row of each half at splits it in in the same way. Composing the affine maps of the parameters gives the claim.
Lemma 2 (hull). If represents on , then lies in the convex hull of the points of , and so in box.
Proof. The Bernstein polynomials of each degree are nonnegative on and sum to one, so the products 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.
Lemma 3 (no witness is dropped). If a pair of pieces has a witness , 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 lies in box and in box by Lemma 2, so the boxes share and overlap; L1 counts touching as overlap, so it keeps the pair. The four quarters of cover , so one of them contains , and by Lemma 1 it is a piece that represents there. The same holds for at L5.
Lemma 4 (flat pieces). Assume on . There is a constant such that, for every piece of over a square of side made by Lemma 1, every control point lies within of the plane through the corners , and , and these corners are not collinear when is small.
Proof. Let the square be , and let be the blossom of , the unique function that is symmetric and affine in each of its first and last arguments and agrees with on the diagonal. The control points of the piece are the blossom values . Expand around . Since it is a polynomial of degree one in each argument, , where the partial derivatives are taken at and , with a bound on the mixed second partial derivatives of over , which is finite because is a polynomial. So every control point is within of the tangent plane at . Let be the minimum of on and let be the unit normal of . The three corners are , and , so . Its length is at least for small , so the corners are not collinear, and its unit vector satisfies . For each control point, has length , and . Hence . All constants depend only on bounds of the derivatives of and on , so they are uniform over all squares.
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 be such that and the corners are not collinear at side , for both patches (Lemma 4). Every piece is a square of side after splits of its patch, and a piece with is flat. Line L2 splits only when is not flat, and L4 splits only when is not flat. So along a path, is split at most times and at most times, the depth is at most , and the tree is finite. A call that reaches L6 has two flat pieces, so its leaf is flat.
Theorem. SUBDIVIDE ends, and for every intersection point there is an output leaf with and . If both patches are regular, the leaves are flat without the depth cap, and every intersection point of a leaf lies within of the corner planes of both pieces.
Proof. Termination is Lemma 5. The root pair, the two patches over , 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 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.
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 in . 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 . 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 control points and degrees and costs , and a box or a flatness test costs . The pair tree has four children at each split, and each of the two patches is split at most times along a path, so it has at most nodes in the worst case, which gives 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 , as the example shows. The extra space is for the recursion and for the 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 , 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 , not .
- 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.
# 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag V3H0YK Edit this page History Report an error Markdown