Algorithm Search⌘K

Algorithmadvanced

Voronoi pocket machining

Also called Held pocket machining.

Held's method that computes the Voronoi diagram of the pocket boundary and reads all offset curves and their topology changes from it for contour-parallel paths.

Time
O(n^2 + K n log n) worst
Space
O(n) extra
Where
K = number of loops; n = number of edges of the convex pocket
Properties
deterministicexactiterative
Origin
Martin Held, 1991

Voronoi pocket machining builds a contour-parallel toolpath for a pocket from the Voronoi diagram of its boundary. The part of the diagram inside the pocket is the medial axis. Each point of it carries its clearance, the distance to the boundary, and the offset curve at distance dd is the set of points of the pocket at clearance exactly dd, so all offsets come from one diagram. Held (1991) made this the core of a pocketing method for areas bounded by segments and circular arcs, with islands. The diagram also shows where an offset splits into parts, and it gives safe links between loops along its arcs. This is a manufacturing method of mechanical CAD, not an EDA router. The code handles convex polygons only, where the medial axis has straight arcs and an exact wavefront builds it.

In plain words

Pour water around the inside of a pocket wall and let it flow inward at the same speed everywhere. The front of the water at each moment has the shape of an offset loop, the loop that a tool center would follow at that distance from the wall.

Mark the places where two fronts from different parts of the wall meet. These marks form a thin tree, the skeleton of the pocket. Each point of the skeleton knows when the water reached it, which is its distance to the wall.

Once the skeleton is known, any loop is found by walking along the skeleton and picking the points with the right distance. The skeleton also shows where a loop breaks into two, and it gives a path from one loop to the next that stays far from the wall.

The problem

The input is a pocket PP, a tool radius rr and a step-over ss. The output is the set of offset loops at distances dk=r+ksd_k = r + ks, and the links between them, as in contour-parallel toolpath, which also proves that the loops cover what the tool can reach when s≤rs \le r.

The depth δ(x)\delta(x) of a point is its distance to the boundary of PP. The medial axis MM is the closure of the set of points of PP that have at least two nearest points on the boundary. For a convex polygon P={x:ni⋅x≤ci}P = \{x : n_i \cdot x \le c_i\} with unit outward normals nin_i, the depth of x∈Px \in P is δ(x)=min⁡ifi(x)\delta(x) = \min_i f_i(x) with fi(x)=ci−ni⋅xf_i(x) = c_i - n_i \cdot x, and MM is the closure of the set of points where at least two indices reach the minimum. The offset at distance dd is Pd={x∈P:δ(x)≥d}P_d = \{x \in P : \delta(x) \ge d\}.

In a convex polygon, MM is a tree with straight arcs. Each arc is a piece of the bisector of two edges, and δ\delta is affine along it. In a pocket with reflex vertices or circular arcs, the Voronoi diagram also has parabolic and other conic arcs, and the offsets have circular arcs around the reflex vertices.

The algorithm

The medial axis of a convex polygon is the track of a wavefront: the offset PtP_t, whose edges move inward at unit speed as tt grows. A vertex of PtP_t is the meeting point of two moved edges, and it moves along their bisector. An edge ee between neighbours pp and qq vanishes at the time tt when the three moved lines ni⋅x=ci−tn_i \cdot x = c_i - t for i∈{p,e,q}i \in \{p, e, q\} meet in one point. This is a 3×33 \times 3 linear system in (x,y,t)(x, y, t), solved by Cramer's rule with exact rationals.

  1. MEDIAL-AXIS(P)
  2. 1F ← the edges of P in order; start one arc at each vertex, with clearance 0
  3. 2while F has more than 3 edges do
  4. 3for each edge e of F with neighbours p and q: t_e ← time when the lines of p, e, q meet
  5. 4take e with the smallest t_e, and let N be the meeting point
  6. 5end the arcs (p, e) and (e, q) at N, with clearance t_e
  7. 6start the arc (p, q) at N, with clearance t_e
  8. 7remove e from F
  9. 8end the three open arcs at the meeting point of the last three lines, and return the arcs
  10. VORONOI-POCKET(P, r, s)
  11. 9A ← MEDIAL-AXIS(P), δmax ← clearance of the deepest node
  12. OFFSET(A, d):
  13. 10collect the point of clearance d on each arc whose clearance range holds d
  14. 11return the convex hull of the collected points
  15. 12for d ← r, r + s, r + 2s, ... while d ≤ δmax: append the loop OFFSET(A, d)
  16. 13if d + s ≤ δmax then link the loop to the next one along the spine

The spine is the chain of arcs from one polygon vertex to the deepest node. The clearance does not decrease along it, so the link between the loops at dd and d+sd + s is the part of the spine between these two clearances, and the tool stays at clearance at least dd during the link. Each loop starts where the spine meets it.

In a convex pocket the points of line L10 are in convex position, so line L11 only puts them in order. In a general pocket, line L10 returns one or more closed curves, and Held reads their order from the tree structure of the diagram.

Example

Take the pentagon with vertices (0,0)(0, 0), (20,0)(20, 0), (20,9)(20, 9), (8,25)(8, 25), (0,10)(0, 10). Its edges have lengths 20, 9, 20, 17 and 10, and the outward unit normals are (0,−1)(0, -1), (1,0)(1, 0), (45,35)(\tfrac45, \tfrac35), (−1517,817)(-\tfrac{15}{17}, \tfrac{8}{17}) and (−1,0)(-1, 0).

step edge that vanishes node clearance
L3 to L7 the right edge x=20x = 20 (534,274)(\tfrac{53}{4}, \tfrac{27}{4}) 274=6.75\tfrac{27}{4} = 6.75
L3 to L7 the left edge x=0x = 0 (8,8)(8, 8) 88
L8 the last three edges meet (374,354)(\tfrac{37}{4}, \tfrac{35}{4}) 354=8.75\tfrac{35}{4} = 8.75

The medial axis has 2⋅5−3=72 \cdot 5 - 3 = 7 arcs: five from the vertices and two between the nodes. With r=2r = 2 and s=2s = 2, the loops are at d=2,4,6,8d = 2, 4, 6, 8. The first three are pentagons, for example (2,2)(2, 2), (18,2)(18, 2), (18,253)(18, \tfrac{25}{3}), (587,1497)(\tfrac{58}{7}, \tfrac{149}{7}), (2,192)(2, \tfrac{19}{2}) at d=2d = 2. The loop at d=8d = 8 is the triangle (434,8)(\tfrac{43}{4}, 8), (647,717)(\tfrac{64}{7}, \tfrac{71}{7}), (8,8)(8, 8), because both vertical edges have vanished by then. The spine from vertex (20,0)(20, 0) gives the links (18,2)→(16,4)(18, 2) \to (16, 4), (16,4)→(14,6)(16, 4) \to (14, 6) and (14,6)→(534,274)→(434,8)(14, 6) \to (\tfrac{53}{4}, \tfrac{27}{4}) \to (\tfrac{43}{4}, 8). The last one bends at the node where the right edge vanished. The deepest node has clearance 8.75, so no loop fits at d=10d = 10.

Correctness

Each wavefront vertex between edges ii and jj at time tt satisfies fi=fj=tf_i = f_j = t and lies in PtP_t, so it has depth tt and two nearest edges: it is on the medial axis. Conversely, a point of the medial axis with depth t>0t > 0 lies on two different moved lines that support the convex set PtP_t, so it is a vertex of PtP_t, and thus on the track of a wavefront vertex. Each edge length of the wavefront is an affine function of tt, so the edge that vanishes first is the one with the smallest meeting time of line L3. For OFFSET, every point found by line L10 has depth dd, so it lies in PdP_d, and every vertex of PdP_d is a point of the medial axis with clearance dd, so it is found. The convex hull of a subset of a convex polygon that holds all its vertices is the polygon.

The proof file gives these steps in full for the generic case, where no two events happen at the same time and no two parallel edges meet. Degenerate inputs, such as a rectangle, where two edges vanish at the same time and two parallel edges meet along a segment of constant clearance, are handled by the same steps, one event at a time. For those the code is checked against direct offsets by exact tests, but the proof does not cover them.

Proof: The wavefront builds the medial axis of a convex polygon, and the offsets read from it are exactfull

Setting. PP is a strictly convex polygon with edges 1,…,n1, \dots, n, n≥3n \ge 3, unit outward normals nin_i and fi(x)=ci−ni⋅xf_i(x) = c_i - n_i \cdot x, so P={x:fi(x)≥0 for all i}P = \{x : f_i(x) \ge 0 \text{ for all } i\}. By the convex offset lemma of the contour-parallel proof, the depth of x∈Px \in P is δ(x)=min⁡ifi(x)\delta(x) = \min_i f_i(x) and Pt={x:fi(x)≥t for all i}P_t = \{x : f_i(x) \ge t \text{ for all } i\}. For a set FF of edges let QF(t)={x:fi(x)≥t for all i∈F}Q_F(t) = \{x : f_i(x) \ge t \text{ for all } i \in F\}, and let Li(t)L_i(t) be the line fi=tf_i = t. MM is the closure of the set of points of the interior of PP where at least two indices reach min⁡ifi\min_i f_i. For two adjacent edges p,qp, q of a polygon, Xpq(t)X_{pq}(t) is the meeting point of Lp(t)L_p(t) and Lq(t)L_q(t).

Assumption (G), the generic case. In each pass of line L3, exactly one edge has the smallest meeting time.

Claim. Under (G), MEDIAL-AXIS stops after n−3n - 3 passes. Its arcs are segments whose union is MM, the clearance δ\delta along each arc is affine in its parameter and runs from t0t_0 to t1t_1, and the deepest node has clearance δmax⁡=max⁡Pδ\delta_{\max} = \max_P \delta. For every d≥0d \ge 0, OFFSET(A,d)=Pd(A, d) = P_d.

Termination. Each pass of the loop of line L2 removes one edge from FF in line L7, so the loop runs exactly n−3n - 3 times.

Lemma 1 (erosion). If QF(τ)=QG(τ)Q_F(\tau) = Q_G(\tau), then QF(t)=QG(t)Q_F(t) = Q_G(t) for all t≥τt \ge \tau. Proof. Let ρ=t−τ≥0\rho = t - \tau \ge 0. For ∣v∣≤ρ|v| \le \rho, fi(x+v)=fi(x)−ni⋅v≥fi(x)−ρf_i(x + v) = f_i(x) - n_i \cdot v \ge f_i(x) - \rho, with equality at v=ρniv = \rho n_i. So the closed disk of radius ρ\rho around xx lies in {fi≥τ}\{f_i \ge \tau\} if and only if fi(x)≥tf_i(x) \ge t. Hence x∈QF(t)x \in Q_F(t) if and only if this disk lies in QF(τ)Q_F(\tau), and the same holds for GG. □\square

Lemma 2 (edge lengths). Let RR be a convex polygon with nonempty interior whose edges, in counterclockwise order, lie on the lines Li(τ)L_i(\tau), i∈Fi \in F, each with positive length. For consecutive edges p,e,qp, e, q, the length of edge ee of the polygon bounded by the lines Li(t)L_i(t) is ℓe(t)=ℓe(τ)−(t−τ)(tan⁡β2+tan⁡γ2)\ell_e(t) = \ell_e(\tau) - (t - \tau)(\tan\tfrac{\beta}{2} + \tan\tfrac{\gamma}{2}), where β,γ∈(0,π)\beta, \gamma \in (0, \pi) are the exterior angles of RR at the two ends of ee. Proof. Rotate so that ne=(0,−1)n_e = (0, -1) and the edge runs in the direction (1,0)(1, 0). The left end Xpe(t)X_{pe}(t) moves with a constant velocity vv with ne⋅v=−1n_e \cdot v = -1 and np⋅v=−1n_p \cdot v = -1. Here np=(−sin⁡β,−cos⁡β)n_p = (-\sin\beta, -\cos\beta), so vy=1v_y = 1 and vx=(1−cos⁡β)/sin⁡β=tan⁡β2>0v_x = (1 - \cos\beta)/\sin\beta = \tan\tfrac{\beta}{2} > 0. The right end moves left at speed tan⁡γ2\tan\tfrac{\gamma}{2} by symmetry. □\square

So ℓe\ell_e is affine and strictly decreasing, and it is zero exactly when Xpe(t)=Xeq(t)X_{pe}(t) = X_{eq}(t), that is, when Lp(t)L_p(t), Le(t)L_e(t) and Lq(t)L_q(t) meet in one point. The system of line L3 has rows (ni,1)(n_i, 1) for three distinct unit vectors, which are not collinear points of the circle, so it has one solution tet_e, and te>τt_e > \tau is the zero of ℓe\ell_e.

Invariant. At each test of line L2, with τ\tau the clearance of the last event (τ=0\tau = 0 at the start):

  • (I1) Pt=QF(t)P_t = Q_F(t) for all t≥τt \ge \tau;
  • (I2) PτP_\tau is a convex polygon with nonempty interior whose edges, in order, lie on Li(τ)L_i(\tau) for i∈Fi \in F, each with positive length;
  • (I3) for each pair (p,q)(p, q) of consecutive edges of FF there is one open arc, which starts at Xpq(τ)X_{pq}(\tau) with clearance τ\tau, and every closed arc runs from Xpq(t0)X_{pq}(t_0) to Xpq(t1)X_{pq}(t_1) for the pair (p,q)(p, q) that was consecutive in FF during [t0,t1][t_0, t_1].

At the start, FF is all edges, P0=PP_0 = P, and line L1 starts arc (i,i+1)(i, i+1) at the vertex Xi,i+1(0)X_{i,i+1}(0). So the invariant holds.

A pass of the loop. Let τ′=te\tau' = t_e be the smallest meeting time, for the edge ee between pp and qq. By Lemma 2 every edge length ℓi\ell_i is positive on [τ,τ′)[\tau, \tau'), and by (G) every ℓi\ell_i with i≠ei \ne e is still positive at τ′\tau'. For t∈[τ,τ′)t \in [\tau, \tau') the lines Li(t)L_i(t), i∈Fi \in F, with the fixed exterior angles of RR and positive lengths, bound a convex polygon. A convex polygon is the intersection of the half-planes of its edges, so this polygon is QF(t)=PtQ_F(t) = P_t. Its vertex between consecutive p,qp, q is Xpq(t)X_{pq}(t), which moves on a straight line at constant speed. At τ′\tau', edge ee has length 0 and Xpe(τ′)=Xeq(τ′)=NX_{pe}(\tau') = X_{eq}(\tau') = N, the point of line L4. The polygon Pτ′P_{\tau'} has its other edges, all of positive length, on the lines of F′=F∖{e}F' = F \setminus \{e\}, and at least three of them, with distinct normals, so its interior is not empty. This gives (I2) for F′F'. Also Pτ′=QF′(τ′)P_{\tau'} = Q_{F'}(\tau'), as the intersection of the half-planes of its edges, and Pτ′=QF(τ′)P_{\tau'} = Q_F(\tau') by (I1). By Lemma 1, QF(t)=QF′(t)Q_F(t) = Q_{F'}(t) for all t≥τ′t \ge \tau', which gives (I1). Lines L5 and L6 close the arcs of (p,e)(p, e) and (e,q)(e, q) at NN and open the arc of (p,q)(p, q) at N=Xpq(τ′)N = X_{pq}(\tau'), which gives (I3).

The last step. When FF has three edges, PτP_\tau is a triangle. The three meeting times of Lemma 2 are all the meeting time TT of the same three lines, so all three edges shrink to the point NN of line L8 at time TT, and ℓi(t)<0\ell_i(t) < 0 for t>Tt > T means that QF(t)Q_F(t) is empty. So δmax⁡=T\delta_{\max} = T, and NN is the deepest node.

Each arc lies in MM. A point Xpq(t)X_{pq}(t) of an arc has fp=fq=tf_p = f_q = t and lies in PtP_t, so δ=t\delta = t is reached by two indices. For t>0t > 0 it is an interior point of PP. The arc starts at clearance t0t_0 and ends at t1t_1, and δ\delta is affine along it. Arcs that start at t0=0t_0 = 0 start at a vertex of PP, which is in the closure.

Each point of MM lies on an arc. Let xx be an interior point of PP where two indices i≠ji \ne j reach δ(x)=t>0\delta(x) = t > 0. Then x∈Ptx \in P_t and fi(x)=fj(x)=tf_i(x) = f_j(x) = t, so Li(t)L_i(t) and Lj(t)L_j(t) are two supporting lines of the convex set PtP_t through xx, with different normals. If t<Tt < T, PtP_t is a polygon with nonempty interior by the invariant, and a boundary point of such a polygon with two different supporting lines is a vertex. So x=Xpq(t)x = X_{pq}(t) for a consecutive pair of FF at time tt, which is a point of the arc of (p,q)(p, q). If t=Tt = T, then PT={N}P_T = \{N\} and x=Nx = N. The points of MM on the boundary of PP are limits of such points, and they are vertices of PP, where arcs start.

OFFSET. Let 0≤d≤T0 \le d \le T. Every point that line L10 collects is a point of an arc with clearance dd, so it has depth dd and lies in PdP_d. Every vertex of PdP_d lies on two edge lines Li(d)L_i(d), Lj(d)L_j(d) with i≠ji \ne j that support PdP_d, so it is reached by two indices: it is in MM with clearance dd, and it is collected. A convex polygon is the convex hull of its vertices, so Pd⊆hull⁡(collected)⊆PdP_d \subseteq \operatorname{hull}(\text{collected}) \subseteq P_d. For d>Td > T no arc has clearance dd, and Pd=∅P_d = \emptyset. ■\blacksquare

The links. Arc aa ends where a.nexta.\mathrm{next} starts, with the same clearance, so the clearance along the spine does not decrease. A link from the loop at dd to the loop at d+sd + s is a chain of straight pieces of arcs whose points have clearance between dd and d+sd + s, so it lies in Pd⊆PrP_d \subseteq P_r, and the tool does not touch the wall during it.

What this proof does not cover. When two edges have the same smallest meeting time, or two parallel edges become neighbours, assumption (G) fails. The code then removes the edges one at a time at the same clearance, and an arc between two parallel edges has t0=t1t_0 = t_1. For these inputs the tests compare the medial axis and the offsets with direct computations, exactly, on rectangles and on random polygons with parallel sides. That is a check, not a proof.

Complexity

Line L2 runs n−3n - 3 times, and line L3 solves at most nn systems of size 3, so the code builds the medial axis in O(n2)O(n^2) time. A priority queue of the meeting times makes this O(nlog⁡n)O(n \log n), because each event changes the meeting times of two edges only. The axis has nn leaves, n−2n - 2 inner nodes counted with multiplicity, and 2n−32n - 3 arcs. Line L10 scans the 2n−32n - 3 arcs, and the hull of line L11 takes O(nlog⁡n)O(n \log n), so each loop costs O(nlog⁡n)O(n \log n), and O(n)O(n) if the points are collected in order around the tree. The total is O(n2+Knlog⁡n)O(n^2 + K n \log n) for KK loops.

For a general pocket with nn segments and arcs, the Voronoi diagram has O(n)O(n) size and can be computed in O(nlog⁡n)O(n \log n) time, for example by Fortune's sweep for segments. Held (1998) uses a wavefront algorithm that is fast in practice.

Properties

  • One diagram, all offsets. The diagram is built once. Every offset, at any distance, comes from it in time linear in its size.
  • Topology from the diagram. Where the clearance along the axis has a local minimum, at a neck of the pocket, the offsets deeper than that clearance split in two. Where it has a local maximum, a loop shrinks to a point and ends. The diagram shows each such place, so the order of the loops and the places where the tool must lift are known before any loop is cut. In a convex pocket the offsets never split.
  • Safe links. The tool center moves along the arcs between loops. Along the spine the clearance does not decrease, so the tool does not cut into the wall.
  • Exact in the convex case. With rational edge normals, every node and every loop vertex of the code is rational.

Variants and improvements

  • Curvilinear pockets. Held (1998) handles areas bounded by segments and circular arcs. The offsets of such an area are again made of segments and arcs, which a CNC controller can follow directly.
  • Islands. The boundary of a pocket with islands has several components. The Voronoi diagram is the same object, and the offsets of the islands and of the outer wall merge where their fronts meet.
  • The straight skeleton. The straight skeleton is the track of a wavefront that keeps sharp corners at reflex vertices. It coincides with the medial axis for convex polygons only. Offsets read from it are mitered offsets, not Euclidean ones.
  • Medial axis toolpaths. Some methods move the tool along the medial axis itself, to clear the middle of a narrow pocket in one pass.

When to use it

Use the Voronoi method when the pocket has islands, reflex corners or arcs, and when many offsets of the same pocket are needed, as in roughing with a small step-over. For a convex pocket, direct half-plane intersection at each depth is simpler, as on the contour-parallel page.

Pitfalls

  • Arcs are required. At a reflex vertex the Voronoi diagram has a parabolic arc between the vertex and an edge, and the offset has a circular arc. A method that uses only straight bisectors builds the straight skeleton, not the medial axis.
  • Degenerate events. Several edges can vanish at the same time, and two parallel edges can meet along a segment of constant clearance, as in a rectangle. The code handles them one event at a time with exact arithmetic. With floating point, the order of near-equal events can flip and give a wrong tree.
  • Robustness of the diagram. A Voronoi diagram of segments in floating point needs care with nearly parallel and nearly touching segments. See exact geometric computation.
  • A hull only in the convex case. Line L11 uses the convex hull to order the points, which is valid only because the offsets of a convex pocket are convex.

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.

voronoi_pocket_machining.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/voronoi-pocket-machining/. The authors are listed in prov/MEJQSV.jsonl.

"""Voronoi pocket machining on a convex polygon, with exact arithmetic.

Held's method computes the Voronoi diagram of the pocket boundary once and
reads every offset curve from it. Inside a convex polygon the Voronoi diagram
of the edges is the medial axis, and it is made of straight pieces of angle
bisectors. This module builds it with a wavefront: all edges move inward at
unit speed, and an edge disappears when its two neighbours meet on it. The
time of that event is the clearance (the distance to the boundary) of the
node where it happens.

Each arc of the medial axis is the track of one wavefront vertex. Its
clearance grows linearly from one end to the other, so the offset at distance
d is read from the arcs: one point on each arc whose clearance range holds d.

The pocket must be strictly convex, counterclockwise, with edges of rational
length, so that the unit normals are rational. A nonconvex pocket has
reflex vertices, and its Voronoi diagram then has parabolic arcs and its
offsets have circular arcs; this module does not handle that case.
"""

from fractions import Fraction
from math import isqrt

Point = tuple[Fraction, Fraction]


def _exact_sqrt(q: Fraction) -> Fraction:
    q = Fraction(q)
    rn, rd = isqrt(q.numerator), isqrt(q.denominator)
    if rn * rn != q.numerator or rd * rd != q.denominator:
        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 for a left turn, zero when collinear."""
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def half_planes(poly):
    """Edge i goes from vertex i to vertex i + 1; it is a x + b y <= c with a unit normal."""
    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]
        length = _exact_sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
        a, b = (y1 - y0) / length, -(x1 - x0) / length
        out.append((a, b, a * x0 + b * y0))
    return pts, out


def _meet(planes, i, j, k):
    """The point and time where the moved lines of edges i, j and k meet (Cramer's rule)."""
    rows = [planes[i], planes[j], planes[k]]
    m = [[a, b, Fraction(1)] for a, b, _ in rows]
    rhs = [c for _, _, c in rows]

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

    d = det(m)
    sol = []
    for col in range(3):
        q = [row[:] for row in m]
        for r in range(3):
            q[r][col] = rhs[r]
        sol.append(det(q) / d)
    return (sol[0], sol[1]), sol[2]


class Arc:
    """The track of the wavefront vertex between edges left and right."""

    __slots__ = ("left", "right", "p0", "t0", "p1", "t1", "next")

    def __init__(self, left, right, p0, t0):
        self.left, self.right = left, right
        self.p0, self.t0 = p0, t0
        self.p1 = self.t1 = None
        self.next = None  # the arc that starts where this one ends

    def at(self, d) -> list[Point]:
        """The points of the arc with clearance d."""
        if not (self.t0 <= d <= self.t1):
            return []
        if self.t1 == self.t0:
            return [self.p0, self.p1]
        lam = (d - self.t0) / (self.t1 - self.t0)
        return [(self.p0[0] + lam * (self.p1[0] - self.p0[0]), self.p0[1] + lam * (self.p1[1] - self.p0[1]))]


def medial_axis(poly):
    """The medial axis of a convex polygon as a list of arcs, and its deepest node.

    The first n arcs start at the polygon vertices: arc i starts at vertex
    i + 1, between edges i and i + 1. Every arc ends at a node, and arc.next is
    the arc that leaves that node (None at the deepest node).
    """
    pts, planes = half_planes(poly)
    n = len(pts)
    front = list(range(n))  # @line L1
    arcs = []
    live = {}  # (left, right) -> Arc
    for i in range(n):
        a = Arc(i, (i + 1) % n, pts[(i + 1) % n], Fraction(0))
        arcs.append(a)
        live[(i, (i + 1) % n)] = a
    while len(front) > 3:  # @line L2
        best = None
        m = len(front)
        for pos in range(m):  # @line L3
            p, e, q = front[pos - 1], front[pos], front[(pos + 1) % m]
            point, t = _meet(planes, p, e, q)
            if best is None or t < best[0]:
                best = (t, pos, point)
        t, pos, point = best  # @line L4
        p, e, q = front[pos - 1], front[pos], front[(pos + 1) % m]
        a1, a2 = live.pop((p, e)), live.pop((e, q))  # @line L5
        new = Arc(p, q, point, t)  # @line L6
        for a in (a1, a2):
            a.p1, a.t1, a.next = point, t, new
        arcs.append(new)
        live[(p, q)] = new
        front.pop(pos)  # @line L7
    point, t = _meet(planes, *front)  # @line L8
    for a in live.values():
        a.p1, a.t1 = point, t
    return arcs, (point, t)


def convex_hull(points: list[Point]) -> list[Point]:
    """Andrew's monotone chain; collinear points are dropped. Exact for rationals."""
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts
    lower, upper = [], []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    hull = lower[:-1] + upper[:-1]
    return hull if len(hull) > 2 else [pts[0], pts[-1]]


def offset_from_axis(arcs, d) -> list[Point]:
    """The offset at distance d, read from the medial axis.

    Inside a convex pocket the points of clearance d on the arcs are the
    vertices of the offset, so the offset is their convex hull.
    """
    d = Fraction(d)
    found = []
    for a in arcs:  # @line L10
        found.extend(a.at(d))
    return convex_hull(found)  # @line L11


def spine(arcs, start=0):
    """The chain of arcs from polygon vertex start + 1 to the deepest node."""
    chain = []
    a = arcs[start]
    while a is not None:
        chain.append(a)
        a = a.next
    return chain


def point_on_spine(chain, d) -> Point:
    """The point of clearance d on a chain whose clearance does not decrease."""
    for a in chain:
        if a.t0 <= d <= a.t1:
            return a.at(d)[0]
    raise ValueError("no point of this clearance on the chain")


def voronoi_pocket(poly, r, s):
    """Loops at d = r, r + s, ... and the links between them along the medial axis.

    Returns (loops, links). Each loop is (d, polygon) and starts at the point
    where the spine meets it. Link k goes from loop k to loop k + 1 along the
    spine, so it stays at clearance at least r.
    """
    r, s = Fraction(r), Fraction(s)
    if r <= 0 or s <= 0:
        raise ValueError("r and s must be positive")
    arcs, (_, deepest) = medial_axis(poly)  # @line L9
    chain = spine(arcs)
    loops, links = [], []
    d = r
    while d <= deepest:  # @line L12
        loop = offset_from_axis(arcs, d)
        loops.append((d, _start_at(loop, point_on_spine(chain, d))))
        nd = d + s
        if nd <= deepest:  # @line L13
            pts = [point_on_spine(chain, d)]
            for a in chain:
                if d < a.t1 and a.t1 < nd:
                    pts.append(a.p1)
            pts.append(point_on_spine(chain, nd))
            links.append(pts)
        d = nd
    return loops, links


def _start_at(loop, p):
    """Rotate a closed loop so that it starts at p, inserting p on an edge if needed."""
    if p in loop:
        k = loop.index(p)
        return loop[k:] + loop[:k]
    m = len(loop)
    for i in range(m):
        a, b = loop[i], loop[(i + 1) % m]
        if cross(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]):
            return [p] + loop[i + 1:] + loop[:i + 1]
    raise ValueError("the point is not on the loop")
test_voronoi_pocket_machining.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/voronoi-pocket-machining/. The authors are listed in prov/MEJQSV.jsonl.

import itertools
import random
from fractions import Fraction as F

import pytest

from voronoi_pocket_machining import (
    convex_hull,
    cross,
    half_planes,
    medial_axis,
    offset_from_axis,
    voronoi_pocket,
)


def unit_vectors():
    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 clip(poly, a, b, c):
    """Reference: clip a convex polygon by a x + b y <= c (Sutherland-Hodgman)."""
    out = []
    for i in range(len(poly)):
        p, q = poly[i], poly[(i + 1) % len(poly)]
        fp, fq = c - a * p[0] - b * p[1], c - a * q[0] - b * q[1]
        if fp >= 0:
            out.append(p)
        if fp * fq < 0:
            t = fp / (fp - fq)
            out.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
    return out


def reference_offset(poly, d):
    """The offset by clipping with all moved half-planes, a method that does not use the axis."""
    _, planes = half_planes(poly)
    q = [(F(x), F(y)) for x, y in poly]
    for a, b, c in planes:
        q = clip(q, a, b, c - d)
        if not q:
            return []
    return convex_hull(q)


def random_convex(rng):
    while True:
        normals = rng.sample(UNITS, rng.randrange(3, 9))
        poly = [(F(-500), F(-500)), (F(500), F(-500)), (F(500), F(500)), (F(-500), F(500))]
        for a, b in normals:
            poly = clip(poly, a, b, F(rng.randrange(2, 16)))
            if not poly:
                break
        if len(poly) < 3 or any(abs(x) == 500 or abs(y) == 500 for x, y in poly):
            continue
        poly = convex_hull(poly)
        if len(poly) >= 3:
            return poly


def depth(planes, p):
    return min(c - a * p[0] - b * p[1] for a, b, c in planes)


def brute_inradius(poly):
    """Largest inscribed circle by trying every triple of edge lines."""
    _, planes = half_planes(poly)
    best = None
    for i, j, k in itertools.combinations(range(len(planes)), 3):
        m = [planes[i], planes[j], planes[k]]
        a = [[x[0], x[1], F(1)] for x in m]
        det = (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
               + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
        if det == 0:
            continue
        # solve by elimination
        rows = [a[t] + [m[t][2]] for t in range(3)]
        for col in range(3):
            piv = next(r for r in range(col, 3) if rows[r][col] != 0)
            rows[col], rows[piv] = rows[piv], rows[col]
            for r in range(3):
                if r != col and rows[r][col] != 0:
                    f = rows[r][col] / rows[col][col]
                    rows[r] = [x - f * y for x, y in zip(rows[r], rows[col])]
        x, y, t = (rows[r][3] / rows[r][r] for r in range(3))
        if t >= 0 and depth(planes, (x, y)) == t and (best is None or t > best):
            best = t
    return best


RECT = [(0, 0), (8, 0), (8, 4), (0, 4)]
PENTAGON = [(0, 0), (20, 0), (20, 9), (8, 25), (0, 10)]
TRIANGLE = [(0, 0), (12, 0), (0, 9)]


def test_triangle_has_one_node():
    arcs, (node, t) = medial_axis(TRIANGLE)
    assert node == (3, 3) and t == 3
    assert len(arcs) == 3 and all(a.p1 == (3, 3) for a in arcs)


def test_rectangle_axis_and_offsets():
    arcs, (node, t) = medial_axis(RECT)
    assert t == 2
    ends = sorted({a.p1 for a in arcs})
    assert ends == [(2, 2), (6, 2)]
    assert offset_from_axis(arcs, 1) == [(1, 1), (7, 1), (7, 3), (1, 3)]
    assert offset_from_axis(arcs, 2) == [(2, 2), (6, 2)]
    assert offset_from_axis(arcs, F(5, 2)) == []


def test_arcs_are_on_the_medial_axis():
    rng = random.Random(5)
    for poly in [RECT, PENTAGON, TRIANGLE] + [random_convex(rng) for _ in range(40)]:
        _, planes = half_planes(poly)
        arcs, _ = medial_axis(poly)
        assert len(arcs) == 2 * len(poly) - 3
        for a in arcs:
            assert a.t0 <= a.t1
            mid = ((a.p0[0] + a.p1[0]) / 2, (a.p0[1] + a.p1[1]) / 2)
            for p, t in ((a.p0, a.t0), (a.p1, a.t1), (mid, (a.t0 + a.t1) / 2)):
                assert depth(planes, p) == t
                for e in (a.left, a.right):
                    ea, eb, ec = planes[e]
                    assert ec - ea * p[0] - eb * p[1] == t


def test_offsets_match_clipping():
    rng = random.Random(9)
    for poly in [RECT, PENTAGON, TRIANGLE] + [random_convex(rng) for _ in range(40)]:
        arcs, (_, deepest) = medial_axis(poly)
        times = sorted({a.t1 for a in arcs})
        ds = times + [F(rng.randrange(0, 40), 4) for _ in range(6)] + [deepest + F(1, 7)]
        for d in ds:
            assert offset_from_axis(arcs, d) == reference_offset(poly, d)


def test_deepest_node_is_the_inradius():
    rng = random.Random(13)
    for poly in [RECT, PENTAGON] + [random_convex(rng) for _ in range(30)]:
        _, (node, t) = medial_axis(poly)
        assert t == brute_inradius(poly)
        _, planes = half_planes(poly)
        assert depth(planes, node) == t


def test_pocket_loops_and_links():
    rng = random.Random(17)
    for poly in [PENTAGON] + [random_convex(rng) for _ in range(20)]:
        _, planes = half_planes(poly)
        r = F(rng.randrange(1, 5), 2)
        s = r * F(rng.randrange(2, 5), 4)
        loops, links = voronoi_pocket(poly, r, s)
        assert len(links) == max(0, len(loops) - 1)
        for k, (d, loop) in enumerate(loops):
            assert d == r + k * s
            assert convex_hull(loop) == reference_offset(poly, d)
        for k, link in enumerate(links):
            assert link[0] == loops[k][1][0] and link[-1] == loops[k + 1][1][0]
            ts = [depth(planes, p) for p in link]
            assert ts == sorted(ts) and ts[0] >= r


def test_pentagon_example():
    arcs, (node, t) = medial_axis(PENTAGON)
    assert node == (F(37, 4), F(35, 4)) and t == F(35, 4)
    assert sorted({(a.p1, a.t1) for a in arcs[:5]}) == [
        ((F(8), F(8)), F(8)),
        ((F(37, 4), F(35, 4)), F(35, 4)),
        ((F(53, 4), F(27, 4)), F(27, 4)),
    ]
    loops, links = voronoi_pocket(PENTAGON, 2, 2)
    assert [(d, len(q)) for d, q in loops] == [(2, 5), (4, 5), (6, 5), (8, 3)]
    assert loops[3][1] == [(F(43, 4), 8), (F(64, 7), F(71, 7)), (8, 8)]
    assert links[2] == [(14, 6), (F(53, 4), F(27, 4)), (F(43, 4), 8)]


def test_bad_input():
    with pytest.raises(ValueError):
        medial_axis([(0, 0), (1, 0), (0, 1)])
    with pytest.raises(ValueError):
        medial_axis([(0, 0), (0, 4), (3, 0)])
    with pytest.raises(ValueError):
        voronoi_pocket(TRIANGLE, 1, 0)

History

Held's 1991 monograph gave the Voronoi diagram of segments and arcs as the tool for pocket machining, with the offsets, their splits and the order of the loops all read from it. Held, Lukács and Andor (1994) described a full system with this method, and Held (1998) gave a wavefront algorithm for curvilinear polygons.

References

  1. Martin Held, On the Computational Geometry of Pocket Machining, Lecture Notes in Computer Science 500, Springer, 1991, the chapters on the Voronoi diagram of a pocket boundary, the offsets read from it, and the generation of contour-parallel tool paths
  2. Martin Held, Voronoi diagrams and offset curves of curvilinear polygons, Computer-Aided Design 30(4), 287-300, 1998, the wavefront algorithm for the Voronoi diagram of an area bounded by segments and circular arcs, and the offsets computed from it
  3. 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 use of the Voronoi diagram for the offsets, the detection of uncut regions and the links between loops

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