Algorithm Search⌘K

Algorithmcore

Contour-parallel toolpath

Also called offset toolpath, echo toolpath.

Covers a region with successive inward offsets of its boundary, computed by polygon offsetting or the Voronoi diagram, which keeps the cutting direction steady.

Time
O(K n^2) worst
Space
O(n) extra
Where
K = number of loops; n = number of edges of the convex pocket
Properties
deterministicexactiterative
Origin
Hans Persson, 1978

A contour-parallel toolpath clears a pocket with a milling tool by moving the tool center along nested offset curves of the pocket boundary, one loop at a time, from the wall inward. The first loop lies at the tool radius rr from the boundary, and each next loop lies one step-over ss further in. This is a manufacturing method of mechanical CAD: the words placement and routing here mean the placement of a cutter and the route it takes, not the placement and routing of an electronic circuit. The page proves that with s≤rs \le r the loops cut all of the material that any tool of radius rr can reach without leaving the pocket. The code builds the loops of a convex pocket with exact rational offsets.

In plain words

Think of a lawn with a fence around it. You mow one lap along the fence, then a lap a little further in, and so on to the middle. Each lap has the shape of the fence, only smaller.

The mower blade has a fixed width. If two laps are too far apart, a strip of grass stays between them. If each new lap is at most half a blade width inside the last one, then every blade of grass that the mower can reach is cut. Some grass in sharp corners can never be reached, because the round blade does not fit into the corner. No path can fix that.

The tool always turns the same way around the loops, so the cutting conditions stay steady. The hard part in a real pocket is to compute the smaller copies of the boundary when the shape is not convex.

The problem

The pocket is a closed bounded region PP of the plane. The tool is a disk DrD_r of radius rr, and the tool center follows a path Γ\Gamma. The tool removes the material in Γ⊕Dr\Gamma \oplus D_r, the Minkowski sum of the path and the disk. The tool must stay in the pocket, so every disk around a point of Γ\Gamma lies in PP.

The depth of a point pp is its distance to the outside of the pocket, δ(p)=dist⁡(p,R2∖P)\delta(p) = \operatorname{dist}(p, \mathbb{R}^2 \setminus P). The offset at distance dd is the set Pd={p∈P:δ(p)≥d}P_d = \{p \in P : \delta(p) \ge d\}, and its boundary ∂Pd\partial P_d is the offset curve. A disk of radius rr around cc lies in PP if and only if δ(c)≥r\delta(c) \ge r, so the tool centers that keep the tool in the pocket form exactly PrP_r. Hence no path can cut more than the morphological opening Or(P)=Pr⊕DrO_r(P) = P_r \oplus D_r. The parts of PP outside Or(P)O_r(P) are the corners that a round tool cannot reach.

For a convex polygon P={x:ni⋅x≤ci, i=1,…,n}P = \{x : n_i \cdot x \le c_i,\ i = 1, \dots, n\} with unit outward normals nin_i, the depth of a point p∈Pp \in P is δ(p)=min⁡i(ci−ni⋅p)\delta(p) = \min_i (c_i - n_i \cdot p), so the offset is the intersection of half-planes Pd={x:ni⋅x≤ci−d}P_d = \{x : n_i \cdot x \le c_i - d\}. If every edge has a rational length, every nin_i is rational and every offset has rational vertices.

The algorithm

  1. CONTOUR-PARALLEL(P, r, s)
  2. 1d ← r
  3. 2loop
  4. 3Q ← OFFSET(P, d) ▷ P_d: all points at depth at least d
  5. 4if Q is empty then exit the loop
  6. 5append the loop (d, ∂Q)
  7. 6d ← d + s
  8. 7link the loops in order and return the path

For a convex pocket, OFFSET clips PP by the nn half-planes moved inward by dd, with the Sutherland-Hodgman rule. Each clip computes the sign of ci−d−ni⋅vc_i - d - n_i \cdot v at each vertex vv with exact rationals, and a vertex with value zero is kept and not duplicated. A loop can be a polygon, a segment or a single point. A segment loop is cut out and back. A loop of zero area appears when PdP_d has no interior, for example at the center of a disk or along the middle line of a long rectangle.

For a pocket that is not convex, OFFSET is the hard part. Moving each edge inward and joining the moved edges gives a raw offset with local loops at reflex corners and global self-intersections where two far parts of the boundary meet. These must be trimmed, and the trimmed offset can split into several closed curves. Curve offsetting covers the trimming, and Voronoi pocket machining reads every offset directly from the medial axis. At a reflex vertex the true offset is a circular arc, not a corner.

Line L7 joins the loops. The tool moves from a point of one loop to a point of the next loop inward, along a short segment inside the offset region. When the offsets split into several curves, the loops form a tree, and the tool clears one branch to its end before it moves to the next branch. A move between branches that crosses material that is already cut is a rapid move or a retraction.

Example

Take the right triangle with vertices (0,0)(0, 0), (12,0)(12, 0) and (0,9)(0, 9), a tool of radius r=1r = 1 and a step-over s=1s = 1. The edges have lengths 12, 15 and 9, and the inward unit normals are (0,1)(0, 1), (−35,−45)(-\tfrac35, -\tfrac45) and (1,0)(1, 0). The inradius is 3, with the incenter at (3,3)(3, 3), and each offset is the triangle scaled toward the incenter by the factor (3−d)/3(3 - d)/3.

step dd loop ∂Pd\partial P_d length
L3 to L5 1 (1,1)(1, 1), (9,1)(9, 1), (1,7)(1, 7) 24
L3 to L5 2 (2,2)(2, 2), (6,2)(6, 2), (2,5)(2, 5) 12
L3 to L5 3 the point (3,3)(3, 3) 0
L3, L4 4 empty, stop

The links (1,1)→(2,2)→(3,3)(1, 1) \to (2, 2) \to (3, 3) add 222\sqrt2, so the path has length 36+22≈38.8336 + 2\sqrt2 \approx 38.83. The triangle has area 54. The opening has area area⁡(P1)+r⋅perimeter⁡(P1)+πr2=24+24+π≈51.14\operatorname{area}(P_1) + r \cdot \operatorname{perimeter}(P_1) + \pi r^2 = 24 + 24 + \pi \approx 51.14, so 6−π≈2.866 - \pi \approx 2.86 of material stays in the three corners. No path with this tool can remove it.

With s=2s = 2 instead, the loops are at d=1d = 1 and d=3d = 3. The point (2.1,2.1)(2.1, 2.1) is in the opening, but its distance to the first loop is 1.11.1 and its distance to the point (3,3)(3, 3) is 0.92≈1.270.9\sqrt2 \approx 1.27. Both are more than rr, so a small island of material stays near the right-angle corner.

Correctness

Theorem. Let PP be a compact region, r>0r > 0 and 0<s≤r0 < s \le r, and let PrP_r be nonempty. CONTOUR-PARALLEL stops after a finite number of loops. Each disk of radius rr around a point of the path lies in PP, and the path cuts exactly the opening Or(P)O_r(P).

The proof rests on one fact about the depth: for δ(p)≥d\delta(p) \ge d, the distance from pp to the offset curve ∂Pd\partial P_d is exactly δ(p)−d\delta(p) - d. Walk from pp straight toward the nearest point outside PP. The depth drops at rate exactly 1 along this walk, so after δ(p)−d\delta(p) - d it equals dd, and that point is on ∂Pd\partial P_d. A point pp deep in the pocket lies between the loop at dkd_k and the loop at dk+sd_k + s, so its distance to the loop at dkd_k is less than s≤rs \le r. A point near the wall is within rr of a tool center c∈Prc \in P_r, and the segment from cc to pp crosses ∂Pr\partial P_r, the first loop, at a point within rr of pp. The full proof is in the proof file.

The condition s≤rs \le r is sufficient for every pocket. It is not necessary: the uncut islands come from the corners of the offsets, and a pocket with only gentle corners is covered with a larger step.

Proof: With a step-over of at most the tool radius, the contour-parallel loops cut exactly the opening of the pocketfull

Setting. P⊂R2P \subset \mathbb{R}^2 is compact, r>0r > 0 and 0<s≤r0 < s \le r. For x∈R2x \in \mathbb{R}^2 let δ(x)=dist⁡(x,R2∖P)\delta(x) = \operatorname{dist}(x, \mathbb{R}^2 \setminus P), so δ(x)=0\delta(x) = 0 for x∉Px \notin P. For d>0d > 0 let Pd={x:δ(x)≥d}P_d = \{x : \delta(x) \ge d\}. Let dk=r+ksd_k = r + ks. Assume Pr≠∅P_r \ne \emptyset, let KK be the largest kk with Pdk≠∅P_{d_k} \ne \emptyset, and let Γ=⋃k=0K∂Pdk\Gamma = \bigcup_{k=0}^{K} \partial P_{d_k} be the set of points visited by the loops. DrD_r is the closed disk of radius rr at the origin, and Or(P)=Pr⊕DrO_r(P) = P_r \oplus D_r.

Claim. (a) KK exists, so CONTOUR-PARALLEL stops after K+1K + 1 loops of lines L2 to L6. (b) For every c∈Γc \in \Gamma, c+Dr⊆Pc + D_r \subseteq P. (c) Γ⊕Dr=Or(P)\Gamma \oplus D_r = O_r(P). (d) If c+Dr⊆Pc + D_r \subseteq P, then c∈Prc \in P_r. So every path whose tool stays in PP cuts a subset of Or(P)O_r(P), and the loops cut all of it.

Step 1 (facts on δ\delta). δ\delta is the distance to a set, so ∣δ(x)−δ(y)∣≤∣x−y∣|\delta(x) - \delta(y)| \le |x - y| for all x,yx, y, and δ\delta is continuous. Each PdP_d with d>0d > 0 is closed, as the preimage of [d,∞)[d, \infty), and lies in PP. If x∈Pdx \in P_d is a limit of points not in PdP_d, then δ(x)≤d\delta(x) \le d by continuity, so δ(x)=d\delta(x) = d. Conversely, let δ(x)=d>0\delta(x) = d > 0. The set R2∖P\mathbb{R}^2 \setminus P is open and nonempty (PP is bounded), so its closure ZZ has a point bb with ∣x−b∣=d|x - b| = d. For 0≤t≤d0 \le t \le d let xt=x+t(b−x)/dx_t = x + t(b - x)/d. Then δ(xt)≤∣xt−b∣=d−t\delta(x_t) \le |x_t - b| = d - t, because dist⁡(⋅,R2∖P)=dist⁡(⋅,Z)\operatorname{dist}(\cdot, \mathbb{R}^2 \setminus P) = \operatorname{dist}(\cdot, Z). So the points xtx_t with t>0t > 0 are not in PdP_d, and xx is a limit of them. Hence ∂Pd={x:δ(x)=d}\partial P_d = \{x : \delta(x) = d\}.

Step 2 (the distance to an offset curve). Let δ(p)≥d>0\delta(p) \ge d > 0. Then some point q∈∂Pdq \in \partial P_d has ∣p−q∣=δ(p)−d|p - q| = \delta(p) - d. Proof. Write D=δ(p)D = \delta(p) and take b∈Zb \in Z with ∣p−b∣=D|p - b| = D as in Step 1. For pt=p+t(b−p)/Dp_t = p + t(b - p)/D, the bound δ(pt)≤D−t\delta(p_t) \le D - t holds as in Step 1, and the Lipschitz bound gives δ(pt)≥D−t\delta(p_t) \ge D - t. So δ(pt)=D−t\delta(p_t) = D - t. Take t=D−dt = D - d and q=ptq = p_t. Then δ(q)=d\delta(q) = d, so q∈∂Pdq \in \partial P_d by Step 1, and ∣p−q∣=D−d|p - q| = D - d. □\square

Step 3 (termination). δ\delta is continuous on the compact set PP and is 00 outside PP, so it has a maximum δmax⁡\delta_{\max}. Then Pd=∅P_d = \emptyset for d>δmax⁡d > \delta_{\max}. The value dd of line L6 grows by exactly s>0s > 0 in each loop, so after at most ⌊(δmax⁡−r)/s⌋+2\lfloor (\delta_{\max} - r)/s \rfloor + 2 tests of line L4 the offset is empty. The nonempty offsets are those with dk≤δmax⁡d_k \le \delta_{\max}, and they form an initial run k=0,…,Kk = 0, \dots, K because Pd⊇Pd′P_{d} \supseteq P_{d'} for d≤d′d \le d'. This proves (a).

Step 4 (the tool stays in the pocket). Let c∈Γc \in \Gamma. Then c∈∂Pdk⊆Pdk⊆Prc \in \partial P_{d_k} \subseteq P_{d_k} \subseteq P_r, so δ(c)≥r\delta(c) \ge r. If a point yy with ∣y−c∣<r|y - c| < r were outside PP, then δ(c)≤∣c−y∣<r\delta(c) \le |c - y| < r. So the open disk of radius rr around cc lies in PP, and the closed disk lies in PP because PP is closed. This proves (b). The same argument with c∈Prc \in P_r shows Pr⊕Dr⊆PP_r \oplus D_r \subseteq P.

Step 5 (maximality). Let c+Dr⊆Pc + D_r \subseteq P. Every point outside PP is outside the closed disk, at distance more than rr from cc, so δ(c)≥r\delta(c) \ge r and c∈Prc \in P_r. This proves (d).

Step 6 (coverage). Γ⊆Pr\Gamma \subseteq P_r gives Γ⊕Dr⊆Or(P)\Gamma \oplus D_r \subseteq O_r(P). For the other inclusion, let p∈Or(P)p \in O_r(P), so ∣p−c∣≤r|p - c| \le r for some c∈Prc \in P_r. We find a point of Γ\Gamma within rr of pp.

Case A: δ(p)≥r\delta(p) \ge r. Let kk be the largest index with dk≤δ(p)d_k \le \delta(p). Then p∈Pdkp \in P_{d_k}, so k≤Kk \le K, and δ(p)<dk+1\delta(p) < d_{k+1}: for k<Kk < K by the choice of kk, and for k=Kk = K because PdK+1=∅P_{d_{K+1}} = \emptyset. By Step 2 some q∈∂Pdk⊆Γq \in \partial P_{d_k} \subseteq \Gamma has ∣p−q∣=δ(p)−dk<dk+1−dk=s≤r|p - q| = \delta(p) - d_k < d_{k+1} - d_k = s \le r.

Case B: δ(p)<r\delta(p) < r. Let g(t)=δ(c+t(p−c))g(t) = \delta(c + t(p - c)) on [0,1][0, 1]. It is continuous, g(0)≥rg(0) \ge r and g(1)<rg(1) < r. Let t∗=sup⁡{t∈[0,1]:g(t)≥r}t^* = \sup\{t \in [0,1] : g(t) \ge r\}. Then g(t∗)≥rg(t^*) \ge r by continuity, so t∗<1t^* < 1, and g(t)<rg(t) < r for all t∈(t∗,1]t \in (t^*, 1]. So x∗=c+t∗(p−c)x^* = c + t^*(p - c) lies in PrP_r and is a limit of points not in PrP_r, so x∗∈∂Pr=∂Pd0⊆Γx^* \in \partial P_r = \partial P_{d_0} \subseteq \Gamma. And ∣p−x∗∣=(1−t∗)∣p−c∣≤r|p - x^*| = (1 - t^*)|p - c| \le r.

In both cases p∈Γ⊕Drp \in \Gamma \oplus D_r. This proves (c). ■\blacksquare

The convex offset used by the code. Let P=⋂i=1n{x:ni⋅x≤ci}P = \bigcap_{i=1}^{n} \{x : n_i \cdot x \le c_i\} with unit vectors nin_i. The complement of PP is the union of the open half-planes {x:ni⋅x>ci}\{x : n_i \cdot x > c_i\}. For p∈Pp \in P, the distance from pp to the ii-th open half-plane is ci−ni⋅pc_i - n_i \cdot p, and the distance to a union is the minimum of the distances. So δ(p)=min⁡i(ci−ni⋅p)\delta(p) = \min_i (c_i - n_i \cdot p) on PP, and Pd=⋂i{x:ni⋅x≤ci−d}P_d = \bigcap_i \{x : n_i \cdot x \le c_i - d\} for d>0d > 0: a point outside PP violates some ni⋅x≤cin_i \cdot x \le c_i and so violates the moved inequality too. This is the set that OFFSET computes by clipping, and each clip is exact because the nin_i and cic_i are rational.

Complexity

Let the convex pocket have nn edges, and let δmax⁡\delta_{\max} be its inradius. The loop of lines L2 to L6 runs K+1K + 1 times, with K=⌊(δmax⁡−r)/s⌋+1K = \lfloor (\delta_{\max} - r)/s \rfloor + 1 loops when δmax⁡≥r\delta_{\max} \ge r. Each OFFSET clips by nn half-planes, and each clip takes time linear in the current polygon, which has at most nn vertices. So the time is O(Kn2)O(K n^2) operations on rationals, and the space is O(n)O(n) for the current offset, plus the output.

The bit size of the rationals grows with each clip in this simple code. An offset of a convex polygon can be computed in O(n)O(n) time from the straight skeleton, which for a convex polygon coincides with the medial axis and is built once in O(nlog⁡n)O(n \log n) time. For a general polygon with nn edges, Held (1991) builds the Voronoi diagram once and reads each offset from it in time linear in the size of the diagram.

Properties

  • Steady cutting direction. The tool turns the same way around every loop, so the whole path is climb milling or the whole path is conventional milling.
  • Maximal cut for s≤rs \le r. By the theorem, no other path with the same tool cuts more.
  • Overlap. For s<2rs < 2r, neighbouring loops cut overlapping strips. With s=rs = r, a point between two loops and away from the corners is within rr of both, so it is cut twice.
  • Sharp corners on the loops. The inward offsets of a convex polygon keep sharp corners, so at each corner the tool turns in place and the engagement with the material jumps.
  • Exact for convex pockets. With rational edge normals, the loops of the code are exact, and every coverage test is a sign test on rationals.

Variants and improvements

  • Voronoi-based offsets. Voronoi pocket machining computes all offsets of a pocket with arcs and islands from one Voronoi diagram, which handles splits and reflex corners.
  • Spiral and Fermat spiral linking. Joining the loops into one spiral removes the link moves. The connected Fermat spiral of additive manufacturing is the same idea for print paths.
  • Outward order. Start at the deepest point and cut outward. This avoids a plunge at the wall, but the first loops cut in full slot.
  • Corner smoothing. High-speed machining rounds the corners of the loops, which lowers the jump in engagement and the change of feed direction.
  • Raster offsets. On a pixel grid, the offsets are the level sets of a distance transform of the pocket.
  • Islands. A pocket with islands has a boundary with several components. The offsets of the outer wall and the offsets of the islands meet and merge, so the loops form a tree.

When to use it

Use a contour-parallel path when the cutting direction must stay the same, for good finish on the walls, and when the pocket has thin features that a zigzag would cross many times. Use a direction-parallel path when the pocket is wide and open and the offsets of its boundary would be hard to compute, or when the machine is faster on straight moves.

Pitfalls

  • Step-over above the radius. Take a corner with interior angle α\alpha on two neighbouring loops of a convex pocket, with long sides. A point on the bisector at distance xx outside the inner corner has distance xx to the inner loop and distance s−xsin⁡(α/2)s - x\sin(\alpha/2) to the outer loop. It stays uncut when r<x<(s−r)/sin⁡(α/2)r < x < (s - r)/\sin(\alpha/2), and such points exist when s>r(1+sin⁡(α/2))s > r(1 + \sin(\alpha/2)), that is s>1.707rs > 1.707r for a right angle. A step-over between rr and 2r2r needs a check for these islands.
  • Mitered offsets of nonconvex shapes. Moving each edge of a nonconvex polygon inward and joining the moved lines is not the Euclidean offset. At a reflex vertex the true offset is an arc, and the joined lines leave self-intersections.
  • Splits. An offset of a nonconvex pocket can split into two or more curves. A program that expects one loop per depth then loses material.
  • Links that leave the offset. A link between two loops must stay in PrP_r, or the tool cuts into the wall. In a convex pocket every straight link between loops is safe, because PrP_r is convex. In a nonconvex pocket it is not.
  • Floating-point offsets. A tiny edge of a floating-point offset can flip its direction and create a spurious loop. Exact rationals avoid this on convex pockets. On general pockets the sign tests of the trimming must be exact.

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.

contour_parallel_toolpath.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contour-parallel-toolpath/. The authors are listed in prov/DWDHQ8.jsonl.

"""Contour-parallel toolpath for a convex pocket, with exact offsets.

The pocket P is a convex polygon given by its vertices in counterclockwise
order. Every edge must have a rational length, so that its unit normal is
rational and every offset is a polygon with rational vertices. Edge
directions such as (3, 4), (5, 12), (8, 15) and the axis directions qualify.

The offset of P at distance d is the set of points of P whose distance to the
boundary is at least d. For a convex polygon it is the intersection of the
half-planes of the edges, each one moved inward by d. The tool center runs
along the boundaries of the offsets at d = r, r + s, r + 2s, ... until the
offset is empty. Here r is the tool radius and s is the step-over.

All coordinates are int or Fraction. Every sign test is exact.
"""

from fractions import Fraction
from math import isqrt

Point = tuple[Fraction, Fraction]
HalfPlane = tuple[Fraction, Fraction, Fraction]  # a x + b y <= c, with a^2 + b^2 = 1


def _exact_sqrt(q: Fraction) -> Fraction:
    """The square root of a nonnegative rational, or ValueError if it is not rational."""
    q = Fraction(q)
    n, d = q.numerator, q.denominator
    rn, rd = isqrt(n), isqrt(d)
    if rn * rn != n or rd * rd != d:
        raise ValueError("an edge has an irrational length")
    return Fraction(rn, rd)


def cross(o: Point, a: Point, b: Point) -> Fraction:
    """The orientation test: positive if o, a, b turn left, zero if collinear."""
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def half_planes(poly: list[Point]) -> list[HalfPlane]:
    """The edge half-planes of a convex counterclockwise polygon, with unit outward normals."""
    pts = [(Fraction(x), Fraction(y)) for x, y in poly]
    n = len(pts)
    if n < 3:
        raise ValueError("a pocket needs at least 3 vertices")
    for i in range(n):
        if cross(pts[i], pts[(i + 1) % n], pts[(i + 2) % n]) <= 0:
            raise ValueError("the polygon is not strictly convex and counterclockwise")
    out = []
    for i in range(n):
        (x0, y0), (x1, y1) = pts[i], pts[(i + 1) % n]
        dx, dy = x1 - x0, y1 - y0
        length = _exact_sqrt(dx * dx + dy * dy)
        a, b = dy / length, -dx / length
        out.append((a, b, a * x0 + b * y0))
    return out


def depth(planes: list[HalfPlane], p: Point) -> Fraction:
    """Signed distance from p to the boundary of the convex polygon: positive inside."""
    return min(c - a * p[0] - b * p[1] for a, b, c in planes)


def clip(poly: list[Point], a: Fraction, b: Fraction, c: Fraction) -> list[Point]:
    """Sutherland-Hodgman clip of a convex polygon by the closed half-plane a x + b y <= c."""
    out: list[Point] = []
    n = len(poly)
    for i in range(n):
        p, q = poly[i], poly[(i + 1) % n]
        fp = c - a * p[0] - b * p[1]
        fq = c - a * q[0] - b * q[1]
        if fp >= 0:
            out.append(p)
        if (fp > 0 and fq < 0) or (fp < 0 and fq > 0):
            t = fp / (fp - fq)
            out.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
    clean: list[Point] = []
    for v in out:
        if not clean or clean[-1] != v:
            clean.append(v)
    if len(clean) > 1 and clean[0] == clean[-1]:
        clean.pop()
    return clean


def offset(poly: list[Point], d) -> list[Point]:
    """The inward offset of the convex polygon at distance d >= 0.

    The result is a convex polygon, a segment (2 points), a point (1 point) or
    empty. Collinear vertices are removed.
    """
    pts = [(Fraction(x), Fraction(y)) for x, y in poly]
    d = Fraction(d)
    q = pts
    for a, b, c in half_planes(pts):
        q = clip(q, a, b, c - d)
        if not q:
            return []
    if len(q) <= 2:
        return q
    keep = [q[i] for i in range(len(q)) if cross(q[i - 1], q[i], q[(i + 1) % len(q)]) != 0]
    if not keep:  # every vertex is collinear: the offset is a segment
        lo, hi = min(q), max(q)
        return [lo, hi] if lo != hi else [lo]
    return keep


def contour_parallel(poly: list[Point], r, s) -> list[tuple[Fraction, list[Point]]]:
    """The loops of a contour-parallel toolpath, from the outside in.

    Each loop is (d, Q): the tool center runs once around the closed polygon Q,
    the offset of the pocket at distance d. A segment or a point is a loop of
    zero area. The first loop is at d = r and each next one is s further in.
    """
    r, s = Fraction(r), Fraction(s)
    if r <= 0 or s <= 0:
        raise ValueError("r and s must be positive")
    loops = []
    d = r  # @line L1
    while True:  # @line L2
        q = offset(poly, d)  # @line L3
        if not q:  # @line L4
            break
        loops.append((d, q))  # @line L5
        d += s  # @line L6
    # The loops are returned in order; a link joins each loop to the next.
    return loops  # @line L7


def loop_segments(q: list[Point]) -> list[tuple[Point, Point]]:
    """The segments of one closed loop. A point gives one degenerate segment."""
    if len(q) == 1:
        return [(q[0], q[0])]
    if len(q) == 2:
        return [(q[0], q[1])]
    return [(q[i], q[(i + 1) % len(q)]) for i in range(len(q))]


def loop_lengths(loops) -> list[Fraction | None]:
    """The length of each loop when it is rational, else None for that loop.

    A segment loop is run out and back, so its length is twice the segment.
    """
    out: list[Fraction | None] = []
    for _, q in loops:
        total = Fraction(0)
        ok = True
        for p, t in loop_segments(q):
            dx, dy = t[0] - p[0], t[1] - p[1]
            try:
                total += _exact_sqrt(dx * dx + dy * dy)
            except ValueError:
                ok = False
        if len(q) == 2:
            total *= 2
        out.append(total if ok else None)
    return out
test_contour_parallel_toolpath.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contour-parallel-toolpath/. The authors are listed in prov/DWDHQ8.jsonl.

import random
from fractions import Fraction as F

import pytest

from contour_parallel_toolpath import (
    clip,
    contour_parallel,
    cross,
    depth,
    half_planes,
    loop_lengths,
    loop_segments,
    offset,
)


def unit_vectors():
    """Rational points on the unit circle from small Pythagorean triples."""
    base = {(F(1), F(0))}
    for m in range(2, 5):
        for n in range(1, m):
            k = m * m + n * n
            base.add((F(m * m - n * n, k), F(2 * m * n, k)))
    out = set()
    for a, b in base:
        for x, y in ((a, b), (b, a)):
            for sx in (1, -1):
                for sy in (1, -1):
                    out.add((sx * x, sy * y))
    return sorted(out)


UNITS = unit_vectors()


def random_convex(rng: random.Random):
    """A random convex polygon whose edges have rational unit normals."""
    while True:
        k = rng.randrange(3, 8)
        normals = rng.sample(UNITS, k)
        box = [(F(-500), F(-500)), (F(500), F(-500)), (F(500), F(500)), (F(-500), F(500))]
        poly = box
        for a, b in normals:
            poly = clip(poly, a, b, F(rng.randrange(3, 20)))
        if len(poly) < 3 or any(abs(x) == 500 or abs(y) == 500 for x, y in poly):
            continue
        n = len(poly)
        poly = [poly[i] for i in range(n) if cross(poly[i - 1], poly[i], poly[(i + 1) % n]) != 0]
        if len(poly) >= 3:
            return poly


def seg_dist2(p, a, b):
    """Exact squared distance from point p to segment ab."""
    dx, dy = b[0] - a[0], b[1] - a[1]
    px, py = p[0] - a[0], p[1] - a[1]
    l2 = dx * dx + dy * dy
    t = F(0) if l2 == 0 else max(F(0), min(F(1), (px * dx + py * dy) / l2))
    ex, ey = px - t * dx, py - t * dy
    return ex * ex + ey * ey


def inside_convex(poly, p):
    if len(poly) == 1:
        return p == poly[0]
    if len(poly) == 2:
        return cross(poly[0], poly[1], p) == 0 and seg_dist2(p, poly[0], poly[1]) == 0
    return all(cross(poly[i], poly[(i + 1) % len(poly)], p) >= 0 for i in range(len(poly)))


def boundary_dist2(poly, p):
    """Squared distance from p to the boundary of a polygon, by a scan of all edges."""
    return min(seg_dist2(p, poly[i], poly[(i + 1) % len(poly)]) for i in range(len(poly)))


def dist2_to_convex(poly, p):
    if not poly:
        return None
    if inside_convex(poly, p):
        return F(0)
    return min(seg_dist2(p, a, b) for a, b in loop_segments(poly))


def path_dist2(loops, p):
    return min(seg_dist2(p, a, b) for _, q in loops for a, b in loop_segments(q))


def grid(poly, steps):
    xs = [x for x, _ in poly]
    ys = [y for _, y in poly]
    x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
    for i in range(steps + 1):
        for j in range(steps + 1):
            yield (x0 + (x1 - x0) * F(2 * i + 1, 2 * steps + 2), y0 + (y1 - y0) * F(2 * j + 1, 2 * steps + 2))


def same_cycle(a, b):
    if len(a) != len(b):
        return False
    if not a:
        return True
    k = a.index(b[0]) if b[0] in a else -1
    return k >= 0 and a[k:] + a[:k] == b


TRIANGLE = [(0, 0), (12, 0), (0, 9)]


def test_example_triangle():
    loops = contour_parallel(TRIANGLE, 1, 1)
    assert [d for d, _ in loops] == [1, 2, 3]
    assert same_cycle(loops[0][1], [(1, 1), (9, 1), (1, 7)])
    assert same_cycle(loops[1][1], [(2, 2), (6, 2), (2, 5)])
    assert loops[2][1] == [(3, 3)]
    assert loop_lengths(loops) == [24, 12, 0]


def test_rectangle_ends_in_a_segment():
    loops = contour_parallel([(0, 0), (8, 0), (8, 4), (0, 4)], 1, 1)
    assert [d for d, _ in loops] == [1, 2]
    assert sorted(loops[1][1]) == [(2, 2), (6, 2)]
    assert loop_lengths(loops) == [16, 8]


def test_offset_against_distance_to_boundary():
    rng = random.Random(7)
    for _ in range(25):
        poly = random_convex(rng)
        planes = half_planes(poly)
        for _ in range(3):
            d = F(rng.randrange(0, 12), rng.randrange(1, 4))
            q = offset(poly, d)
            for p in grid(poly, 7):
                inside_p = inside_convex(poly, p)
                want = inside_p and boundary_dist2(poly, p) >= d * d
                assert (bool(q) and inside_convex(q, p)) == want
                if inside_p:
                    assert depth(planes, p) ** 2 == boundary_dist2(poly, p)


def test_cut_region_is_the_opening_when_step_at_most_radius():
    rng = random.Random(11)
    for _ in range(12):
        poly = random_convex(rng)
        r = F(rng.randrange(1, 4), 2)
        s = r * F(rng.randrange(1, 5), 4)
        loops = contour_parallel(poly, r, s)
        if not loops:
            continue
        core = offset(poly, r)
        for p in grid(poly, 9):
            in_opening = dist2_to_convex(core, p) <= r * r
            assert (path_dist2(loops, p) <= r * r) == in_opening


def test_tool_stays_in_pocket():
    rng = random.Random(3)
    for _ in range(30):
        poly = random_convex(rng)
        planes = half_planes(poly)
        r = F(rng.randrange(1, 6), 2)
        for d, q in contour_parallel(poly, r, F(1)):
            assert d >= r
            for v in q:
                assert depth(planes, v) >= d


def test_large_step_leaves_material_in_a_corner():
    loops = contour_parallel(TRIANGLE, 1, 2)
    assert [d for d, _ in loops] == [1, 3]
    p = (F(21, 10), F(21, 10))
    assert inside_convex(offset(TRIANGLE, 1), p)
    assert path_dist2(loops, p) > 1


def test_square_corner_threshold():
    square = [(0, 0), (10, 0), (10, 10), (0, 10)]
    p = (F(41, 20), F(41, 20))
    loops = contour_parallel(square, 1, F(9, 5))
    assert inside_convex(offset(square, 1), p) and path_dist2(loops, p) > 1
    loops = contour_parallel(square, 1, F(17, 10))
    core = offset(square, 1)
    for q in grid(square, 24):
        if dist2_to_convex(core, q) <= 1:
            assert path_dist2(loops, q) <= 1


def test_bad_input():
    with pytest.raises(ValueError):
        contour_parallel([(0, 0), (1, 0), (0, 1)], 1, 1)  # hypotenuse sqrt(2)
    with pytest.raises(ValueError):
        contour_parallel([(0, 0), (0, 4), (4, 0)], 1, 1)  # clockwise
    with pytest.raises(ValueError):
        contour_parallel(TRIANGLE, 0, 1)

History

Persson (1978) machined pockets of any shape with offset curves of the boundary and built them from the bisectors between boundary elements. Held (1991) gave a full computational geometry of pocket machining, with offsets read from the Voronoi diagram of segments and arcs, and Held, Lukács and Andor (1994) described a complete contour-parallel pocketing system with checks for uncut regions.

References

  1. Martin Held, On the Computational Geometry of Pocket Machining, Lecture Notes in Computer Science 500, Springer, 1991, the chapters on contour-parallel machining, the offsetting of the pocket boundary and the order of the offset loops
  2. Martin Held, Gábor Lukács and László Andor, Pocket machining based on contour-parallel tool paths generated by means of proximity maps, Computer-Aided Design 26(3), 189-203, 1994, the generation of the offset loops from the Voronoi diagram, the check for uncut regions, and the linking of the loops
  3. Hans Persson, NC machining of arbitrarily shaped pockets, Computer-Aided Design 10(3), 169-174, 1978, the offset curves of a pocket boundary built from the bisectors of its elements

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