Algorithm Search⌘K

Algorithmcore

Rolling-ball blend

Also called rolling-ball fillet, constant radius fillet.

Builds a blend as the envelope of a ball of fixed or varying radius that rolls while touching both surfaces, from the spine curve of the ball centres.

Time
O(m (i + k)) worst
Space
O(m k) extra
Where
i = the number of Newton iterations in one step; k = the number of points on each cross-section arc; m = the number of spine points
Properties
deterministicnot exactiterative
Origin
Byoung K. Choi, Suk Y. Ju, 1989

The rolling-ball blend of two surfaces S1S_1 and S2S_2 is the surface swept by a ball of radius rr that rolls along the edge between them while it touches both. Its blending surface is the envelope of the ball: at each position, the ball touches the envelope along a circle, and the part of that circle between the two contact points is a cross section of the blend. The ball center moves on the spine, which is the intersection of the two offset surfaces at distance rr. So the algorithm traces the spine with surface surface intersection, and then, for each center, drops the contact points onto the surfaces and draws the arc between them. Choi and Ju gave this construction for parametric surfaces in 1989. The result meets both surfaces with the same tangent plane (G1G^1), but in general not with the same curvature.

In plain words

Push a ball into the inner corner between two walls, so that it touches both, and roll it along the corner. The ball sweeps out a rounded strip. That strip is the fillet.

The center of the ball always stays at the same distance from both walls. So it moves along the line where the two walls, moved out by the radius of the ball, cross each other. That line is called the spine.

To build the fillet, first follow the spine in small steps. At each step, find the two points where the ball touches the walls. They lie straight down from the center onto each wall. Then join them with the short arc of a circle around the center. The arcs, one after the other, form the fillet.

The problem

The input is two surfaces S1S_1 and S2S_2, each with a signed distance function sdi\mathrm{sd}_i that is exact near the surface and whose gradient is the unit normal nin_i, a radius r>0r > 0, a side si∈{+1,−1}s_i \in \{+1, -1\} for each surface, a start point x0x_0 near the spine, and a step length hh. The ball must lie on side sis_i of SiS_i, so its center cc satisfies

sd1(c)=s1r,sd2(c)=s2r.\mathrm{sd}_1(c) = s_1 r, \qquad \mathrm{sd}_2(c) = s_2 r.

The output is a sequence of spine points c0,c1,…c_0, c_1, \ldots and, for each, the contact points p1∈S1p_1 \in S_1, p2∈S2p_2 \in S_2 and a sampled arc between them. For a fillet on a concave edge the ball lies outside the solid, so sis_i is the side of the outward normal; for a round on a convex edge it lies inside. The faces are oriented so that the outward normal of each face follows the right-hand rule with its loops, and the blend inherits the outward normals of S1S_1 and S2S_2 at its two trimlines.

The algorithm

  1. ROLLING-BALL-BLEND(S1, S2, r, s1, s2, x0, h)
  2. 1c ← CORRECT(x0) ▷ Newton onto sd1 = s1 r and sd2 = s2 r
  3. 2spine ← [c]
  4. 3repeat
  5. 4t ← n1(c) × n2(c), as a unit vector that agrees in sign with the previous t
  6. 5c ← CORRECT(c + h t)
  7. 6append c to spine
  8. 7until c is back near spine[0] or the step budget is used up
  9. 8for each c in spine do
  10. 9p1 ← c − s1 r n1(c), p2 ← c − s2 r n2(c) ▷ the contact points
  11. 10A ← the shorter arc from p1 to p2 on the circle with center c and radius r
  12. 11record (c, p1, p2, A)
  13. 12return the records

CORRECT at lines L1 and L5 is the Newton method for systems on the two equations F(x)=(sd1(x)−s1r,sd2(x)−s2r)=0F(x) = (\mathrm{sd}_1(x) - s_1 r, \mathrm{sd}_2(x) - s_2 r) = 0, three unknowns and two equations. It takes the step of least length, x←x−J⊤(JJ⊤)−1F(x)x \leftarrow x - J^\top (J J^\top)^{-1} F(x), where the rows of JJ are n1(x)n_1(x) and n2(x)n_2(x). The step is undefined where n1∥n2n_1 \parallel n_2, which is where the spine has no tangent, and the implementation stops there with an error. Lines L3 to L7 are a marching trace of the intersection of the two offsets, with the step along n1×n2n_1 \times n_2 that is the tangent of the spine.

Line L10 lies in the plane through cc normal to tt, because both contact points do: ni⊥tn_i \perp t, so pi−c=−sirnip_i - c = -s_i r n_i is perpendicular to tt. With a=(p1−c)/ra = (p_1 - c)/r, b=(p2−c)/rb = (p_2 - c)/r and θ=arccos⁡(a⋅b)\theta = \arccos(a \cdot b), the arc is c+r (sin⁡((1−λ)θ) a+sin⁡(λθ) b)/sin⁡θc + r \, (\sin((1 - \lambda)\theta) \, a + \sin(\lambda \theta) \, b) / \sin \theta for 0≤λ≤10 \le \lambda \le 1.

Example

Take the floor z=0z = 0 with the ball above it (s1=+1s_1 = +1), a vertical shaft x2+y2=1x^2 + y^2 = 1 with the ball outside it (s2=+1s_2 = +1), and r=1/2r = 1/2. This is the fillet at the foot of the shaft. Start at x0=(1.8,0,0.7)x_0 = (1.8, 0, 0.7) with h=0.05h = 0.05 and three points per arc.

step spine point cc p1p_1 (floor) arc midpoint p2p_2 (shaft)
0 (1.5,0,0.5)(1.5, 0, 0.5) (1.5,0,0)(1.5, 0, 0) (1.14645,0,0.14645)(1.14645, 0, 0.14645) (1,0,0.5)(1, 0, 0.5)
1 (1.49917,0.04997,0.5)(1.49917, 0.04997, 0.5) (1.49917,0.04997,0)(1.49917, 0.04997, 0) (1.14581,0.03819,0.14645)(1.14581, 0.03819, 0.14645) (0.99944,0.03331,0.5)(0.99944, 0.03331, 0.5)
2 (1.49667,0.09989,0.5)(1.49667, 0.09989, 0.5) (1.49667,0.09989,0)(1.49667, 0.09989, 0) (1.14390,0.07634,0.14645)(1.14390, 0.07634, 0.14645) (0.99778,0.06659,0.5)(0.99778, 0.06659, 0.5)
47 (0.00706,1.49998,0.5)(0.00706, 1.49998, 0.5) (0.00706,1.49998,0)(0.00706, 1.49998, 0) (0.00540,1.14643,0.14645)(0.00540, 1.14643, 0.14645) (0.00471,0.99999,0.5)(0.00471, 0.99999, 0.5)
94 (−1.49993,0.01413,0.5)(-1.49993, 0.01413, 0.5) (−1.49993,0.01413,0)(-1.49993, 0.01413, 0) (−1.14640,0.01080,0.14645)(-1.14640, 0.01080, 0.14645) (−0.99996,0.00942,0.5)(-0.99996, 0.00942, 0.5)

At step 0, one Newton step moves x0x_0 to (1.5,0,0.5)(1.5, 0, 0.5): the offsets are the plane z=1/2z = 1/2 and the cylinder of radius 3/23/2, both linear in the direction of the step. The tangent is n1×n2=(0,0,1)×(1,0,0)=(0,1,0)n_1 \times n_2 = (0, 0, 1) \times (1, 0, 0) = (0, 1, 0). The spine closes after 188188 points, which matches the length 2π⋅3/2≈9.422\pi \cdot 3/2 \approx 9.42 of the circle of radius 3/23/2 at height 1/21/2 divided by hh. The arcs are quarter circles, and every arc point xx satisfies (x12+x22−3/2)2+(x3−1/2)2=1/4(\sqrt{x_1^2 + x_2^2} - 3/2)^2 + (x_3 - 1/2)^2 = 1/4: the blend is the inner lower quarter of a torus with axis radius 3/23/2 and tube radius 1/21/2.

Correctness

Let c(σ)c(\sigma) be a regular parametrization of the exact spine, so that sdi(c(σ))=sir\mathrm{sd}_i(c(\sigma)) = s_i r for all σ\sigma, and let B(σ)B(\sigma) be the sphere of radius rr around c(σ)c(\sigma). Differentiating gives ni(c)⋅c′=0n_i(c) \cdot c' = 0, so c′c' is parallel to n1×n2n_1 \times n_2, which justifies line L4. The envelope of the family ∣x−c(σ)∣2=r2|x - c(\sigma)|^2 = r^2 is found by also setting the derivative in σ\sigma to zero: (x−c(σ))⋅c′(σ)=0(x - c(\sigma)) \cdot c'(\sigma) = 0. So each sphere touches the envelope along the characteristic circle, its intersection with the plane through cc normal to c′c'. The contact point pi=c−sirnip_i = c - s_i r n_i lies on SiS_i, because sdi\mathrm{sd}_i is a signed distance whose gradient is the unit normal, and it lies on the characteristic circle, because ∣pi−c∣=r|p_i - c| = r and (pi−c)⋅c′=−sir ni⋅c′=0(p_i - c) \cdot c' = -s_i r \, n_i \cdot c' = 0. At pip_i the normal of the envelope is (pi−c)/r=−sini(p_i - c)/r = -s_i n_i, parallel to the normal of SiS_i, so the join is G1G^1. The full proof states the conditions and also shows that the ball does not cut either surface near the contact.

What is proved is the geometry of exact spine points. The trace itself is numerical: each spine point satisfies the two equations within the Newton tolerance, and a step hh that is too long can jump to another branch of the spine, as for every marching method.

Proof: The rolling-ball cross sections lie on the envelope and meet both surfaces with the same tangent planefull

Let S1S_1 and S2S_2 be surfaces with signed distance functions sd1\mathrm{sd}_1 and sd2\mathrm{sd}_2. Assume that on an open set UU each sdi\mathrm{sd}_i is C2C^2 with ∣∇sdi∣=1|\nabla \mathrm{sd}_i| = 1, that sdi(x)\mathrm{sd}_i(x) is the signed distance from xx to SiS_i, and that the nearest point of SiS_i to xx is unique and equal to x−sdi(x) ni(x)x - \mathrm{sd}_i(x) \, n_i(x), where ni=∇sdin_i = \nabla \mathrm{sd}_i. This holds near a smooth surface at distances below its smallest radius of curvature on that side, and everywhere for planes, and for cylinders away from the axis. Fix r>0r > 0 and s1,s2∈{+1,−1}s_1, s_2 \in \{+1, -1\}.

Let c:(α,β)→Uc : (\alpha, \beta) \to U be a C1C^1 curve with c′(σ)≠0c'(\sigma) \ne 0 and sdi(c(σ))=sir\mathrm{sd}_i(c(\sigma)) = s_i r for i=1,2i = 1, 2 and all σ\sigma, the exact spine. Write nin_i for ni(c(σ))n_i(c(\sigma)), pi(σ)=c(σ)−sirnip_i(\sigma) = c(\sigma) - s_i r n_i, and K(σ)={x:∣x−c(σ)∣=r, (x−c(σ))⋅c′(σ)=0}K(\sigma) = \{x : |x - c(\sigma)| = r, \ (x - c(\sigma)) \cdot c'(\sigma) = 0\}.

Lemma 1 (the tangent). n1⋅c′=n2⋅c′=0n_1 \cdot c' = n_2 \cdot c' = 0. If n1∦n2n_1 \nparallel n_2, then c′c' is a nonzero multiple of n1×n2n_1 \times n_2.

Proof. Differentiate sdi(c(σ))=sir\mathrm{sd}_i(c(\sigma)) = s_i r by the chain rule: ∇sdi(c)⋅c′=0\nabla \mathrm{sd}_i(c) \cdot c' = 0. A nonzero vector perpendicular to two independent vectors is a multiple of their cross product. □\square

Lemma 2 (the envelope). Let EE be the envelope of the spheres Σ(σ)={x:∣x−c(σ)∣2=r2}\Sigma(\sigma) = \{x : |x - c(\sigma)|^2 = r^2\}, the set of points xx for which some σ\sigma solves G(x,σ)=∣x−c(σ)∣2−r2=0G(x, \sigma) = |x - c(\sigma)|^2 - r^2 = 0 and ∂σG(x,σ)=0\partial_\sigma G(x, \sigma) = 0. Then the points of EE for the parameter σ\sigma form the circle K(σ)K(\sigma), which has radius rr and lies in the plane through c(σ)c(\sigma) normal to c′(σ)c'(\sigma).

Proof. ∂σG=−2(x−c(σ))⋅c′(σ)\partial_\sigma G = -2 (x - c(\sigma)) \cdot c'(\sigma). So the two conditions are exactly ∣x−c∣=r|x - c| = r and (x−c)⋅c′=0(x - c) \cdot c' = 0, which define K(σ)K(\sigma). The plane through the center cc cuts the sphere in a great circle of radius rr. □\square

Lemma 3 (the contact points). pi(σ)∈Sip_i(\sigma) \in S_i, pi(σ)∈K(σ)p_i(\sigma) \in K(\sigma), and c(σ)−pi(σ)=sir ni(pi)c(\sigma) - p_i(\sigma) = s_i r \, n_i(p_i).

Proof. By the assumption on nearest points, c−sdi(c)ni(c)=c−sirnic - \mathrm{sd}_i(c) n_i(c) = c - s_i r n_i is the nearest point of SiS_i to cc, so pi∈Sip_i \in S_i. Next, ∣pi−c∣=r∣ni∣=r|p_i - c| = r |n_i| = r, and (pi−c)⋅c′=−sir ni⋅c′=0(p_i - c) \cdot c' = -s_i r \, n_i \cdot c' = 0 by Lemma 1, so pi∈K(σ)p_i \in K(\sigma). Finally, the gradient of a distance function is constant along the segment from a point to its nearest point on the surface, because the distance grows with slope 11 along that segment, so ni(pi)=ni(c)n_i(p_i) = n_i(c), and c−pi=sirni(pi)c - p_i = s_i r n_i(p_i). □\square

Lemma 4 (no cut near the contact). The ball {x:∣x−c(σ)∣<r}\{x : |x - c(\sigma)| < r\} contains no point of SiS_i that lies in UU.

Proof. A point y∈Siy \in S_i with ∣y−c∣<r|y - c| < r would give ∣sdi(c)∣≤∣y−c∣<r|\mathrm{sd}_i(c)| \le |y - c| < r, against ∣sdi(c)∣=r|\mathrm{sd}_i(c)| = r. □\square

Lemma 5 (tangency). At pip_i, the sphere Σ(σ)\Sigma(\sigma), the envelope EE and the surface SiS_i have the same tangent plane, the plane through pip_i normal to ni(pi)n_i(p_i).

Proof. The normal of the sphere at pip_i is (pi−c)/r=−sini(pi)(p_i - c)/r = -s_i n_i(p_i) by Lemma 3, which is parallel to the normal of SiS_i. The sphere touches EE along K(σ)K(\sigma), which contains pip_i: at a regular point of the envelope, the envelope and the sphere through it have the same tangent plane, because ∇xG(x,σ)=2(x−c)\nabla_x G(x, \sigma) = 2(x - c) is normal to both. So all three normals are parallel. □\square

Theorem. Let the spine points computed at lines L1 to L7 be exact points c(σ0),c(σ1),…c(\sigma_0), c(\sigma_1), \ldots of a regular spine with n1∦n2n_1 \nparallel n_2. Then for each one, the points p1p_1 and p2p_2 of line L9 are the points where the ball of radius rr around cc touches S1S_1 and S2S_2, the arc of line L10 lies on the characteristic circle K(σj)K(\sigma_j) and hence on the envelope of the rolling ball, and the envelope meets each SiS_i at pip_i with the same tangent plane. So the blend is a G1G^1 blending surface along the trimlines σ↦p1(σ)\sigma \mapsto p_1(\sigma) and σ↦p2(σ)\sigma \mapsto p_2(\sigma), and the ball does not cut either surface near the contact.

Proof. Line L9 computes pi=c−sirni(c)p_i = c - s_i r n_i(c), which by Lemma 3 lies on SiS_i and on K(σj)K(\sigma_j). The arc of line L10 is a great circle arc of radius rr around cc from p1p_1 to p2p_2. The great circle through two points of a sphere that are not antipodal is unique, and K(σj)K(\sigma_j) is a great circle through p1p_1 and p2p_2 by Lemmas 2 and 3. The points are not antipodal: p1−cp_1 - c and p2−cp_2 - c are −s1rn1-s_1 r n_1 and −s2rn2-s_2 r n_2, which are not opposite because n1∦n2n_1 \nparallel n_2. So the arc lies on K(σj)K(\sigma_j), and by Lemma 2 on EE. Tangency is Lemma 5, and the last claim is Lemma 4. ■\blacksquare

What is not claimed. The curvature of the blend across a trimline is 1/r1/r in the direction of the arc, while the curvature of SiS_i in that direction is in general different, for example 00 for a plane. So the join is not G2G^2 in general. The theorem is about exact spine points. The computed points satisfy the two equations only within the Newton tolerance, and the trace can leave the branch it started on if the step hh is long compared with the distance to another branch.

Complexity

The costs are in the real RAM with square roots, counted per spine point. Line L4 costs O(1)O(1), CORRECT costs O(1)O(1) per Newton iteration, which gives O(i)O(i) per step with ii iterations, and lines L9 and L10 cost O(k)O(k) for kk arc points. In all the time is O(m(i+k))O(m(i + k)) and the space O(mk)O(mk) for mm spine points. Near a regular spine point Newton converges quadratically, so ii is a small constant once hh is small. The number of spine points is the length of the spine divided by hh.

Properties

  • G1G^1, not G2G^2. The blend has the tangent plane of each surface along the trimline. The normal curvature across the trimline jumps, for example from 00 on a plane to 1/r1/r on the blend.
  • Circular cross sections. Each cross section is an arc of radius rr in the normal plane of the spine. The blend is a canal surface, the envelope of a one-parameter family of spheres.
  • Exact for simple pairs. Two planes give a cylinder, a plane and a cylinder perpendicular to it give a torus, two parallel cylinders give a cylinder. CAD systems store these cases in closed form.
  • Rational only in special cases. The spine is an intersection of offsets, which are not rational in general, so the blend of two NURBS surfaces is approximated.

Variants and improvements

  • Variable radius. The radius r(σ)r(\sigma) changes along the edge. The characteristic circle then lies in a plane that is no longer normal to the spine, given by (x−c)⋅c′+rr′=0(x - c) \cdot c' + r r' = 0, and the contact points come from offsets at varying distance.
  • Parametric surfaces. For NURBS surfaces there is no exact distance function. Choi and Ju solve for a center cc and two parameter points (u1,v1)(u_1, v_1) and (u2,v2)(u_2, v_2) with c=S1(u1,v1)+s1rN1=S2(u2,v2)+s2rN2c = S_1(u_1, v_1) + s_1 r N_1 = S_2(u_2, v_2) + s_2 r N_2, and march along the solution curve.
  • Spine-based and trimline-based blends. Other cross sections, such as conics or Hermite cubics, give more control of the shape and can reach G2G^2; Vida, Martin and Várady compare the classes.
  • Solid offsetting. Rounding and filleting a whole solid with one radius is (S↓r)↑r(S \downarrow r) \uparrow r or (S↑r)↓r(S \uparrow r) \downarrow r (solid offsetting, Rossignac and Requicha offsetting). Near an edge, the faces of the result are rolling-ball surfaces.

When to use it

Use the rolling-ball blend for constant or variable radius fillets and rounds on mechanical parts, where the radius is a design or manufacturing value: a ball-end cutter of radius rr leaves a rolling-ball fillet in a concave corner. Use a spine-based or trimline-based blend when the shape of the cross section matters more than a constant radius, for example for G2G^2 transitions on visible surfaces. For many edges at once on a whole solid, offsetting the solid gives all the fillets without a separate trace for each edge.

Pitfalls

  • A radius larger than the space. If the ball does not fit, for example a fillet of radius rr in a slot narrower than 2r2r, the offsets do not meet where expected, and the spine runs into another face. The blend then intersects other faces of the solid and the operation must fail or be merged.
  • Parallel normals. Where the two surfaces are tangent, n1×n2=0n_1 \times n_2 = 0 and the spine has no tangent. The Newton step is undefined there. The implementation raises an error, and real systems end the blend before such points.
  • Concave surfaces. On a surface whose radius of curvature on the ball side is smaller than rr, the offset folds over, and the foot point at line L9 is not the nearest point. The ball then cuts the surface.
  • Branch jumps. A long step at line L5 can land on another branch of the intersection of the offsets, for example the spine on the other side of the shaft. Keep hh small relative to the radius of curvature of the spine.
  • Corners. Where three rounded edges meet, the three blends leave a hole at the vertex, which needs a separate vertex surface.

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.

rolling_ball_blend.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rolling-ball-blend/. The authors are listed in prov/DRVDD3.jsonl.

"""Constant-radius rolling-ball blend of two surfaces, in floating point.

Each surface is given by a signed distance function sd(x), which is exact
near the surface, and its gradient, the unit normal. Planes and circular
cylinders are provided. The side of the ball is chosen by a sign s = +1 or
-1 for each surface: the ball center c satisfies sd_i(c) = s_i r.

The method follows the page: the spine (the path of the ball center) is
the intersection of the two offset surfaces sd_i = s_i r, traced by steps
along the cross product of the normals with a Newton correction. At each
spine point the contact points are the feet of the center on the two
surfaces, and the cross section is the shorter circular arc between them
around the center.
"""

import math

Vec = tuple


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))


def unit(a: Vec) -> Vec:
    return scale(1.0 / norm(a), a)


class Plane:
    """The plane n . x = d with the positive side along the normal n."""

    def __init__(self, n: Vec, d: float):
        length = norm(n)
        self.n = scale(1.0 / length, n)
        self.d = d / length

    def sd(self, x: Vec) -> float:
        return dot(self.n, x) - self.d

    def normal(self, x: Vec) -> Vec:
        return self.n


class Cylinder:
    """The circular cylinder of radius R around the line a + t u, positive outside."""

    def __init__(self, a: Vec, u: Vec, R: float):
        self.a = a
        self.u = unit(u)
        self.R = R

    def radial(self, x: Vec) -> Vec:
        w = sub(x, self.a)
        return sub(w, scale(dot(w, self.u), self.u))

    def sd(self, x: Vec) -> float:
        return norm(self.radial(x)) - self.R

    def normal(self, x: Vec) -> Vec:
        return unit(self.radial(x))


def foot(surface, x: Vec) -> Vec:
    """The nearest point of the surface to x, valid where sd is a true distance."""
    return sub(x, scale(surface.sd(x), surface.normal(x)))


def correct(s1, s2, r: float, sides: tuple, x: Vec, tol: float = 1e-13, iters: int = 40) -> Vec:
    """Newton iteration with the minimum-norm step onto sd1 = s1 r and sd2 = s2 r."""
    for _ in range(iters):
        f1 = s1.sd(x) - sides[0] * r
        f2 = s2.sd(x) - sides[1] * r
        if abs(f1) <= tol and abs(f2) <= tol:
            return x
        g1, g2 = s1.normal(x), s2.normal(x)
        a, b, c = dot(g1, g1), dot(g1, g2), dot(g2, g2)
        det = a * c - b * b
        if det < 1e-14:
            raise ValueError("the normals are parallel, the spine is not regular here")
        l1 = (c * f1 - b * f2) / det
        l2 = (a * f2 - b * f1) / det
        x = sub(x, add(scale(l1, g1), scale(l2, g2)))
    raise ValueError("Newton correction did not converge")


def tangent(s1, s2, c: Vec, prev):
    """The unit vector along n1 x n2 at c, with the sign of the previous tangent."""
    t = cross(s1.normal(c), s2.normal(c))
    if norm(t) < 1e-7:
        raise ValueError("the normals are parallel, the spine has no tangent here")
    t = unit(t)
    if prev is not None and dot(t, prev) < 0:
        t = scale(-1.0, t)
    return t


def shorter_arc(c: Vec, p1: Vec, p2: Vec, r: float, k: int) -> list:
    """k + 1 points of the shorter great circle arc from p1 to p2 around c."""
    a = scale(1.0 / r, sub(p1, c))
    b = scale(1.0 / r, sub(p2, c))
    theta = math.acos(max(-1.0, min(1.0, dot(a, b))))
    arc = []
    for j in range(k + 1):
        lam = j / k
        if theta < 1e-12:
            w = a
        else:
            w = add(scale(math.sin((1 - lam) * theta), a), scale(math.sin(lam * theta), b))
            w = scale(1.0 / math.sin(theta), w)
        arc.append(add(c, scale(r, w)))
    return arc


def rolling_ball_blend(s1, s2, r: float, sides: tuple, start: Vec, h: float, max_steps: int, k: int = 8):
    """Return (spine, sections, closed); each section is (p1, p2, arc points)."""
    c = correct(s1, s2, r, sides, start)  # @line L1
    spine = [c]  # @line L2
    prev, left, closed = None, False, False
    for _ in range(max_steps):  # @line L3
        t = tangent(s1, s2, c, prev)  # @line L4
        c = correct(s1, s2, r, sides, add(c, scale(h, t)))  # @line L5
        gap = norm(sub(c, spine[0]))
        left = left or gap > 2 * h
        if left and gap <= 1.5 * h:  # @line L7
            closed = True
            break
        spine.append(c)  # @line L6
        prev = t
    sections = []
    for c in spine:  # @line L8
        p1 = sub(c, scale(sides[0] * r, s1.normal(c)))  # @line L9
        p2 = sub(c, scale(sides[1] * r, s2.normal(c)))
        arc = shorter_arc(c, p1, p2, r, k)  # @line L10
        sections.append((p1, p2, arc))  # @line L11
    return spine, sections, closed  # @line L12
test_rolling_ball_blend.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rolling-ball-blend/. The authors are listed in prov/DRVDD3.jsonl.

import math
import random
import unittest
from fractions import Fraction

from rolling_ball_blend import Cylinder, Plane, cross, dot, norm, rolling_ball_blend, scale, sub, unit

F = Fraction
TOL = 1e-9


def solve3(rows, rhs):
    """Exact Cramer's rule for a 3 by 3 system with Fraction entries."""

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

    d = det(rows)
    out = []
    for j in range(3):
        m = [[rhs[i] if c == j else rows[i][c] for c in range(3)] for i in range(3)]
        out.append(det(m) / d)
    return out


def plane_plane_spine(n1, d1, s1, n2, d2, s2, r, t, along):
    """Closed form: the point c with n_i . c = d_i + s_i r and t . c = along, exactly."""
    return solve3([list(n1), list(n2), list(t)], [d1 + s1 * r, d2 + s2 * r, along])


class Checks:
    def check_sections(self, s1, s2, r, sides, spine, sections):
        for c, (p1, p2, arc) in zip(spine, sections):
            self.assertAlmostEqual(s1.sd(c), sides[0] * r, delta=1e-12)
            self.assertAlmostEqual(s2.sd(c), sides[1] * r, delta=1e-12)
            t = unit(cross(s1.normal(c), s2.normal(c)))
            for surface, p, s in ((s1, p1, sides[0]), (s2, p2, sides[1])):
                self.assertLess(abs(surface.sd(p)), TOL)  # the contact is on the surface
                g = scale(1.0 / r, sub(c, p))
                n = scale(s, surface.normal(p))
                self.assertLess(norm(sub(g, n)), TOL)  # the same tangent plane, G1
            total = math.acos(max(-1.0, min(1.0, dot(sub(p1, c), sub(p2, c)) / r ** 2)))
            self.assertLess(total, math.pi)  # the shorter arc
            for x in arc:
                self.assertAlmostEqual(norm(sub(x, c)), r, delta=TOL)
                self.assertLess(abs(dot(sub(x, c), t)), TOL)  # in the normal plane of the spine
                a1 = math.acos(max(-1.0, min(1.0, dot(sub(x, c), sub(p1, c)) / r ** 2)))
                a2 = math.acos(max(-1.0, min(1.0, dot(sub(x, c), sub(p2, c)) / r ** 2)))
                self.assertAlmostEqual(a1 + a2, total, delta=1e-7)


class TestRollingBallBlend(unittest.TestCase, Checks):
    def test_two_planes_against_closed_form(self):
        r = F(1, 2)
        n1, d1 = (F(0), F(0), F(1)), F(0)
        n2, d2 = (F(3, 5), F(0), F(-4, 5)), F(0)
        p1 = Plane(tuple(map(float, n1)), float(d1))
        p2 = Plane(tuple(map(float, n2)), float(d2))
        spine, sections, closed = rolling_ball_blend(p1, p2, float(r), (1, 1), (2.0, 0.0, 1.0), 0.1, 30)
        self.assertFalse(closed)
        t = (F(0), F(1), F(0))
        for c in spine:
            exact = plane_plane_spine(n1, d1, 1, n2, d2, 1, r, t, F(c[1]))
            self.assertLess(norm(sub(c, tuple(map(float, exact)))), 1e-12)
            self.assertEqual(exact[0], F(3, 2))
            self.assertEqual(exact[2], F(1, 2))
        self.check_sections(p1, p2, float(r), (1, 1), spine, sections)
        q1, q2, _ = sections[0]
        self.assertAlmostEqual(q2[0], 1.2, delta=1e-12)
        self.assertAlmostEqual(q2[2], 0.9, delta=1e-12)

    def test_round_of_a_convex_edge(self):
        # Solid x >= 0, y >= 0 with outward normals (-1, 0, 0) and (0, -1, 0); the ball is inside.
        r = 0.25
        a, b = Plane((-1, 0, 0), 0.0), Plane((0, -1, 0), 0.0)
        spine, sections, _ = rolling_ball_blend(a, b, r, (-1, -1), (0.3, 0.2, 0.0), 0.05, 20)
        for c, (p1, p2, arc) in zip(spine, sections):
            self.assertAlmostEqual(c[0], r, delta=1e-12)
            self.assertAlmostEqual(c[1], r, delta=1e-12)
            for x in arc:
                self.assertLessEqual(x[0], r + 1e-12)
                self.assertLessEqual(x[1], r + 1e-12)
        self.check_sections(a, b, r, (-1, -1), spine, sections)

    def test_random_plane_pairs(self):
        rng = random.Random(7)
        triples = [(3, 4, 5), (5, 12, 13), (8, 15, 17), (7, 24, 25), (20, 21, 29)]
        for _ in range(40):
            p, q, h = rng.choice(triples)
            ang = rng.choice([(p, q), (q, p), (-p, q), (p, -q)])
            n1 = (F(0), F(0), F(1))
            n2 = (F(ang[0], h), F(0), F(ang[1], h))
            if abs(n2[2]) == 1 or n2[0] == 0:
                continue
            d1, d2 = F(rng.randint(-3, 3), 2), F(rng.randint(-3, 3), 2)
            r = F(rng.randint(1, 4), 4)
            sides = (rng.choice((1, -1)), rng.choice((1, -1)))
            t = (F(0), F(1), F(0))
            exact = plane_plane_spine(n1, d1, sides[0], n2, d2, sides[1], r, t, F(0))
            start = tuple(float(v) + rng.uniform(-0.2, 0.2) for v in exact)
            pl1 = Plane(tuple(map(float, n1)), float(d1))
            pl2 = Plane(tuple(map(float, n2)), float(d2))
            spine, sections, _ = rolling_ball_blend(pl1, pl2, float(r), sides, start, 0.1, 10)
            for c in spine:
                e = plane_plane_spine(n1, d1, sides[0], n2, d2, sides[1], r, t, F(c[1]))
                self.assertLess(norm(sub(c, tuple(map(float, e)))), 1e-11)
            self.check_sections(pl1, pl2, float(r), sides, spine, sections)

    def test_plane_and_cylinder_gives_a_torus(self):
        R, r = 1.0, 0.5
        floor = Plane((0, 0, 1), 0.0)
        shaft = Cylinder((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), R)
        spine, sections, closed = rolling_ball_blend(floor, shaft, r, (1, 1), (1.7, 0.1, 0.6), 0.05, 1000)
        self.assertTrue(closed)
        self.assertAlmostEqual(len(spine) * 0.05, 2 * math.pi * (R + r), delta=0.1)
        for c in spine:
            self.assertAlmostEqual(math.hypot(c[0], c[1]), R + r, delta=1e-12)
            self.assertAlmostEqual(c[2], r, delta=1e-12)
        for _, _, arc in sections:
            for x in arc:
                rho = math.hypot(x[0], x[1])
                self.assertAlmostEqual((rho - (R + r)) ** 2 + (x[2] - r) ** 2, r * r, delta=1e-9)
                self.assertLessEqual(rho, R + r + 1e-12)  # the quarter of the tube in the corner
                self.assertLessEqual(x[2], r + 1e-12)
        self.check_sections(floor, shaft, r, (1, 1), spine, sections)

        # Brute force: sample the two faces densely; no sample is closer than r to a ball center.
        samples = []
        for i in range(90):
            th = 2 * math.pi * i / 90
            for j in range(15):
                z = 0.1 * j
                samples.append((R * math.cos(th), R * math.sin(th), z))
                rho = R + 0.1 * j
                samples.append((rho * math.cos(th), rho * math.sin(th), 0.0))
        for c in spine[::10]:
            dmin = min(norm(sub(c, s)) for s in samples)
            self.assertGreaterEqual(dmin, r - 1e-12)
            self.assertLess(dmin, r + 0.05)

        # Brute force envelope test: no arc point lies inside the ball at another spine point.
        for _, _, arc in sections[::7]:
            for x in arc:
                self.assertGreaterEqual(min(norm(sub(x, c)) for c in spine), r - 1e-9)

    def test_two_parallel_cylinders(self):
        r = 0.5
        big = Cylinder((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 1.0)
        small = Cylinder((1.2, 0.0, 0.0), (0.0, 0.0, 1.0), 0.5)
        # Closed form: the center is at distance 1.5 from the first axis and 1.0 from the second.
        d, ra, rb = 1.2, 1.5, 1.0
        x0 = (d * d + ra * ra - rb * rb) / (2 * d)
        y0 = math.sqrt(ra * ra - x0 * x0)
        for sign in (1, -1):
            spine, sections, closed = rolling_ball_blend(big, small, r, (1, 1), (1.0, sign * 1.2, 0.0), 0.1, 15)
            self.assertFalse(closed)
            for c in spine:
                self.assertAlmostEqual(c[0], x0, delta=1e-12)
                self.assertAlmostEqual(c[1], sign * y0, delta=1e-12)
            self.check_sections(big, small, r, (1, 1), spine, sections)
            for _, _, arc in sections:
                for x in arc:
                    self.assertGreaterEqual(big.sd(x), -1e-12)
                    self.assertGreaterEqual(small.sd(x), -1e-12)

    def test_parallel_planes_are_rejected(self):
        a, b = Plane((0, 0, 1), 0.0), Plane((0, 0, 1), 1.0)
        with self.assertRaises(ValueError):
            rolling_ball_blend(a, b, 0.5, (1, -1), (0.0, 0.0, 0.5), 0.1, 5)


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

History

Rossignac and Requicha's 1986 paper on offsetting obtained constant-radius rounding and filleting of whole solids as compositions of offsets. Choi and Ju published in 1989 the construction for parametric surfaces from the intersection of offset surfaces, and Vida, Martin and Várady's survey of 1994 put rolling-ball blends beside the spine-based and trimline-based methods.

References

  1. Byoung K. Choi and Suk Y. Ju, Constant-radius blending in surface modelling, Computer-Aided Design 21(4), 213 to 220, 1989, the whole paper (the spine as the intersection of offset surfaces, the contact points and the circular cross sections)
  2. Janos Vida, Ralph R. Martin and Tamas Varady, A survey of blending methods that use parametric surfaces, Computer-Aided Design 26(5), 341 to 365, 1994, the section on rolling-ball blends and their variable-radius forms, and the comparison with spine-based and trimline-based methods
  3. Jaroslaw R. Rossignac and Aristides A. G. Requicha, Offsetting operations in solid modelling, Computer Aided Geometric Design 3(2), 129 to 148, 1986, constant-radius rounding and filleting of solids as compositions of offsets, whose faces near an edge are rolling-ball surfaces
  4. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 11, Offset curves and surfaces (the offset surfaces whose intersection is the spine), and Section 5.8, Surface/surface intersections

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example