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.
- Solves
- Pocket machining
- Time
- O(K n^2) worst
- Space
- O(n) extra
- Where
- K = number of loops; n = number of edges of the convex pocket
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 from the boundary, and each next loop lies one step-over 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 the loops cut all of the material that any tool of radius 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 of the plane. The tool is a disk of radius , and the tool center follows a path . The tool removes the material in , the Minkowski sum of the path and the disk. The tool must stay in the pocket, so every disk around a point of lies in .
The depth of a point is its distance to the outside of the pocket, . The offset at distance is the set , and its boundary is the offset curve. A disk of radius around lies in if and only if , so the tool centers that keep the tool in the pocket form exactly . Hence no path can cut more than the morphological opening . The parts of outside are the corners that a round tool cannot reach.
For a convex polygon with unit outward normals , the depth of a point is , so the offset is the intersection of half-planes . If every edge has a rational length, every is rational and every offset has rational vertices.
The algorithm
CONTOUR-PARALLEL(P, r, s)- 1
d ← r - 2
loop - 3
Q ← OFFSET(P, d) ▷ P_d: all points at depth at least d - 4
if Q is empty then exit the loop - 5
append the loop (d, ∂Q) - 6
d ← d + s - 7
link the loops in order and return the path
For a convex pocket, OFFSET clips by the half-planes moved inward by , with the Sutherland-Hodgman rule. Each clip computes the sign of at each vertex 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 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 , and , a tool of radius and a step-over . The edges have lengths 12, 15 and 9, and the inward unit normals are , and . The inradius is 3, with the incenter at , and each offset is the triangle scaled toward the incenter by the factor .
| step | loop | length | |
|---|---|---|---|
| L3 to L5 | 1 | , , | 24 |
| L3 to L5 | 2 | , , | 12 |
| L3 to L5 | 3 | the point | 0 |
| L3, L4 | 4 | empty, stop |
The links add , so the path has length . The triangle has area 54. The opening has area , so of material stays in the three corners. No path with this tool can remove it.
With instead, the loops are at and . The point is in the opening, but its distance to the first loop is and its distance to the point is . Both are more than , so a small island of material stays near the right-angle corner.
Correctness
Theorem. Let be a compact region, and , and let be nonempty. CONTOUR-PARALLEL stops after a finite number of loops. Each disk of radius around a point of the path lies in , and the path cuts exactly the opening .
The proof rests on one fact about the depth: for , the distance from to the offset curve is exactly . Walk from straight toward the nearest point outside . The depth drops at rate exactly 1 along this walk, so after it equals , and that point is on . A point deep in the pocket lies between the loop at and the loop at , so its distance to the loop at is less than . A point near the wall is within of a tool center , and the segment from to crosses , the first loop, at a point within of . The full proof is in the proof file.
The condition 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. is compact, and . For let , so for . For let . Let . Assume , let be the largest with , and let be the set of points visited by the loops. is the closed disk of radius at the origin, and .
Claim. (a) exists, so CONTOUR-PARALLEL stops after loops of lines L2 to L6. (b) For every , . (c) . (d) If , then . So every path whose tool stays in cuts a subset of , and the loops cut all of it.
Step 1 (facts on ). is the distance to a set, so for all , and is continuous. Each with is closed, as the preimage of , and lies in . If is a limit of points not in , then by continuity, so . Conversely, let . The set is open and nonempty ( is bounded), so its closure has a point with . For let . Then , because . So the points with are not in , and is a limit of them. Hence .
Step 2 (the distance to an offset curve). Let . Then some point has . Proof. Write and take with as in Step 1. For , the bound holds as in Step 1, and the Lipschitz bound gives . So . Take and . Then , so by Step 1, and .
Step 3 (termination). is continuous on the compact set and is outside , so it has a maximum . Then for . The value of line L6 grows by exactly in each loop, so after at most tests of line L4 the offset is empty. The nonempty offsets are those with , and they form an initial run because for . This proves (a).
Step 4 (the tool stays in the pocket). Let . Then , so . If a point with were outside , then . So the open disk of radius around lies in , and the closed disk lies in because is closed. This proves (b). The same argument with shows .
Step 5 (maximality). Let . Every point outside is outside the closed disk, at distance more than from , so and . This proves (d).
Step 6 (coverage). gives . For the other inclusion, let , so for some . We find a point of within of .
Case A: . Let be the largest index with . Then , so , and : for by the choice of , and for because . By Step 2 some has .
Case B: . Let on . It is continuous, and . Let . Then by continuity, so , and for all . So lies in and is a limit of points not in , so . And .
In both cases . This proves (c).
The convex offset used by the code. Let with unit vectors . The complement of is the union of the open half-planes . For , the distance from to the -th open half-plane is , and the distance to a union is the minimum of the distances. So on , and for : a point outside violates some and so violates the moved inequality too. This is the set that OFFSET computes by clipping, and each clip is exact because the and are rational.
Complexity
Let the convex pocket have edges, and let be its inradius. The loop of lines L2 to L6 runs times, with loops when . Each OFFSET clips by half-planes, and each clip takes time linear in the current polygon, which has at most vertices. So the time is operations on rationals, and the space is 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 time from the straight skeleton, which for a convex polygon coincides with the medial axis and is built once in time. For a general polygon with 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 . By the theorem, no other path with the same tool cuts more.
- Overlap. For , neighbouring loops cut overlapping strips. With , a point between two loops and away from the corners is within 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 on two neighbouring loops of a convex pocket, with long sides. A point on the bisector at distance outside the inner corner has distance to the inner loop and distance to the outer loop. It stays uncut when , and such points exist when , that is for a right angle. A step-over between and 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 , or the tool cuts into the wall. In a convex pocket every straight link between loops is safe, because 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DWDHQ8 Edit this page History Report an error Markdown