Algorithm Search⌘K

Algorithmadvanced

Pencil-cut clean-up machining

Also called pencil curve machining, clean-up toolpath.

Traces the curves along concave corners where a ball end tool touches two surfaces at once, to remove material left by larger tools, as Choi and Jerard describe.

Time
O(m k) worst
Space
O(1) extra
Where
k = number of corrector steps per point; m = number of traced points
Properties
deterministiciterative
Origin
Byoung K. Choi, Robert B. Jerard, 1998

Pencil-cut machining is a finishing pass that runs a small ball end mill along the concave corners of a part, where two surfaces meet in a valley or a sharp inside edge. A larger tool used before cannot reach into such corners, so it leaves a strip of material there. The pencil path is the curve along which the ball touches both surfaces at once. Its ball centers are the points at the distance rr from both surfaces, which is the intersection of the two offset surfaces at the distance rr. The algorithm here traces that intersection with a predictor step along the tangent and a Newton corrector. For two planes the curve is a straight line parallel to the edge at the distance r/sin⁡(α/2)r/\sin(\alpha/2), where α\alpha is the opening angle, and the tracer follows it exactly.

In plain words

A big round cutter cannot get into an inside corner. It always leaves a little rib of material in the corner, like dust in the corner of a room that a broom cannot reach.

The clean-up pass uses a smaller round cutter and pushes it into the corner as far as it goes, so that it touches both walls. Then it slides the cutter along the corner, always touching both walls. The line that the center of the cutter follows is the pencil line, because it looks like a pencil stroke drawn along the corner.

To find the line on curved walls, the computer takes a small step along the corner, and then pulls the cutter back until it touches both walls again.

The problem

Two surfaces S1S_1 and S2S_2 meet along a concave edge, or come close in a valley, and the free side is where both signed distances are positive. For a ball end mill of radius rr, let gi(x)g_i(x) be the signed distance from xx to SiS_i minus rr. The ball with center xx touches SiS_i from the free side when gi(x)=0g_i(x) = 0. The pencil curve is

{ x:g1(x)=0, g2(x)=0 },\{\, x : g_1(x) = 0,\ g_2(x) = 0 \,\},

the curve of ball centers that touch both surfaces. The task is to compute it as a sequence of cutter locations, with the contact points x−rn1x - r n_1 and x−rn2x - r n_2, where nin_i is the unit normal of SiS_i at the contact. Pencil curves are needed only where the edge is sharper than the ball, that is where the corner fillet has a radius smaller than rr. Elsewhere the ball touches one surface at a time.

The algorithm

  1. PENCIL-TRACE(g₁, ∇g₁, g₂, ∇g₂, x₀, h, m)
  2. 1x ← CORRECT(x₀) ▷ the nearest point with g₁ = g₂ = 0
  3. 2path ← [x]
  4. 3repeat m times
  5. 4t ← ∇g₁(x) × ∇g₂(x), normalized and turned to agree with the last t
  6. 5y ← x + h t ▷ predictor along the tangent of the curve
  7. 6x ← CORRECT(y) ▷ Newton steps back onto the curve
  8. 7append x to path
  9. 8return path

CORRECT repeats the step x←x−JT(JJT)−1g(x)x \leftarrow x - J^{\mathsf T}(J J^{\mathsf T})^{-1} g(x), where g=(g1,g2)g = (g_1, g_2) and JJ has the rows ∇g1\nabla g_1 and ∇g2\nabla g_2, until ∣g∣|g| is below a tolerance. It is the smallest move that solves the linearized equations. The tangent of the curve is orthogonal to both gradients, so it is their cross product. The contact points are x−r∇gi(x)x - r\nabla g_i(x), since the gradient of a signed distance is the unit normal.

Example

The floor is z=0z = 0 with n1=(0,0,1)n_1 = (0, 0, 1). A wall leans out from the line x=10x = 10, z=0z = 0, with the normal n2=(−4,0,3)/5n_2 = (-4, 0, 3)/5, so the free side of the wall is x≤10+0.75zx \le 10 + 0.75 z. The ball has r=5r = 5.

quantity value
n1⋅n2n_1 \cdot n_2 3/53/5
opening angle α\alpha arccos⁡(−3/5)=126.87°\arccos(-3/5) = 126.87°
r(n1+n2)/(1+n1⋅n2)r(n_1 + n_2)/(1 + n_1 \cdot n_2) 5⋅(−4/5,0,8/5)/(8/5)=(−2.5,0,5)5 \cdot (-4/5, 0, 8/5)/(8/5) = (-2.5, 0, 5)
pencil line (7.5,y,5)(7.5, y, 5) for all yy
distance from the edge 2.52+52=5.590=5/sin⁡63.43°\sqrt{2.5^2 + 5^2} = 5.590 = 5/\sin 63.43°
contact with the floor (7.5,y,0)(7.5, y, 0)
contact with the wall (7.5,y,5)−5(−0.8,0,0.6)=(11.5,y,2)(7.5, y, 5) - 5(-0.8, 0, 0.6) = (11.5, y, 2)

The wall contact is on the wall, since 10+0.75⋅2=11.510 + 0.75 \cdot 2 = 11.5. Started at the origin, the tracer reaches (7.5,0,5)(7.5, 0, 5) in one corrector step and then moves along yy. For a vertical wall, n2=(−1,0,0)n_2 = (-1, 0, 0), the line is at (10−r,y,r)(10 - r, y, r), at the distance r2r\sqrt 2 from the edge.

On a floor and a concave cylinder wall of radius ρ=20\rho = 20 with r=3r = 3, the traced pencil curve is the circle of radius ρ−r=17\rho - r = 17 at the height 3, to within 10−910^{-9}, and with the step h=0.05h = 0.05 it goes once round in 2136 steps.

Correctness

Theorem. For two planes with unit normals n1≠±n2n_1 \ne \pm n_2 pointing into the free wedge, the centers of the balls of radius rr that lie in the wedge and touch both planes form the line

p+r1+n1⋅n2(n1+n2)+t (n1×n2),t∈R,p + \frac{r}{1 + n_1 \cdot n_2}(n_1 + n_2) + t\,(n_1 \times n_2), \qquad t \in \mathbb{R},

where pp is a point of the edge. The line is parallel to the edge at the distance r/sin⁡(α/2)r/\sin(\alpha/2), the contacts are c−rn1c - r n_1 and c−rn2c - r n_2, and no ball in the wedge has its center closer to the edge.

The proof is in the proof file. A ball lies on the free side of a plane and touches it exactly when its center is at the distance rr, so the centers solve two independent linear equations, and the given point solves them because ni⋅(n1+n2)=1+n1⋅n2n_i \cdot (n_1 + n_2) = 1 + n_1 \cdot n_2. The distance follows from ∣n1+n2∣2=2(1+n1⋅n2)=4sin⁡2(α/2)|n_1 + n_2|^2 = 2(1 + n_1 \cdot n_2) = 4\sin^2(\alpha/2). For two planes the corrector is exact after one step, since the equations are linear, and the predictor moves along the line. So every traced point is on the closed-form line. The tests check this in exact rational arithmetic, with normals such as (1,2,2)/3(1, 2, 2)/3 and (2,3,6)/7(2, 3, 6)/7, together with the contacts, the squared distance 2r2/(1+n1⋅n2)2r^2/(1 + n_1 \cdot n_2), and a brute force search that finds no admissible center closer to the edge.

For curved surfaces the result is local: Newton's method converges near the curve where the gradients are independent. The tracer does not check the ball against other parts of the model.

Proof: For a ball touching two planes the pencil path is a line parallel to the edge at the distance r over sin of half the opening angle, and the tracer follows it exactlyfull

Setting. Two planes Pi={x:ni⋅x=di}P_i = \{x : n_i \cdot x = d_i\}, i=1,2i = 1, 2, have unit normals n1,n2n_1, n_2 that are not parallel, so e=n1×n2≠0e = n_1 \times n_2 \ne 0. The free region, where the tool may be, is the wedge W={x:n1⋅x≥d1, n2⋅x≥d2}W = \{x : n_1 \cdot x \ge d_1,\ n_2 \cdot x \ge d_2\}, so the normals point into the free side, and the edge E=P1∩P2E = P_1 \cap P_2 is a concave edge of the part. The opening angle α∈(0°,180°)\alpha \in (0°, 180°) of the wedge satisfies cos⁡α=−n1⋅n2\cos\alpha = -n_1 \cdot n_2. The tool is a ball of radius r>0r > 0. The offset functions of the code are gi(x)=ni⋅x−di−rg_i(x) = n_i \cdot x - d_i - r.

Lemma 1. The closed ball B(c,r)B(c, r) lies in the half-space ni⋅x≥din_i \cdot x \ge d_i if and only if ni⋅c−di≥rn_i \cdot c - d_i \ge r. It lies in it and touches PiP_i if and only if ni⋅c−di=rn_i \cdot c - d_i = r, and then the only common point is c−rnic - r n_i.

Proof. The smallest value of ni⋅xn_i \cdot x on the ball is ni⋅c−rn_i \cdot c - r, taken only at x=c−rnix = c - r n_i, because ni⋅(x−c)≥−∣x−c∣≥−rn_i \cdot (x - c) \ge -|x - c| \ge -r with equality only when x−c=−rnix - c = -r n_i. □\square

Theorem. The centers cc of the balls that lie in WW and touch both planes form the line

ℓ={ p+r1+n1⋅n2(n1+n2)+t e  :  t∈R },\ell = \Big\{\, p + \frac{r}{1 + n_1 \cdot n_2}(n_1 + n_2) + t\, e \;:\; t \in \mathbb{R} \,\Big\},

where pp is any point of EE. The line is parallel to the edge, at the distance r/sin⁡(α/2)r/\sin(\alpha/2) from it, and the contact points are c−rn1∈P1c - r n_1 \in P_1 and c−rn2∈P2c - r n_2 \in P_2. Every center of a ball that lies in WW, whether it touches the planes or not, is at least as far from EE as ℓ\ell.

Proof. By Lemma 1 the centers are the solutions of the two linear equations ni⋅c=di+rn_i \cdot c = d_i + r. The normals are independent, so the solutions form a line whose direction is orthogonal to both, that is parallel to ee. Since n1≠−n2n_1 \ne -n_2, 1+n1⋅n2>01 + n_1 \cdot n_2 > 0. Let w=r(n1+n2)/(1+n1⋅n2)w = r(n_1 + n_2)/(1 + n_1 \cdot n_2). Then n1⋅w=r(1+n1⋅n2)/(1+n1⋅n2)=rn_1 \cdot w = r(1 + n_1 \cdot n_2)/(1 + n_1 \cdot n_2) = r, and in the same way n2⋅w=rn_2 \cdot w = r. So p+wp + w is a solution, which gives ℓ\ell. The edge EE is the line p+tep + t e, and ww is orthogonal to ee, so the distance from ℓ\ell to EE is ∣w∣|w|. Now ∣n1+n2∣2=2+2 n1⋅n2|n_1 + n_2|^2 = 2 + 2\, n_1 \cdot n_2, so

∣w∣2=2r21+n1⋅n2=2r21−cos⁡α=r2sin⁡2(α/2).|w|^2 = \frac{2r^2}{1 + n_1 \cdot n_2} = \frac{2r^2}{1 - \cos\alpha} = \frac{r^2}{\sin^2(\alpha/2)} .

The contacts come from Lemma 1. For the last claim, let xx be the center of a ball in WW, and write x=p+w+v+tex = p + w + v + t e with v⊥ev \perp e. By Lemma 1, ni⋅x−di≥rn_i \cdot x - d_i \ge r, so ni⋅v≥0n_i \cdot v \ge 0 for both ii. Then w⋅v=r(n1⋅v+n2⋅v)/(1+n1⋅n2)≥0w \cdot v = r(n_1 \cdot v + n_2 \cdot v)/(1 + n_1 \cdot n_2) \ge 0, and the squared distance from xx to EE is ∣w+v∣2=∣w∣2+2 w⋅v+∣v∣2≥∣w∣2|w + v|^2 = |w|^2 + 2\, w \cdot v + |v|^2 \ge |w|^2. □\square

So the pencil path for a concave edge between two planes is the straight line ℓ\ell, and its ball is the one that goes deepest into the corner. With the tip of the tool as the reference point, the path of a vertical tool is ℓ\ell moved down by rr.

The tracer on two planes. Line L1 and line L6 call the corrector. For linear g=(g1,g2)g = (g_1, g_2) with the matrix JJ of rows n1,n2n_1, n_2, one corrector step maps xx to x′=x−JT(JJT)−1g(x)x' = x - J^{\mathsf T}(J J^{\mathsf T})^{-1} g(x). The matrix JJTJ J^{\mathsf T} has the determinant 1−(n1⋅n2)2=∣e∣2>01 - (n_1 \cdot n_2)^2 = |e|^2 > 0, so it is invertible, and g(x′)=g(x)+J(x′−x)=g(x)−g(x)=0g(x') = g(x) + J(x' - x) = g(x) - g(x) = 0. So every point that the corrector returns is on ℓ\ell, after one step and with no error in exact arithmetic. Line L4 gives the tangent ∇g1×∇g2=e\nabla g_1 \times \nabla g_2 = e, so line L5 moves along ℓ\ell, and the corrector leaves the point unchanged. Successive points are hh apart along ℓ\ell, or h∣e∣h|e| apart when the tangent is not normalized. The tests check, in rational arithmetic with unit normals from Pythagorean quadruples, that every traced point is on the closed-form line at the squared distance 2r2/(1+n1⋅n2)2r^2/(1 + n_1 \cdot n_2) and that the contacts lie on the planes. A brute force search over random points checks that no admissible center is closer to the edge.

Curved surfaces. When the gig_i are signed distances to smooth surfaces with independent gradients along the curve, the pencil curve g1=g2=0g_1 = g_2 = 0 is a smooth curve by the implicit function theorem, and the corrector is a Newton method for an underdetermined system, which converges fast from a point close enough to it. This is a local statement. No global result is claimed: the tracer can jump to another branch with a long step, it stops where the gradients become parallel, and it does not check the ball against other surfaces. On a floor and a concave cylinder wall of radius ρ\rho, the pencil curve is the circle of radius ρ−r\rho - r at height rr, and the tests measure that the traced points stay on it to 10−910^{-9} and go once round.

Complexity

Each traced point costs one tangent and kk corrector steps, and each corrector step evaluates g1g_1, g2g_2 and their gradients and solves a 2×22 \times 2 system. With O(1)O(1) evaluation, mm points take O(mk)O(mk) time and O(1)O(1) extra space besides the path. For planes k=1k = 1. On a triangle mesh, the evaluation of the offset distances is the main cost, and practical systems use spatial search structures or the z-map of the offset surface.

Properties

  • Exact for planar corners. The pencil path of two planes is a straight line at a closed-form position.
  • Deepest reach. The pencil ball is the one that goes furthest into the corner. No ball in the corner is closer to the edge.
  • Two contacts. Along the path the tool touches both surfaces, so it cuts the rest material from both sides of the corner.
  • Local tracing. The tracer follows one branch of the curve from a start point. Finding the start points is a separate step.

Variants and improvements

  • Mesh-based detection. On triangle meshes, Park computed pencil curves from an offset mesh and the visibility of its intersections. Kim, Jun and Park found pencil points from scanning paths with two contacts and traced the pencil-cut path from them.
  • Bitangency angle. CAM systems mark a point as a pencil point when the two contact normals differ by more than a chosen angle. Small angles find shallow valleys too.
  • Multiple pencil passes. Parallel passes on both sides of the pencil curve, at offsets set by the scallop height, clean a wider band after the main pass.
  • Five-axis pencil cuts. Tilting the tool lets a longer tool reach deep corners and keeps the holder clear of the walls.
  • Corners in 2D. In pocket machining, the same formula gives the position of a tool touching both walls of a corner with angle α\alpha, at the distance r/sin⁡(α/2)r/\sin(\alpha/2) from the corner point.

When to use it

Use pencil cuts after roughing and finishing with a larger ball, on molds and dies with fillets and sharp inside edges. The pass is short and removes the material that the larger tool left in the corners, before the final finishing with a small tool or before a smaller pencil pass. Where the fillet radius is larger than the ball, no pencil curve exists there, and ordinary finishing reaches the corner.

Pitfalls

  • Global gouges. The tracer looks only at two surfaces. Near a third surface the ball can gouge, so the path must be checked by gouge detection.
  • Tangent surfaces. Where the two surfaces become tangent, the gradients are parallel, the pencil curve ends, and the corrector fails. The trace must stop there.
  • Branch jumps. A long step can land the predictor near another branch of the curve, and the corrector then follows the wrong corner. Keep hh small compared with the size of the features.
  • Full load in the corner. The pencil tool cuts on both sides of the corner at once, and the material left by the larger tool can be thick. Several passes with growing depth, or a lower feed, protect the tool.
  • Sign of the normals. The formula needs the normals that point into the free region. With one normal reversed the line lies inside the material.

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.

pencil_cut_machining.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pencil-cut-machining/. The authors are listed in prov/K6TS7H.jsonl.

"""Pencil-cut tracing: the path of a ball end mill that touches two surfaces at once.

Each surface is given by a function g(x) = (signed distance of x from the
surface, positive on the free side) - r and its gradient. A ball of radius r
with center x touches surface i exactly when g_i(x) = 0, so the pencil curve
of ball centers is the intersection of the two offset surfaces g_1 = 0 and
g_2 = 0. It is traced by a predictor along the tangent grad g_1 x grad g_2
and a Newton corrector that moves to the nearest point with g_1 = g_2 = 0
(the minimum norm step of the 2 x 3 linear system).

The code works with floats or with Fractions. With Fractions and planes the
corrector is exact; pass normalize=False to step along the raw tangent, so
that no square root is taken.
"""

import math


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


def cross(a, b):
    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 correct(g1, dg1, g2, dg2, x, tol=1e-12, max_iter=20):
    """Newton steps to a point with g1 = g2 = 0, each the minimum norm solution
    of the linearized system."""
    for _ in range(max_iter):
        v1, v2 = g1(x), g2(x)
        if abs(v1) <= tol and abs(v2) <= tol:
            return x
        a, b = dg1(x), dg2(x)
        aa, ab, bb = dot(a, a), dot(a, b), dot(b, b)
        det = aa * bb - ab * ab
        if det == 0:
            raise ValueError("the two surfaces are tangent here; the pencil curve is not defined")
        # solve [[aa, ab], [ab, bb]] (l1, l2) = (v1, v2), then x <- x - l1 a - l2 b
        l1 = (bb * v1 - ab * v2) / det
        l2 = (aa * v2 - ab * v1) / det
        x = tuple(x[i] - l1 * a[i] - l2 * b[i] for i in range(3))
    if abs(g1(x)) <= tol and abs(g2(x)) <= tol:
        return x
    raise ValueError("the corrector did not converge")


def pencil_trace(g1, dg1, g2, dg2, x0, h, m, tol=1e-12, normalize=True):
    """Trace m steps of length h of the pencil curve of ball centers from near x0."""
    x = correct(g1, dg1, g2, dg2, x0, tol)  # @line L1
    path = [x]  # @line L2
    prev = None
    for _ in range(m):  # @line L3
        t = cross(dg1(x), dg2(x))  # @line L4
        if prev is not None and dot(t, prev) < 0:
            t = (-t[0], -t[1], -t[2])
        prev = t
        if normalize:
            n = math.sqrt(dot(t, t))
            if n == 0:
                raise ValueError("the two surfaces are tangent here; the pencil curve is not defined")
            t = (t[0] / n, t[1] / n, t[2] / n)
        y = (x[0] + h * t[0], x[1] + h * t[1], x[2] + h * t[2])  # @line L5
        x = correct(g1, dg1, g2, dg2, y, tol)  # @line L6
        path.append(x)  # @line L7
    return path  # @line L8


def contacts(x, r, dg1, dg2, unit=True):
    """The two contact points x - r n_i, with n_i the unit normals (the gradients of
    signed distances are unit vectors already when unit is True)."""
    out = []
    for dg in (dg1, dg2):
        n = dg(x)
        if not unit:
            s = math.sqrt(dot(n, n))
            n = (n[0] / s, n[1] / s, n[2] / s)
        out.append((x[0] - r * n[0], x[1] - r * n[1], x[2] - r * n[2]))
    return out


def plane(n, d, r):
    """The offset function and gradient of the plane n . x = d, with unit normal n
    pointing to the free side, for a ball of radius r."""
    def g(x):
        return dot(n, x) - d - r

    def dg(x):
        return n

    return g, dg
test_pencil_cut_machining.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pencil-cut-machining/. The authors are listed in prov/K6TS7H.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

from pencil_cut_machining import contacts, cross, dot, pencil_trace, plane

# Rational unit vectors from Pythagorean quadruples a^2 + b^2 + c^2 = d^2.
QUADS = [(1, 2, 2, 3), (2, 3, 6, 7), (1, 4, 8, 9), (4, 4, 7, 9), (2, 6, 9, 11), (6, 6, 7, 11), (0, 3, 4, 5), (0, 0, 1, 1)]


def random_unit(rng):
    a, b, c, d = rng.choice(QUADS)
    v = [F(a, d), F(b, d), F(c, d)]
    rng.shuffle(v)
    return tuple(x if rng.random() < 0.5 else -x for x in v)


def det3(a, b, c):
    return dot(a, cross(b, c))


def closed_form(n1, d1, n2, d2, r):
    """The reference: a point of the edge line, by Cramer's rule, plus
    r (n1 + n2) / (1 + n1 . n2)."""
    e = cross(n1, n2)
    D = det3(n1, n2, e)
    rhs = (d1, d2, 0)
    cols = []
    for k in range(3):
        m = [list(n1), list(n2), list(e)]
        for i in range(3):
            m[i][k] = rhs[i]
        cols.append(det3(*m) / D)
    p = tuple(cols)
    s = r / (1 + dot(n1, n2))
    c = tuple(p[i] + s * (n1[i] + n2[i]) for i in range(3))
    return p, e, c


def dist2_to_line(x, p, e):
    w = tuple(x[i] - p[i] for i in range(3))
    return dot(w, w) - dot(w, e) ** 2 / dot(e, e)


def test_two_planes_exact_against_closed_form():
    rng = random.Random(3)
    done = 0
    while done < 60:
        n1, n2 = random_unit(rng), random_unit(rng)
        e = cross(n1, n2)
        if e == (0, 0, 0):
            continue
        d1, d2 = F(rng.randint(-20, 20), rng.randint(1, 5)), F(rng.randint(-20, 20), rng.randint(1, 5))
        r = F(rng.randint(1, 12), rng.randint(1, 4))
        g1, dg1 = plane(n1, d1, r)
        g2, dg2 = plane(n2, d2, r)
        p, e, c = closed_form(n1, d1, n2, d2, r)
        x0 = tuple(c[i] + F(rng.randint(-9, 9), 7) for i in range(3))
        path = pencil_trace(g1, dg1, g2, dg2, x0, F(1, 3), 5, tol=0, normalize=False)
        for k, x in enumerate(path):
            # the center is on the closed-form line
            assert cross(tuple(x[i] - c[i] for i in range(3)), e) == (0, 0, 0)
            # at the distance r / sin(alpha / 2) from the edge: squared, 2 r^2 / (1 + n1 . n2)
            assert dist2_to_line(x, p, e) == 2 * r * r / (1 + dot(n1, n2))
            # the ball touches both planes, at x - r n_i
            q1, q2 = contacts(x, r, dg1, dg2)
            assert dot(n1, q1) == d1 and dot(n2, q2) == d2
            if k:
                step = tuple(x[i] - path[k - 1][i] for i in range(3))
                assert step != (0, 0, 0) and cross(step, e) == (0, 0, 0)
        done += 1


def test_floor_and_leaning_wall_example():
    # floor z = 0, and a wall through the line x = 10, z = 0 with normal (-4, 0, 3)/5
    r = F(5)
    n1, d1 = (F(0), F(0), F(1)), F(0)
    n2 = (F(-4, 5), F(0), F(3, 5))
    d2 = dot(n2, (F(10), F(0), F(0)))
    g1, dg1 = plane(n1, d1, r)
    g2, dg2 = plane(n2, d2, r)
    path = pencil_trace(g1, dg1, g2, dg2, (F(0), F(0), F(0)), F(1), 3, tol=0, normalize=False)
    for x in path:
        assert (x[0], x[2]) == (F(15, 2), F(5))
        q1, q2 = contacts(x, r, dg1, dg2)
        assert (q1[0], q1[2]) == (F(15, 2), F(0)) and (q2[0], q2[2]) == (F(23, 2), F(2))
    ys = [x[1] for x in path]
    assert len(set(ys)) == len(ys)


def test_pencil_center_is_the_deepest_admissible_center():
    # brute force: every center at distance >= r from both planes (the ball fits
    # in the wedge) is at least r / sin(alpha / 2) from the edge
    rng = random.Random(8)
    for _ in range(20):
        n1, n2 = random_unit(rng), random_unit(rng)
        if cross(n1, n2) == (0, 0, 0):
            continue
        n1f, n2f = tuple(map(float, n1)), tuple(map(float, n2))
        r = rng.uniform(0.5, 4.0)
        g1, dg1 = plane(n1f, 0.0, r)
        g2, dg2 = plane(n2f, 0.0, r)
        path = pencil_trace(g1, dg1, g2, dg2, (1.0, 2.0, 3.0), 0.5, 2)
        e = cross(n1f, n2f)
        best = dist2_to_line(path[0], (0.0, 0.0, 0.0), e)
        half = math.acos(-dot(n1f, n2f)) / 2  # alpha / 2, alpha the opening angle
        assert math.isclose(math.sqrt(best), r / math.sin(half), rel_tol=1e-9)
        for _ in range(2000):
            x = tuple(rng.uniform(-20, 20) for _ in range(3))
            if dot(n1f, x) >= r and dot(n2f, x) >= r:
                assert dist2_to_line(x, (0.0, 0.0, 0.0), e) >= best * (1 - 1e-9)


def test_floor_and_cylinder_wall_gives_a_circle():
    rho, r = 20.0, 3.0

    def g1(x):
        return x[2] - r

    def dg1(x):
        return (0.0, 0.0, 1.0)

    def g2(x):
        return rho - math.hypot(x[0], x[1]) - r

    def dg2(x):
        q = math.hypot(x[0], x[1])
        return (-x[0] / q, -x[1] / q, 0.0)

    h = 0.05
    m = int(2 * math.pi * (rho - r) / h)
    path = pencil_trace(g1, dg1, g2, dg2, (rho - r + 0.3, 0.1, r + 0.2), h, m)
    for x in path:
        assert abs(x[2] - r) <= 1e-9
        assert abs(math.hypot(x[0], x[1]) - (rho - r)) <= 1e-9
        q1, q2 = contacts(x, r, dg1, dg2)
        assert abs(q1[2]) <= 1e-9 and abs(math.hypot(q2[0], q2[1]) - rho) <= 1e-9
    # the steps follow the circle, so the path goes once round
    turn = 0.0
    for a, b in zip(path, path[1:]):
        turn += math.atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1])
    assert abs(abs(turn) - m * h / (rho - r)) <= 1e-3
    assert abs(abs(turn) - 2 * math.pi) <= h / (rho - r)


def test_parallel_planes_have_no_pencil_curve():
    g1, dg1 = plane((0.0, 0.0, 1.0), 0.0, 1.0)
    g2, dg2 = plane((0.0, 0.0, -1.0), -10.0, 1.0)
    with pytest.raises(ValueError):
        pencil_trace(g1, dg1, g2, dg2, (0.0, 0.0, 5.0), 0.1, 3)

History

Clean-up machining of corners came with the CAM systems for sculptured surfaces in the 1990s. Choi and Jerard described pencil-cut paths in their 1998 book, as the path of a ball that touches two surfaces at once. In 2005 Park computed pencil curves from the visibility of intersections on an offset triangle mesh, and Kim, Jun and Park traced pencil-cut and fillet-cut paths on polyhedral models from points with two contacts. Commercial CAM systems offer pencil passes with a bitangency angle as the main setting.

References

  1. Byoung K. Choi and Robert B. Jerard, Sculptured Surface Machining, Theory and Applications, Kluwer Academic Publishers, 1998, the material on clean-up machining of concave corners and on offset surfaces of the part
  2. Sang C. Park, Pencil curve detection from visibility data, Computer-Aided Design 37(14), 1492-1498, 2005, the pencil curve as the path of the ball center sliding along a concave edge, and its computation from an offset triangle mesh
  3. D.-S. Kim, C.-S. Jun and S. C. Park, Tool path generation for clean-up machining by a curve-based approach, Computer-Aided Design 37(9), 967-973, 2005, the detection of pencil points from points with two contacts, and the tracing of pencil-cut and fillet-cut paths on polyhedral models

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