Inversion and projection
Let’s start with what a kernel asks, and how often. A STEP file stores the vertices of a solid as points in space and its edges as 3D curves; before a face can be meshed or classified, every one of those points needs its (u, v) on the surfaces it lies on. A user clicks on a model, and the click has to become a point on a face. A Boolean computes an intersection curve in space and then needs it as a curve in each face’s parameter rectangle. A validity check asks whether a vertex is within tolerance of the curve of each edge that uses it. Each of these is the same question: given a point P and a curve C(t) or a surface S(u, v), which parameters give the point of the geometry nearest to P, and how far is it?
The question has two names, depending on what we expect. Point inversion is the case where P is known to lie on the geometry: a vertex on its edge, a sample of an intersection curve on its face. The answer is the parameter that evaluates back to P. Point projection is the general case, where P can be anywhere and the answer is the nearest point. Inversion is projection with an expected distance of zero, so one routine serves both, and the distance it returns is how we check that an inversion really was one.
So the contract of a projection routine is: given P, return the parameters of the nearest point and the distance to it. Everything else in this article is about meeting that contract on each kind of geometry, including the places where the nearest point is not unique.
The condition for a foot point
We start with a curve. The squared distance from P to the point at parameter t is a function of one variable, and it is simpler to work with half of it:
f(t) = ½ |C(t) − P|2, f′(t) = (C(t) − P) · C′(t)
At the nearest point inside the curve’s range, f′ is zero. Read geometrically, the segment from P to the curve is perpendicular to the tangent there. We call such a point a foot point, and the equation the stationarity condition:
g(t) = (C(t) − P) · C′(t) = 0
For a surface there are two parameters and so two conditions, one per tangent direction:
(S − P) · Su = 0, (S − P) · Sv = 0
The condition is necessary but it is far from sufficient. Let’s take the 20 by 10 ellipse of parts three and three and the point P = (5, 2) inside it.
As we can see, the condition finds every point where the distance is stationary: the nearest, the farthest, and the others in between. A point inside an ellipse near its centre always has four, and a point on the axis of a cylinder has a whole circle of them. So solving the condition and choosing among its solutions are two separate steps, and an implementation should keep them separate.
There is a second gap. The condition only holds inside the parameter range. A bounded curve can have its nearest point at one of its ends, where the distance is still decreasing as the curve stops, and there g is not zero. On a surface patch the same is true of its four edges and four corners. So the candidates are the roots of the condition plus the boundary.
Collect every candidate: each root of the stationarity condition inside the range, and the boundary of the range. Evaluate the distance at each, and return the smallest. Any method that returns the first root it converges to is solving a different problem.
The elementary surfaces
Part three printed, under each of the ten elementary geometries, the inverse map: the parameter recovered from a point. For the five surfaces those formulas are more than inversions. They are projections, exact for any point in space, because the nearest point on a surface of revolution lies in the half-plane through the axis and the point. The angle u of that half-plane is the same arctangent for all four surfaces of revolution, and what remains is a problem in the plane of one meridian.
We write the point in the surface’s own frame, (x, y, z) = ((P−O)·X, (P−O)·Y, (P−O)·Z), and ρ = √(x2 + y2) for its distance from the axis:
| Surface | Nearest point | Where it is not unique | Distance there |
|---|---|---|---|
| Plane | u = x, v = y | nowhere | |z| |
| Cylinder, radius r | u = atan2(y, x), v = z | on the axis: every u | r |
| Sphere, radius r | u = atan2(y, x), v = atan2(z, ρ) | at the centre: every (u, v) | r |
| Torus, radii R, r | u = atan2(y, x), v = atan2(z, ρ−R) | on the axis: every u; on the circle through the tube’s centre: every v | √(R2+z2) − r; r |
| Cone, half-angle α, radius R at v = 0 | u = atan2(y, x), v = sinα (ρ−R) + cosα z | on the axis: every u | |(−R, z)·(cosα, −sinα)| |
The cone’s v is the foot of the point on the generator line in its meridian half-plane: the generator starts at (R, 0) in (ρ, z) coordinates with direction (sinα, cosα), and v is the projection of (ρ−R, z) onto that direction. One case needs care: a cone extends through its apex, and the generator on the far side of the axis can be closer than the near one. If the point is beyond the apex along the axis (−R > z tanα), we take u = atan2(−y, −x), the opposite half-plane, and compute v with the signed radial coordinate x cos u + y sin u in place of ρ. On that side it equals −ρ, and the foot lands on the other nappe.
The torus has a similar case. When its tube radius is larger than its major radius (r > R), the tube swallows the axis, and the nearest point can lie in the opposite half-plane. So we evaluate the candidate at u and at u + π and keep the nearer one.
The third column is what an implementation must decide in advance. On the axis of a cylinder every u is correct, and so is none of them in particular. The distance is still well defined, so the right behaviour is to return a fixed choice (u = 0 is the usual one) together with the true distance, and never to fail. With that rule, a point on the axis of a cylinder of radius 2 returns u = 0 and a distance of exactly 2; the centre of a sphere of radius 3 returns its north pole and 3; the centre of a 5 by 1 torus returns u = 0, v = π on the inner equator and 4. A caller that needs a particular foot (a mesher walking along a seam, say) has to pass a neighbouring parameter and reframe the answer against it, as part five described.
Part three’s inverse of the ellipse, u = atan2(y/b, x/a), is the eccentric angle of the point. On the curve it is exact. Off the curve it is not a projection: for P = (5, 2) it returns t = 0.675, a point 11.435 away, while the nearest point is at t = 1.254 and 7.603 away. The same holds for the parabola and the hyperbola. Their inverses are inversions only, and projection onto them needs the next section.
The conics, and the root a quartic loses
The line and the circle are the two curves with a one-line projection. For a line through O with unit direction d, t = (P−O)·d. For a circle it is the angle of the point in the circle’s plane, t = atan2(y, x), with the whole circle as the answer when the point is on the axis.
The other three conics need their stationarity condition solved, and in each case it becomes a polynomial. For the ellipse C(t) = (a cos t, b sin t), with c2 = a2 − b2 and the point at (px, py) in the ellipse’s frame, the condition is
g(t) = −c2 sin t cos t + a px sin t − b py cos t = 0
The substitution s = tan(t/2) turns sine and cosine into rational functions of s (sin t = 2s/(1+s2), cos t = (1−s2)/(1+s2)), and multiplying through by (1+s2)2 leaves a quartic:
b py s4 + 2(a px + c2) s3 + 2(a px − c2) s − b py = 0
A quartic has a closed-form solution, so it looks as though we are done. But the substitution has a blind spot. t = π corresponds to s = ∞, so the quartic cannot have a root there. When the foot is exactly at t = π, the leading coefficient b py is zero, the quartic drops to a cubic, and the root we need disappears with the degree. This is not a rare configuration: it is every point on the major axis behind the centre. On a 20 by 2 ellipse, for P = (−25, 0), the nearest point is the vertex at t = π, 5 away. The quartic alone finds nothing nearer than t = 0, the far vertex, and answers 45.
There are two fixes, and robust code uses both. First, add t = 0 and t = π to the candidates unconditionally; they cost two evaluations. Second, for roots near π, solve the reversed quartic in r = tan((t−π)/2), which is the same polynomial with its coefficients reversed and every other sign flipped, since s = −1/r. Then polish every root with a few Newton steps on the trigonometric g(t) itself, not on the polynomial. A polynomial root next to another root (two feet close together) is only resolved to about the square root of the machine precision, and the polish recovers the rest.
The parabola and the hyperbola follow the same pattern with simpler substitutions. For the parabola C(t) = (t2/4f, t) the condition multiplied by 8f2 is already a cubic:
t3 + (8f2 − 4f px) t − 8f2 py = 0
For the hyperbola C(t) = (a cosh t, b sinh t), with k = a2 + b2, the substitution w = et gives a quartic of which only the positive roots are kept, t = ln w:
k w4 − 2(a px + b py) w3 + 2(a px − b py) w − k = 0
Free-form curves: Newton from seeds
A B-spline has no closed form for its feet, so we solve the condition numerically. Newton’s method on g(t) = 0 needs its derivative, which is the second derivative of f:
g′(t) = C′·C′ + (C − P)·C″, t ← t − g(t) / g′(t)
Two terms make up g′. The first is the squared speed of the curve and is always positive. The second is proportional to the distance, through (C − P), and to the curvature, through C″. Some implementations drop it, which is the Gauss–Newton method. For inversion that is harmless, because the distance is zero at the answer. For projection from a point far from a curved piece of geometry it is not: the dropped term is the large one, and the iteration crawls.
Newton as written converges to the stationary point nearest its start, whichever kind it is. Where g′ is negative we are near a maximum of the distance, and the step goes towards it. So the iteration must minimise f, not solve g = 0. In practice:
- When g′ ≤ 0, replace it with a small positive number (or with C′·C′ alone), so the step always goes downhill.
- Accept a step only if f decreases; otherwise halve it, up to a fixed number of times.
- Keep t inside the range. A step that would leave it stops at the end, and if the slope there points outwards the end is a candidate. This is how the minima at the ends of the curve are reached at all.
- Stop when the step is below the parametric tolerance.
Newton converges quadratically, but only from close enough. So it needs starting points, called seeds, and the usual choice is a few per knot span: within one span the curve is a single polynomial piece, and degree + 1 samples are enough to see its general shape. Let’s run this on a cubic B-spline with five spans and a point Q above its middle.
Two lessons come out of this figure. First, the seeds that land on the false minimum are not wrong; they converge correctly to a point that is not the answer. That is why every candidate is kept and the smallest is chosen at the end. Second, a seed whose iteration does not converge within its step budget must also be kept, with whatever point it reached. Dropping it is tempting, and it is how a projection returns a far local minimum when the seed near the true one happened to be slow.
What seeding cannot give is a guarantee. Degree + 1 seeds per span see the shape of the span, but within one span g is a polynomial of degree 2p − 1, which can have more roots than there are seeds between them. The next section removes the guesswork, in two ways: one avoids searching most of the curve, and the other finds every root in the spans that remain.
Never missing the nearest point
A lower bound per span. Inserting each interior knot of a B-spline until its multiplicity equals the degree, with the knot insertion of part four, cuts the curve into Bézier pieces, one per span, each with its own control points. By the convex hull property of part four, each piece lies inside the convex hull of those points. It therefore lies inside the axis-aligned box of those points, and the distance from Q to that box (zero if Q is inside) is a lower bound on the distance to any point of the piece. That gives a branch-and-bound search:
- Split the curve into its Bézier pieces, and compute the box of each piece’s control points.
- Put the pieces in a priority queue, ordered by the distance from Q to their box.
- Take the nearest box. If its distance is greater than the best distance found so far, stop: every remaining box is at least as far.
- Otherwise search that piece for its nearest point, update the best distance, and go back to step 3.
Two details matter in step 3. The comparison is strictly greater: a box that only touches the circle may hold a point exactly as near, which is the case here, where the answer is on the knot shared by two pieces. And the bound remains valid for a rational curve with positive weights, because the convex hull property survives the weights.
Every root of a span. Within one Bézier piece with control points b0, …, bp, both C(s) − Q and C′(s) are polynomials in Bernstein form, over the local parameter s ∈ [0, 1]:
C(s) − Q = Σj=0p Bj,p(s) (bj − Q), C′(s) = p Σi=0p−1 Bi,p−1(s) (bi+1 − bi)
Their dot product g(s) is a polynomial of degree 2p − 1, and the product of two Bernstein polynomials is again one, with coefficients we can write down directly:
ck = Σi+j=k [ C(p−1, i) C(p, j) / C(2p−1, k) ] p (bi+1 − bi)·(bj − Q), k = 0, …, 2p−1
where C(n, k) is the binomial coefficient. Now the variation-diminishing property of the Bernstein basis does the rest: the number of roots of g in (0, 1) is at most the number of sign changes in its coefficients c0, …, c2p−1. With no sign change there is no root, and the span has no interior foot. With exactly one there is exactly one root, bracketed by the span. With more, we split the coefficients at s = ½ with de Casteljau’s algorithm, which part four used on control points and which works on any Bernstein coefficients, and look at each half again. The recursion ends quickly in practice; a depth limit of about forty halvings is a safe stop.
We only need the roots where g rises through zero, from negative to positive, because those are the minima of the distance. Each one is bracketed, so the bounded Newton iteration of the previous section, confined to its bracket, converges to it. Two more candidates complete the span: its ends, which are the knots. At a knot of full multiplicity the curve can turn a corner, g can jump, and a knot where g is negative on the left and positive on the right is a minimum with no root at all. For a rational curve the same scan applies to the numerator of the derivative of the distance, (A′·A) w − |A|2 w′ with A the homogeneous control points minus Q times the weight, which has degree 3p − 1.
Together, the two tools leave nothing to chance on a curve. The boxes decide which spans can contain the answer, and the sign changes find every candidate inside those spans.
Free-form surfaces
On a surface the iteration has two unknowns. The gradient and the Hessian of f(u, v) = ½|S − P|2, with r = S(u, v) − P, are
∇f = (Su·r, Sv·r), H = [ Su·Su + Suu·r, Su·Sv + Suv·r ; Su·Sv + Suv·r, Sv·Sv + Svv·r ]
and the Newton step δ solves H δ = −∇f. The first part of each entry of H is the first fundamental form of part five; the second part is the curvature term, proportional to the distance, that Gauss–Newton drops. Each safeguard from the curve case carries over, in its two-dimensional form:
- Positive definiteness. Away from a minimum H can be indefinite. If its smallest eigenvalue is not positive, add μI with μ just large enough to make it so; the step then goes downhill.
- Bounds, one parameter at a time. The iteration works inside a rectangle (the patch, or the face’s domain). When a parameter sits on a bound and its component of the gradient points outwards, freeze it and take the step in the other parameter alone. This reaches a minimum on an edge exactly, and one at a corner when both are frozen, instead of stalling against a clamp.
- Line search. Accept the step only if f decreases, projecting back into the rectangle after each halving.
Seeding on a surface is where implementations most often go wrong, because the obvious choice is a uniform grid over the whole parameter rectangle. Its spacing ignores the knots, so a dense control net gets the same seeds as a coarse one. We measured it against branch and bound on bumpy bicubic surfaces, with a dense brute-force search as the reference:
| Control net | Queries | 17 × 17 uniform seeds: missed | Worst error | Branch and bound: missed |
|---|---|---|---|---|
| 6 × 6 | 150 | 49 (33%) | 0.47 | 0 |
| 12 × 12 | 150 | 28 (19%) | 1.06 | 0 |
| 24 × 24 | 150 | 23 (15%) | 1.88 | 0 |
| 48 × 48 | 150 | 57 (38%) | 31.46 | 0 |
The branch and bound is the curve algorithm with one more dimension. Each patch between knot lines lies in the box of its (p+1)(q+1) control points. With thousands of patches, testing every box for every query becomes the cost, so the boxes are arranged in a hierarchy: split the index range of the patches in half along its longer direction, recursively, and give each node the union of its children’s boxes. The priority queue then holds nodes, and a whole region of the surface is discarded with one box test.
Inside a patch that cannot be discarded, the curve’s exact scan has no direct counterpart, because two equations in two unknowns have no sign rule. What carries over is subdivision. Convert the patch to Bernstein form and work on pieces of it:
- Discard a piece if the box of its control points is farther from P than the best distance so far.
- Bound the Hessian H over the piece. Every term in it (Su, Suu, r and the rest) is a Bernstein polynomial whose values lie in the box of its own coefficients, so each entry of H lies in an interval we can compute from those boxes. If the lower bounds of both diagonal entries are positive and their product exceeds the largest square of the off-diagonal entry, H is positive definite everywhere on the piece: the distance is convex there, it has a single minimum, and the bounded Newton iteration finds it from any start.
- Otherwise split the piece in half with de Casteljau’s algorithm along its longer direction, visit the half whose control points are closer first, and repeat.
- Minima on the edges of a patch (its boundary, or a crease where the surface is only C0) are found on the edge itself, which is a curve, with the exact scan of the previous section.
Close to a minimum the distance is convex, so the subdivision stops after a few levels; it only goes deep where two basins sit close together. The search took at most about a tenth of a millisecond per query, on every net in the table.
That last case is not hypothetical. An earlier version of this search seeded each patch from a small grid of samples instead of subdividing it, and on the same 600 queries it missed one. The patch held two shallow basins 0.008 apart in distance, its samples showed only one of them, and Newton converged to the wrong basin. The answer it returned was 0.0013 farther than the true nearest point. The boxes had done their job. The samples inside the patch failed, and subdivision is what removed them.
Tolerance, and answers on a seam
A projection returns a distance computed in floating point, and a point on the surface rarely comes back at exactly zero. So the routine has to say what “on the surface” means, and the simplest consistent rule is to snap: a distance at or below the confusion tolerance (10−7 in model units is the common choice) is returned as exactly zero. Then a single routine answers both questions, and the containment test is defined by it:
contains(P) ⇔ project(P).distance = 0
If the two are written separately, sooner or later they disagree on a point near the tolerance, and an algorithm that asks one and then the other gets a contradiction.
The parameter needs the same care on a periodic geometry. A projection onto a cylinder returns u in [0, 2π), which is right in isolation and wrong for a caller whose neighbouring point is at 6.2: the answer 0.05 is the same place on the surface, but the step between them reads as −6.15 instead of +0.13. As part five argued, the projection itself should return the canonical value, and the caller should reframe it against its own reference. The next section is the place where that matters most.
Projecting a curve onto a surface
An edge of a B-rep has a 3D curve and, on each face it bounds, a 2D curve in that face’s parameter rectangle (part one attached it to the coedge, as its pcurve). Building that 2D curve from the 3D one is curve projection, and it divides the same way point projection does: a closed form for the simple pairs, and a numerical method for the rest.
The closed forms are the pairs where the 3D curve is an isoparametric curve of the surface or a line in a plane:
| Surface | 3D curve | Curve in (u, v) |
|---|---|---|
| Plane | line; circle | line; circle |
| Cylinder | line parallel to the axis; circle perpendicular to it | vertical line u = u0; horizontal line v = v0 |
| Cone | generator line; circle perpendicular to the axis | vertical line; horizontal line |
| Sphere | meridian circle; parallel circle | vertical line; horizontal line, v = asin(h/R) |
| Torus | circle round the axis; circle round the tube | horizontal line; vertical line |
Each closed form assumes the curve really lies on the surface, and an implementation should check it before trusting the answer: evaluate the 2D curve at a few parameters, map through the surface, and compare with the 3D curve. A circle of the wrong radius on a cylinder, or a circle on a torus that is neither round the axis nor round the tube (there are such circles), would otherwise produce a confident wrong curve.
Everything else (an ellipse on a cylinder, any curve on a free-form surface) is done numerically, and the steps are:
- Sample the 3D curve, densely enough for its curvature.
- Project each sample onto the surface with the routine of the previous sections, passing the previous sample’s (u, v) as the starting point.
- Unwrap each periodic parameter against the previous sample: u ← u + 2π round((uprev − u)/2π). At a pole of a sphere, where u is undefined, take it from the neighbouring sample.
- Fit a 2D curve through the unwrapped (u, v) samples, with chord-length or centripetal parameters.
- Check the result in three dimensions, at points between the samples, and refine where it deviates by more than the tolerance.
Step three is the one that is easy to forget, because every individual projection is correct. Projected one at a time, 49 samples of that ellipse give one jump of more than π between neighbours, and a fit through them draws the long segment on the left. The 3D check of step five would catch it, but only after the work of fitting it.
Implementation checklist
If we implement projection from scratch, these are the decisions in the order the problems arrive.
Return parameters and distance, never fail. One routine, used for both inversion and projection. Where the foot is not unique, return a fixed choice and the true distance.
Keep solving and choosing apart. Collect every root of the stationarity condition and every boundary candidate, then take the smallest distance.
Use the closed forms where they exist, and only as projections where they are projections. On the five elementary surfaces they are; on the ellipse, parabola and hyperbola the inverse map is an inversion only.
Add the points a substitution cannot reach. For the ellipse that is t = 0 and t = π. Polish every polynomial root with Newton on the original equation.
Minimise the distance, do not solve g = 0. Keep the step downhill, keep the curvature term in the second derivative, accept only decreasing steps, and freeze parameters pinned at a bound by an outward slope.
Keep every seed’s result, converged or not.
Bound before searching. Boxes of Bézier control points, nearest first, stop at the first box farther than the best distance found. On surfaces, put the boxes in a hierarchy.
Find every root in a span from the sign changes of its Bernstein coefficients, and treat knots, patch edges and corners as candidates. On a surface, subdivide a patch until the distance is provably convex on each piece, instead of trusting samples.
Snap the distance at the confusion tolerance, and define containment by the same routine.
Unwrap periodic parameters against a neighbour before fitting a curve through them, and check the fitted curve in three dimensions.
What this article leaves out
Projection along a direction. Everything here is orthogonal projection, the nearest point. Projecting a point along a fixed direction (as a drawing view does, or a curve projected onto a face along the view direction) is a line–surface intersection, which belongs to part ten.
The distance between two curves or two surfaces. The same condition with two points instead of one: the segment between them is perpendicular to both tangents. It is a stationarity problem in two to four parameters, solved by the same machinery (bounds on pairs of boxes, then bounded Newton), and it has more candidates and more degenerate cases.
Intersection. Two curves meeting, a curve crossing a surface, two surfaces meeting along a curve: these are the next foundation algorithm, and their numerical part leans on everything in this article. That is part ten.
The quality of a fitted 2D curve. Step four of the curve projection fits a curve through samples, and how many samples, which parameters and which degree decide whether the fitted curve stays within tolerance of the 3D one between them. Fitting is its own subject.
Reading list
Sources
L. Piegl and W. Tiller, The NURBS Book, 2nd edition, Springer, 1997, section 6.1, “Point inversion and projection for curves and surfaces”. Not consulted directly for this article. The standard reference for the Newton formulation of section five and its stopping tests.
Y. L. Ma and W. T. Hewitt, “Point inversion and projection for NURBS curve and surface: control polygon approach”, Computer Aided Geometric Design 20 (2003), 79–99. Not consulted directly. Subdivides into Bézier pieces and uses the control polygon to select the candidate pieces before refining with Newton, which is the idea behind section six.
I. Selimovic, “Improved algorithms for the projection of points on NURBS curves and surfaces”, Computer Aided Geometric Design 23 (2006), 439–445. Not consulted directly. Refines Ma and Hewitt’s elimination test for pieces that cannot contain the nearest point.
S.-M. Hu and J. Wallner, “A second order algorithm for orthogonal projection onto curves and surfaces”, Computer Aided Geometric Design 22 (2005), 251–260. Not consulted directly. A geometric second-order iteration, an alternative to Newton on the stationarity condition with a smaller sensitivity to the starting point.
D. Eberly, “Distance from a Point to an Ellipse, an Ellipsoid, or a Hyperellipsoid”, Geometric Tools. Not consulted directly. A robust treatment of the ellipse case of section four by a different reduction.
Method
The four figures are drawn by a program that computes what they show: the four feet of figure one are the sign changes of g refined by bisection, the candidates of figure two are where the bounded Newton iteration of section five takes each seed, and the searched and skipped boxes of figure three come from running the branch and bound of section six. Each is checked against a second implementation of every method in the article, written separately from the figure program: the four feet and their distances agree to 10−9, its own candidates on the curve of figure two include the same three, and its nearest point is t = 0.4 at a distance of 5.000000000.
All the measurements use that second implementation. The surface table was measured on bicubic surfaces with clamped uniform knots, control points on a unit grid and heights drawn uniformly in ±1.5, with query points 1.6 to 3 units above or below. The reference is a brute-force grid of at least eight samples per span in each direction, with the six best samples refined. A projection counts as missed if it is more than 10−7 farther than the best of the reference and both methods. The uniform-seed method samples a 17 × 17 grid over the whole rectangle and refines the twelve nearest samples with the bounded Newton iteration of section seven.
. The method notes describe the checks without naming an implementation.
. Part numbers renumbered for the new part two, The Mathematics a Kernel Stands On.