Algorithm Search⌘K

Algorithmcore

Marching surface intersection

Also called intersection curve tracing, surface intersection by marching.

Traces each branch of a surface intersection curve from a start point by stepping along the tangent and correcting with Newton iterations onto both surfaces.

Time
O(n i) worst
Space
O(n) extra
Where
i = the number of Newton iterations in one correction; n = the number of points on the traced branch
Properties
deterministicnot exactiterative
Origin
Robert E. Barnhill, Gerald Farin, M. Jordan, Bruce R. Piper, 1987

Marching traces one branch of the intersection curve of two surfaces. It starts from a point on the curve and repeats two steps: a predictor step of length hh along the tangent of the curve, which is the cross product of the two surface normals, and a corrector that pulls the predicted point back onto both surfaces with Newton's method for systems. The result is a sequence of points on the curve, each accurate to the Newton tolerance, which is the usual output of surface surface intersection in CAD systems. Marching is fast and accurate, but it finds only the branch of its start point: it misses closed loops that have no start point, and with a long step it can jump to another branch. Barnhill, Farin, Jordan and Piper described the method for parametric surfaces in 1987.

In plain words

Two curved sheets cross along a curve. Stand on the curve and look along it: the direction of the curve is at right angles to both sheets' normals, so it is easy to compute. Take a small step in that direction. The step leaves the curve a little, because the curve bends. So pull the new point back onto both sheets, by a few rounds of Newton's method. Now you are on the curve again, a step further along. Repeat.

Stop when you are back where you started, which means the curve is a closed ring, or when you leave the region of interest. Then go back to the start and walk the other way.

The walk never visits a ring of the curve that it did not start on. Finding one starting point on every ring is a separate task.

The problem

The input is two implicit surfaces f(x)=0f(x) = 0 and g(x)=0g(x) = 0 in R3\mathbb{R}^3, with gradients ∇f\nabla f and ∇g\nabla g, a start point x0x_0 near the curve C={f=g=0}C = \{f = g = 0\}, a step length hh, and a box that bounds the region. The output is one branch of CC, the one through the point that x0x_0 converges to, as a polyline whose vertices satisfy ∣f∣≤τ|f| \le \tau and ∣g∣≤τ|g| \le \tau for the tolerance τ\tau, and a flag that tells whether the branch closed. This page uses quadrics for ff and gg: planes, spheres and cylinders. For two parametric surfaces the same scheme runs in the four parameters, with the equations S1(u,v)=S2(s,t)S_1(u, v) = S_2(s, t). A point where ∇f∥∇g\nabla f \parallel \nabla g is where the curve can be singular, and the method treats it as a failure of the step, not as a normal case.

The algorithm

  1. MARCH(f, g, x0, h, box)
  2. 1p0 ← CORRECT(x0) ▷ Newton onto f = g = 0
  3. 2A ← empty, B ← empty ▷ points after p0 and before p0
  4. 3for d in (+1, −1) do
  5. 4p ← p0, t' ← d · T(p0), δ ← h ▷ T(p) = unit vector of ∇f(p) × ∇g(p)
  6. 5repeat: t ← T(p), with the sign that agrees with t'
  7. 6q ← CORRECT(p + δ t)
  8. 7if CORRECT failed or T(q) turns by more than α from t then δ ← δ / 2 and go to L5 (stop if δ < δ_min)
  9. 8if q is outside box then leave the loop
  10. 9if the trace has been farther than 2h from p0 and |q − p0| ≤ h then return the closed branch p0, A
  11. 10append q to A if d = +1, or to B if d = −1
  12. 11p ← q, t' ← t, δ ← min(h, 1.5 δ)
  13. 12return the open branch reverse(B), p0, A

CORRECT solves the two equations F(x)=(f(x),g(x))=0F(x) = (f(x), g(x)) = 0 in three unknowns with Newton steps of least length:

x←x−J⊤(JJ⊤)−1F(x),J=(∇f(x)⊤∇g(x)⊤).x \leftarrow x - J^\top (J J^\top)^{-1} F(x), \qquad J = \begin{pmatrix} \nabla f(x)^\top \\ \nabla g(x)^\top \end{pmatrix}.

Each step moves xx in the plane spanned by the two gradients, normal to the curve, so the correction does not slide along the curve. The 2×22 \times 2 matrix JJ⊤J J^\top is singular exactly when the gradients are parallel, and CORRECT reports a failure there. Another common form adds a third equation, the plane through the predicted point normal to tt, and solves a square 3×33 \times 3 Newton system.

Line L7 is the step control. A step is refused when Newton does not converge, or when the tangent turns by more than the angle α\alpha, a sign that the step went past a sharp bend or onto another branch. Line L11 lets the step grow back towards hh.

Example

Viviani's curve is the intersection of the sphere f=x2+y2+z2−4f = x^2 + y^2 + z^2 - 4 and the cylinder g=(x−1)2+y2−1g = (x - 1)^2 + y^2 - 1, which touches the sphere from inside at (2,0,0)(2, 0, 0). The curve is (1+cos⁡s,sin⁡s,2sin⁡(s/2))(1 + \cos s, \sin s, 2 \sin(s/2)) for 0≤s<4π0 \le s < 4\pi, a figure eight with a double point at (2,0,0)(2, 0, 0). Start at x0=(0.1,0,1.9)x_0 = (0.1, 0, 1.9) with h=0.1h = 0.1.

iteration point ff gg
L1, 0 (0.1,0,1.9)(0.1, 0, 1.9) −3.8⋅10−1-3.8 \cdot 10^{-1} −1.9⋅10−1-1.9 \cdot 10^{-1}
L1, 1 (−0.005556,0,2.005556)(-0.005556, 0, 2.005556) 2.2⋅10−22.2 \cdot 10^{-2} 1.1⋅10−21.1 \cdot 10^{-2}
L1, 2 (−0.000015,0,2.000015)(-0.000015, 0, 2.000015) 6.1⋅10−56.1 \cdot 10^{-5} 3.1⋅10−53.1 \cdot 10^{-5}
L1, 3 (0,0,2)(0, 0, 2) 4.7⋅10−104.7 \cdot 10^{-10} 2.4⋅10−102.4 \cdot 10^{-10}
L6, predictor (0,−0.1,2)(0, -0.1, 2) 1.0⋅10−21.0 \cdot 10^{-2} 1.0⋅10−21.0 \cdot 10^{-2}
L6, 1 (0.004938,−0.099383,1.997531)(0.004938, -0.099383, 1.997531) 3.1⋅10−53.1 \cdot 10^{-5} 2.5⋅10−52.5 \cdot 10^{-5}
L6, 2 (0.004951,−0.099381,1.997523)(0.004951, -0.099381, 1.997523) 2.1⋅10−102.1 \cdot 10^{-10} 1.5⋅10−101.5 \cdot 10^{-10}

The residuals square at each iteration, as Newton's method does near a regular point. At p0=(0,0,2)p_0 = (0, 0, 2) the gradients are (0,0,4)(0, 0, 4) and (−2,0,0)(-2, 0, 0), and their cross product (0,−8,0)(0, -8, 0) gives the first direction. The trace passes the double point twice, once on each lobe, because the predictor carries it straight through: there the gradients (4,0,0)(4, 0, 0) and (2,0,0)(2, 0, 0) are parallel, but no computed point falls on it. It closes after 153153 points with a polyline of length 15.277215.2772. With h=0.02h = 0.02 it closes after 764764 points with length 15.280615.2806. The exact length, ∫04π1+cos⁡2(s/2) ds\int_0^{4\pi} \sqrt{1 + \cos^2(s/2)} \, ds, is 15.280815.2808.

Correctness

The tangent of CC at a regular point is perpendicular to both gradients, so it is parallel to ∇f×∇g\nabla f \times \nabla g, which justifies line L5. Near a point where the gradients are independent, the Newton step of least length converges quadratically to a point of CC at distance O(∣F(x)∣)O(|F(x)|) from its start. The predictor is off the curve by O(δ2)O(\delta^2), so each corrected point lies on the same branch and moves along it by δ+O(δ2)\delta + O(\delta^2). For a compact regular branch and a step below a bound that depends on its curvature and its distance to other branches, the trace visits the branch in order and closes it. The full proof states these assumptions and proves the claim, including the converse fact that the trace never leaves a tube around the branch of the start point, so it cannot find another component.

What is proved is local. The constants in the step bound are not computed by the method, so in practice hh and α\alpha are chosen by experience, and the success of the trace on a given model is measured, not proved.

Proof: Marching with a short step traces the whole branch of its start point and nothing elsefull

Let f,g:R3→Rf, g : \mathbb{R}^3 \to \mathbb{R} be C2C^2, let F=(f,g)F = (f, g), and let J(x)J(x) be the 2×32 \times 3 matrix with rows ∇f(x)⊤\nabla f(x)^\top and ∇g(x)⊤\nabla g(x)^\top. Write T(x)T(x) for the unit vector of ∇f(x)×∇g(x)\nabla f(x) \times \nabla g(x). Let CC be a connected component of {F=0}\{F = 0\} that is compact and regular: ∇f×∇g≠0\nabla f \times \nabla g \ne 0 on CC. Then CC is a closed C2C^2 curve, by the implicit function theorem, and TT is a unit tangent field along it. Let LL be its length.

The proof uses exact arithmetic: CORRECT returns the limit of its Newton iteration. The tolerance τ\tau of the implementation adds an error of order τ\tau to every point and changes no step of the argument when τ\tau is small compared with the step.

Lemma 1 (the tangent). At each p∈Cp \in C, the tangent line of CC is spanned by T(p)T(p).

Proof. ff and gg are constant on CC, so their derivatives along CC vanish: the tangent vector is perpendicular to ∇f(p)\nabla f(p) and to ∇g(p)\nabla g(p). These are independent, so the vectors perpendicular to both form the line spanned by their cross product. □\square

Lemma 2 (a tube). There are numbers ρ>0\rho > 0, K≥1K \ge 1 and β>0\beta > 0 such that on the closed tube U={x:dist⁡(x,C)≤ρ}U = \{x : \operatorname{dist}(x, C) \le \rho\}:

  1. UU meets {F=0}\{F = 0\} only in CC;
  2. the smallest singular value of J(x)J(x) is at least β\beta, and ∇f×∇g≠0\nabla f \times \nabla g \ne 0;
  3. for each x∈Ux \in U with dist⁡(x,C)≤ρ/(2K)\operatorname{dist}(x, C) \le \rho / (2K), the Newton iteration x←x−J⊤(JJ⊤)−1F(x)x \leftarrow x - J^\top (J J^\top)^{-1} F(x) stays in UU and converges to a point x∗∈Cx^* \in C with ∣x∗−x∣≤K∣F(x)∣|x^* - x| \le K |F(x)|.

Proof. (1) By the implicit function theorem, each point of CC has a neighborhood in which {F=0}\{F = 0\} is a single arc of CC. Finitely many of these neighborhoods cover the compact CC, and their union contains a tube around CC; take ρ\rho smaller than its radius. (2) holds on CC and is an open condition, so it holds on a tube by compactness. (3) is the local convergence theorem of the Newton method with the pseudoinverse J⊤(JJ⊤)−1J^\top (J J^\top)^{-1} for underdetermined systems, a form of the Kantorovich theorem: when JJ has full row rank with smallest singular value at least β\beta and JJ is Lipschitz on a ball, the iteration from a point with small enough ∣F∣|F| converges quadratically to a zero within a constant times ∣F(x)∣|F(x)| of the start. The constants are uniform on UU by compactness, and by (1) the zero lies in CC. □\square

Lemma 3 (one step). There is h1>0h_1 > 0 such that for every p∈Cp \in C and 0<δ≤h10 < \delta \le h_1, the point qq = CORRECT(p+δT(p))(p + \delta T(p)) lies on CC and satisfies ∣q−p∣=δ+O(δ2)|q - p| = \delta + O(\delta^2), and the arc of CC from pp to qq in the direction of T(p)T(p) has length δ+O(δ2)\delta + O(\delta^2). The constants are uniform in pp.

Proof. Parametrize CC by arc length near pp as γ(s)\gamma(s) with γ(0)=p\gamma(0) = p and γ′(0)=T(p)\gamma'(0) = T(p) (Lemma 1). Taylor's theorem gives ∣p+δT(p)−γ(δ)∣≤κmax⁡δ2/2|p + \delta T(p) - \gamma(\delta)| \le \kappa_{\max} \delta^2 / 2, where κmax⁡\kappa_{\max} bounds the curvature of CC. So dist⁡(p+δT,C)=O(δ2)\operatorname{dist}(p + \delta T, C) = O(\delta^2) and ∣F(p+δT)∣=O(δ2)|F(p + \delta T)| = O(\delta^2), since FF is Lipschitz. For δ\delta small, Lemma 2 (3) applies, and q∈Cq \in C with ∣q−(p+δT)∣≤K⋅O(δ2)|q - (p + \delta T)| \le K \cdot O(\delta^2). Hence ∣q−γ(δ)∣=O(δ2)|q - \gamma(\delta)| = O(\delta^2). Near γ(δ)\gamma(\delta), CC is a single arc, by Lemma 2 (1), so q=γ(δ+O(δ2))q = \gamma(\delta + O(\delta^2)), which gives both claims. □\square

Lemma 4 (no refused step). Let α>0\alpha > 0 be the turning angle of line L7. For δ\delta small enough, uniformly on CC, CORRECT succeeds and the angle between T(q)T(q) and T(p)T(p) is O(δ)<αO(\delta) < \alpha. So for hh small enough the step control never halves the step, and δ=h\delta = h throughout.

Proof. Success is Lemma 3. TT is Lipschitz on UU by Lemma 2 (2), and ∣q−p∣=O(δ)|q - p| = O(\delta), so the angle is O(δ)O(\delta). □\square

Lemma 5 (the sign of the tangent). Along the trace, the sign rule of line L5 keeps the direction of travel. That is, if t′t' points along CC in the direction of travel at pp, the chosen tt at the next point qq does too.

Proof. TT is continuous along CC. The direction of travel at qq is ±T(q)\pm T(q) with the sign that makes it close to the direction at pp, which by Lemma 4 is the sign with T(q)⋅t′>0T(q) \cdot t' > 0. □\square

Theorem. Assume x0x_0 is close enough to CC that CORRECT(x0)=p0∈C(x_0) = p_0 \in C (Lemma 2 (3)), that the box contains UU, and that hh is small enough for Lemmas 3 and 4 and also satisfies the separation condition: any two points of CC at distance at most 3h3h in space are joined by an arc of CC of length at most 4h4h. Then MARCH returns a closed polyline whose vertices lie on CC, in the order of CC, with consecutive vertices at arc distance h+O(h2)h + O(h^2), and every point of CC is within O(h2)O(h^2) of the polyline. No vertex lies on another component of {F=0}\{F = 0\}.

Proof. By Lemmas 3 to 5, the trace for d=+1d = +1 produces points p0,p1,p2,…p_0, p_1, p_2, \ldots on CC with arc positions sks_k, measured from p0p_0 in the direction of travel, that grow by h+O(h2)h + O(h^2) at each step. Line L8 never fires, since the points stay on C⊂U⊆C \subset U \subseteq box. The separation condition exists for small hh: CC is a compact embedded C2C^2 curve, so chord length and arc length are comparable for short arcs, and points far apart along CC are a positive distance apart in space.

The trace leaves. Once sk>4hs_k > 4h and L−sk>4hL - s_k > 4h, the arc distance from pkp_k to p0p_0 is more than 4h4h, so by the separation condition ∣pk−p0∣>3h>2h|p_k - p_0| > 3h > 2h. So the flag of line L9 is set after a bounded number of steps.

No early closure. Suppose line L9 fires at step kk with ∣pk−p0∣≤h|p_k - p_0| \le h. By the separation condition the arc distance from pkp_k to p0p_0 is at most 4h4h, so sk≤4hs_k \le 4h or L−sk≤4hL - s_k \le 4h. The first case is impossible. The flag was set by an earlier point pjp_j with ∣pj−p0∣>2h|p_j - p_0| > 2h, so sk>sj≥∣pj−p0∣>2hs_k > s_j \ge |p_j - p_0| > 2h. On arcs of length at most 4h4h, chord and arc length differ by a factor 1−O(h2)1 - O(h^2), so ∣pk−p0∣≥sk(1−O(h2))>h|p_k - p_0| \ge s_k (1 - O(h^2)) > h for small hh, against ∣pk−p0∣≤h|p_k - p_0| \le h. So L−sk≤4hL - s_k \le 4h, and the trace has gone around CC.

It closes. The positions sks_k grow by about hh until L−sk<h/2+O(h2)L - s_k < h/2 + O(h^2) for some kk. Then ∣pk−p0∣≤L−sk<h|p_k - p_0| \le L - s_k < h, so line L9 fires at the latest there. It returns the points p0,…,pk−1p_0, \ldots, p_{k - 1} in order along CC, and the closing segment from pk−1p_{k - 1} to p0p_0 spans an arc of length at most 2h+O(h2)2h + O(h^2).

Cover. Each segment joins two points of CC at arc distance at most 2h+O(h2)2h + O(h^2), and a chord of an arc of length ℓ\ell and curvature at most κmax⁡\kappa_{\max} is within κmax⁡ℓ2/8+O(ℓ3)\kappa_{\max} \ell^2 / 8 + O(\ell^3) of the arc. Every point of CC lies on one of these arcs, which gives the O(h2)O(h^2) bound.

Nothing else. Every vertex is the output of CORRECT from a point in the tube, which by Lemma 2 lies on CC. ■\blacksquare

Corollary (one component). Under the assumptions of the theorem, MARCH returns points of CC only. If {F=0}\{F = 0\} has a second component C′C', no vertex lies on C′C', however large the box. So a marching method finds every component only if it is given a start point on each, which is the reason for loop detection and start point searches.

What is not claimed. The bounds on hh depend on ρ\rho, KK, β\beta, the curvature of CC and the separation condition, none of which MARCH computes. With a larger step, the predictor can land in the tube of another branch, and Lemma 2 no longer protects the trace; this is branch jumping. At a singular point, where Lemma 2 (2) fails, the theorem says nothing, and the passage of the trace through the double point of Viviani's curve on the page is an observed behavior of the example, not a consequence of the theorem.

Complexity

The costs are in the real RAM with square roots. One Newton iteration evaluates two quadrics and their gradients and solves a 2×22 \times 2 system, O(1)O(1) time. A point costs O(i)O(i) for ii iterations, so the branch costs O(ni)O(ni) time for nn points, plus the refused steps of line L7, at most log⁡2(h/δmin⁡)\log_2(h / \delta_{\min}) for each point. The space is O(n)O(n) for the output. The number of points is about the length of the branch divided by hh, and the accuracy between points is the chord error, about h2κ/8h^2 \kappa / 8 for curvature κ\kappa.

Properties

  • Local and accurate. Every output point is on both surfaces to the Newton tolerance, independently of hh.
  • One branch per start point. The method finds the component of the start point and nothing else.
  • Order is free. The points come in order along the curve, which a spline fit or a trimmed surface needs.
  • Not exact. All arithmetic is floating point. A decision such as "the branch closed" or "the gradients are parallel" compares computed numbers with tolerances.

Variants and improvements

  • Parametric surfaces. March in the four parameters (u,v,s,t)(u, v, s, t) with the three equations S1(u,v)−S2(s,t)=0S_1(u, v) - S_2(s, t) = 0. The output points are then given in both parameter domains, as trimming curves need.
  • Start points. Intersect the boundary curves of each patch with the other surface, which finds every open branch. For closed loops, subdivide until the loop test of Sederberg and Meyers excludes loops in each pair of patches, and start from the boundary points of the pieces. This hybrid is the usual production method.
  • Step control by curvature. Choose hh from the curvature of CC, computed from the second derivatives of the surfaces, to keep the chord error below a bound.
  • Certified tracing. Interval Newton methods or the Kantorovich theorem prove that a box around each step contains a single piece of one branch, so the trace cannot jump. Homotopy continuation uses the same predictor and corrector to follow solution paths of polynomial systems.
  • Singular points. At a point where the gradients are parallel, branch points are found from the second derivatives, and the trace continues on each outgoing branch.

When to use it

Use marching when the start points are known or can be found reliably, and when the output must be accurate and ordered: for the edges of Boolean operations, for trimming curves, and for fillet spines in the rolling-ball method. Use subdivision when it matters more that no part of the curve is missed than that it is fast, or to find the start points for marching.

Pitfalls

  • Missed loops. A small closed loop with no start point is not found. The sphere x2+y2+z2=1x^2 + y^2 + z^2 = 1 and the plane z=1−δz = 1 - \delta meet in a circle of radius about 2δ\sqrt{2\delta} that no boundary curve of a large patch meets. A start-point search on a coarse grid can miss it.
  • Several components. The sphere of radius 22 and the cylinder x2+y2=1x^2 + y^2 = 1 meet in two circles at z=±3z = \pm\sqrt 3. A trace from one start point closes after one circle and never sees the other.
  • Branch jumping. Where two branches pass close to each other, or cross at a singular point, a long step lands on the other branch, and the trace continues there. The two cylinders x2+y2=1x^2 + y^2 = 1 and x2+z2=1x^2 + z^2 = 1 meet in two ellipses that cross at (±1,0,0)(\pm 1, 0, 0). Keep the step short near points where ∣∇f×∇g∣|\nabla f \times \nabla g| is small, and check the turning angle as line L7 does.
  • Tangential contact. Where the surfaces touch along the curve, ∇f∥∇g\nabla f \parallel \nabla g at every point, JJ⊤J J^\top is singular, and the Newton step fails. Such curves need a different formulation, for example as the minima of f2+g2f^2 + g^2.
  • Closing too early. The closure test at line L9 can fire when the curve passes near its start point without closing. The guard of line L9, a trace that has first been farther than 2h2h, helps but is not a proof; a robust code compares the tangents as well.

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.

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

"""Marching along the intersection curve of two implicit surfaces, in floating point.

A surface is the zero set of a quadric q(x) = x . A x + b . x + c, with the
gradient 2 A x + b. Planes, spheres and circular cylinders are quadrics. The
method traces one branch of the curve f = g = 0 from a start point: each step
predicts along the unit tangent, the cross product of the two gradients, and
corrects back onto both surfaces with Newton steps of least length. The step
is halved when Newton fails or the tangent turns too much. The trace stops
when the branch closes, when it leaves the box, or after max_steps steps.

Tolerances: a returned point p has |f(p)| and |g(p)| at most TOL, after the
gradients have been scaled as they are given.
"""

import math

Vec = tuple
TOL = 1e-11


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


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


def scale(t: float, a: Vec) -> Vec:
    return (t * a[0], t * a[1], t * a[2])


def dot(a: Vec, b: Vec) -> float:
    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 norm(a: Vec) -> float:
    return math.sqrt(dot(a, a))


class Quadric:
    """The surface x . A x + b . x + c = 0, with A symmetric 3 by 3."""

    def __init__(self, A, b: Vec, c: float):
        self.A = [list(map(float, row)) for row in A]
        self.b = tuple(map(float, b))
        self.c = float(c)

    def _Ax(self, x: Vec) -> Vec:
        return tuple(sum(self.A[i][j] * x[j] for j in range(3)) for i in range(3))

    def value(self, x: Vec) -> float:
        return dot(x, self._Ax(x)) + dot(self.b, x) + self.c

    def grad(self, x: Vec) -> Vec:
        return add(scale(2.0, self._Ax(x)), self.b)


def sphere(center: Vec, R: float) -> Quadric:
    I3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    return Quadric(I3, scale(-2.0, center), dot(center, center) - R * R)


def cylinder(point: Vec, axis: Vec, R: float) -> Quadric:
    u = scale(1.0 / norm(axis), axis)
    A = [[(1.0 if i == j else 0.0) - u[i] * u[j] for j in range(3)] for i in range(3)]
    Aa = tuple(sum(A[i][j] * point[j] for j in range(3)) for i in range(3))
    return Quadric(A, scale(-2.0, Aa), dot(point, Aa) - R * R)


def plane(n: Vec, d: float) -> Quadric:
    return Quadric([[0, 0, 0], [0, 0, 0], [0, 0, 0]], n, -d)


def correct(f, g, x: Vec, iters: int = 30):
    """Newton steps of least length onto f = g = 0; None when they fail."""
    for _ in range(iters):
        F1, F2 = f.value(x), g.value(x)
        if abs(F1) <= TOL and abs(F2) <= TOL:
            return x
        a, b = f.grad(x), g.grad(x)
        aa, ab, bb = dot(a, a), dot(a, b), dot(b, b)
        det = aa * bb - ab * ab
        if det <= 1e-24 * aa * bb:
            return None
        l1 = (bb * F1 - ab * F2) / det
        l2 = (aa * F2 - ab * F1) / det
        x = sub(x, add(scale(l1, a), scale(l2, b)))
        if not all(math.isfinite(v) for v in x):
            return None
    return None


def unit_tangent(f, g, p: Vec):
    t = cross(f.grad(p), g.grad(p))
    n = norm(t)
    if n == 0.0:
        return None
    return scale(1.0 / n, t)


def inside(box, p: Vec) -> bool:
    lo, hi = box
    return all(lo[i] <= p[i] <= hi[i] for i in range(3))


def march(f, g, x0: Vec, h: float, box, max_steps: int = 10000, max_turn: float = 0.2, h_min: float = 1e-7):
    """Trace one branch through the point near x0. Return (points, closed)."""
    p0 = correct(f, g, x0)  # @line L1
    if p0 is None:
        raise ValueError("the start point does not converge onto the curve")
    t0 = unit_tangent(f, g, p0)
    if t0 is None:
        raise ValueError("the start point is a singular point of the curve")
    ends = {+1: [], -1: []}  # @line L2
    for d in (+1, -1):  # @line L3
        p, t_prev, step, left = p0, scale(d, t0), h, False  # @line L4
        for _ in range(max_steps):
            t = unit_tangent(f, g, p)  # @line L5
            if t is None:
                break
            if dot(t, t_prev) < 0:
                t = scale(-1.0, t)
            q = correct(f, g, add(p, scale(step, t)))  # @line L6
            tq = None if q is None else unit_tangent(f, g, q)
            if q is None or tq is None or abs(dot(tq, t)) < math.cos(max_turn) or norm(sub(q, p)) > 2 * step:
                step /= 2  # @line L7
                if step < h_min:
                    break
                continue
            if not inside(box, q):  # @line L8
                break
            gap = norm(sub(q, p0))
            left = left or gap > 2 * h
            if left and gap <= h:  # @line L9
                return [p0] + ends[+1], True
            ends[d].append(q)  # @line L10
            p, t_prev = q, t  # @line L11
            step = min(h, 1.5 * step)
    return list(reversed(ends[-1])) + [p0] + ends[+1], False  # @line L12
test_marching_surface_intersection.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/marching-surface-intersection/. The authors are listed in prov/ZVWZT1.jsonl.

import math
import random
import unittest

from marching_surface_intersection import cylinder, dot, march, norm, plane, scale, sphere, sub

BOX = ((-3.0, -3.0, -3.0), (3.0, 3.0, 3.0))


def dist_to_polyline(x, pts, closed):
    best = math.inf
    n = len(pts)
    for i in range(n if closed else n - 1):
        a, b = pts[i], pts[(i + 1) % n]
        ab = sub(b, a)
        L = dot(ab, ab)
        t = 0.0 if L == 0 else max(0.0, min(1.0, dot(sub(x, a), ab) / L))
        best = min(best, norm(sub(x, (a[0] + t * ab[0], a[1] + t * ab[1], a[2] + t * ab[2]))))
    return best


def sign_change_points(f, g, R, n_theta, n_phi):
    """Brute force: walk a (theta, phi) grid on a sphere f of radius R about the origin
    and return the linear interpolants of the grid edges on which g changes sign."""

    def P(i, j):
        th = 2 * math.pi * i / n_theta
        ph = math.pi * j / n_phi
        return (R * math.sin(ph) * math.cos(th), R * math.sin(ph) * math.sin(th), R * math.cos(ph))

    out = []
    for i in range(n_theta):
        for j in range(n_phi):
            a = P(i, j)
            for b in (P(i + 1, j), P(i, j + 1)):
                ga, gb = g.value(a), g.value(b)
                if (ga < 0) != (gb < 0):
                    s = ga / (ga - gb)
                    out.append(tuple(a[k] + s * (b[k] - a[k]) for k in range(3)))
    return out


class TestMarching(unittest.TestCase):
    def assert_on_both(self, f, g, pts):
        for p in pts:
            self.assertLess(abs(f.value(p)), 1e-10)
            self.assertLess(abs(g.value(p)), 1e-10)

    def test_viviani_curve(self):
        f = sphere((0.0, 0.0, 0.0), 2.0)
        g = cylinder((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0)
        h = 0.02
        pts, closed = march(f, g, (0.1, 0.0, 1.9), h, BOX)
        self.assertTrue(closed)
        self.assert_on_both(f, g, pts)
        # Closed form: (1 + cos t, sin t, 2 sin(t / 2)) for t in [0, 4 pi).
        for j in range(800):
            t = 4 * math.pi * j / 800
            x = (1 + math.cos(t), math.sin(t), 2 * math.sin(t / 2))
            self.assertLess(dist_to_polyline(x, pts, True), 1e-3)
        # Brute force: every sign change of g on a grid of the sphere is near the trace.
        for x in sign_change_points(f, g, 2.0, 120, 60):
            self.assertLess(dist_to_polyline(x, pts, True), 0.03)
        # The trace passes the double point (2, 0, 0) twice.
        near = [i for i, p in enumerate(pts) if norm(sub(p, (2.0, 0.0, 0.0))) < 2 * h]
        self.assertTrue(near)
        self.assertGreater(max(near) - min(near), len(pts) // 4)

    def test_one_start_point_finds_one_loop(self):
        f = sphere((0.0, 0.0, 0.0), 2.0)
        g = cylinder((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0)
        pts, closed = march(f, g, (1.0, 0.1, 1.6), 0.05, BOX)
        self.assertTrue(closed)
        self.assert_on_both(f, g, pts)
        for p in pts:
            self.assertAlmostEqual(p[2], math.sqrt(3.0), delta=1e-9)
        # The second loop, at z = -sqrt(3), is far from everything that was traced.
        for j in range(60):
            th = 2 * math.pi * j / 60
            x = (math.cos(th), math.sin(th), -math.sqrt(3.0))
            self.assertGreater(dist_to_polyline(x, pts, True), 3.0)
        # The brute force grid sees both loops.
        found = sign_change_points(f, g, 2.0, 60, 40)
        self.assertTrue(any(x[2] > 1 for x in found))
        self.assertTrue(any(x[2] < -1 for x in found))

    def test_random_sphere_pairs(self):
        rng = random.Random(3)
        for _ in range(15):
            c1 = tuple(rng.uniform(-0.5, 0.5) for _ in range(3))
            u = tuple(rng.gauss(0, 1) for _ in range(3))
            u = scale(1 / norm(u), u)
            r1, r2 = rng.uniform(1.0, 1.5), rng.uniform(0.6, 1.2)
            d = rng.uniform(abs(r1 - r2) + 0.2, r1 + r2 - 0.2)
            c2 = tuple(c1[k] + d * u[k] for k in range(3))
            f, g = sphere(c1, r1), sphere(c2, r2)
            a = (d * d + r1 * r1 - r2 * r2) / (2 * d)
            rho = math.sqrt(r1 * r1 - a * a)
            center = tuple(c1[k] + a * u[k] for k in range(3))
            v = (u[1], -u[0], 0.0) if abs(u[2]) < 0.9 else (0.0, u[2], -u[1])
            v = scale(1 / norm(v), v)
            w = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])
            start = tuple(center[k] + rho * v[k] + rng.uniform(-0.03, 0.03) for k in range(3))
            h = 0.03
            pts, closed = march(f, g, start, h, BOX)
            self.assertTrue(closed)
            self.assert_on_both(f, g, pts)
            length = sum(norm(sub(pts[i], pts[i - 1])) for i in range(len(pts)))
            self.assertAlmostEqual(length, 2 * math.pi * rho, delta=2 * h)
            for j in range(100):
                th = 2 * math.pi * j / 100
                x = tuple(center[k] + rho * (math.cos(th) * v[k] + math.sin(th) * w[k]) for k in range(3))
                # A chord of length at most 2h of a circle of radius rho is within (2h)^2 / (8 rho).
                self.assertLess(dist_to_polyline(x, pts, True), h * h / (2 * rho) + 1e-9)

    def test_open_branch_stops_at_the_box(self):
        f = plane((0.0, 0.0, 1.0), 0.0)
        g = cylinder((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), 1.0)
        box = ((-2.0, -2.0, -2.0), (2.0, 2.0, 2.0))
        pts, closed = march(f, g, (0.3, 1.1, 0.1), 0.1, box)
        self.assertFalse(closed)
        self.assert_on_both(f, g, pts)
        xs = sorted(p[0] for p in pts)
        self.assertLess(xs[0], -1.89)
        self.assertGreater(xs[-1], 1.89)
        for p in pts:
            self.assertAlmostEqual(p[1], 1.0, delta=1e-9)

    def test_crossing_of_two_ellipses(self):
        f = cylinder((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0)
        g = cylinder((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), 1.0)
        pts, closed = march(f, g, (0.05, 1.0, 1.0), 0.05, BOX)
        self.assertTrue(closed)
        self.assert_on_both(f, g, pts)
        # The trace passes the singular points (1, 0, 0) and (-1, 0, 0) on its own ellipse y = z.
        for p in pts:
            self.assertLess(abs(p[1] - p[2]), 1e-9)
        self.assertLess(min(norm(sub(p, (1.0, 0.0, 0.0))) for p in pts), 0.05)
        self.assertLess(min(norm(sub(p, (-1.0, 0.0, 0.0))) for p in pts), 0.05)

    def test_singular_start_is_rejected(self):
        f = sphere((0.0, 0.0, 0.0), 2.0)
        g = cylinder((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0)
        with self.assertRaises(ValueError):
            march(f, g, (2.0, 0.0, 0.0), 0.02, BOX)


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

History

Barnhill, Farin, Jordan and Piper's paper of 1987 described a marching method for two parametric surfaces, and Barnhill and Kersey refined it in 1990. Sederberg and Meyers in 1988 gave the normal cone test for loops, which made it possible to find start points on every closed branch. Patrikalakis's survey of 1993 placed marching beside lattice evolution, subdivision and analytic methods, and named the missed loops and the jumps between branches as its two main failures.

References

  1. Robert E. Barnhill, Gerald Farin, M. Jordan and Bruce R. Piper, Surface/surface intersection, Computer Aided Geometric Design 4(1-2), 3 to 16, 1987, the whole paper (the marching scheme, the start points, the step length and the correction onto both surfaces)
  2. Nicholas M. Patrikalakis, Surface-to-surface intersections, IEEE Computer Graphics and Applications 13(1), 89 to 95, 1993, the section on marching methods and their failure modes (missed loops, branch jumping and singular points)
  3. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Intersection problems, Section 5.8.2.3, Marching methods, and Section 5.8.3 on implicit and implicit intersections
  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 that tells when a pair of patches can hold a closed loop, which a marcher needs to find all start points

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