Algorithmresearch
Connected Fermat spiral toolpath
Also called Fermat spiral infill.
Zhao and coauthors' fill that covers a layer with Fermat spirals joined into one continuous path, which avoids the many starts and stops of contour filling.
- Solves
- Toolpath planning
- Time
- O(n) worst
- Space
- O(n) extra
- Where
- n = number of contours of the rectangle
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Haisen Zhao, Fanglin Gu, Qi Xing Huang, Jorge Garcia, Yong Chen, Changhe Tu, Bedrich Benes, Hao Zhang, Daniel Cohen Or, Baoquan Chen, 2016
A connected Fermat spiral toolpath fills one layer of a printed part with a single continuous path. Zhao and coauthors (2016) built it from the iso-contours of the distance to the boundary, the same curves that a contour-parallel toolpath prints as separate closed loops. A Fermat spiral links every second contour into an inward spiral and the other contours into an outward spiral, and joins the two at the center. Both ends of the path then lie on the outer contour, next to each other, so the spiral of one region can be linked to the spirals of the regions around it. A contour fill with loops needs starts and stops of the nozzle. A Fermat spiral needs one. This page gives the construction on a rectangle, with exact offsets, and proves that the path is simple, stays inside, and covers the rectangle. The general method of the paper, for any region, is described in words only.
In plain words
Draw nested rectangles inside a rectangle, one bead width apart. A printer could print each one as a closed loop, but then it must stop, lift, move and start again for every loop, and each start leaves a mark.
Instead, cut every loop open at one place on its bottom side. Join loop 1 to loop 3, loop 3 to loop 5, and so on, with short vertical pieces that pass through the cuts of the loops in between. This gives a spiral that goes in. Join loops 2, 4, 6 in the same way. That spiral comes back out. Connect the two spirals at the middle. The nozzle now goes in along one spiral and comes out along the other, and it ends right next to where it started.
The problem
The input is a rectangle with and a bead width . The output is a path for the nozzle, a polyline. A good fill path is simple (it does not cross or touch itself), stays at least from the boundary so that the bead stays inside, and leaves no gap and no overlap between beads. A fill path for a region in a layer is a case of toolpath planning.
The contours are the curves at distance from the boundary, for , where is the number of such with . In a rectangle, the contour at distance is the rectangle . With a square bead of side centered on the path, contour covers the frame of points whose distance to the boundary is between and .
The algorithm
Let be the abscissa of the links. Write . Contour is cut open on its bottom side between and , a gap of length , except the innermost contour, which has the gap from to .
FERMAT-RECTANGLE(W, H, w, X)- 1
n ← number of i ≥ 1 with (i − 1/2)w < H/2 - 2
if n < 2 or not (2n − 3/2)w < X < W − 3w/2 then fail - 3
for i ← 1 to n do - 4
d ← (i − 1/2)w - 5
s ← (c_(i−2), d) ▷ start of the open contour - 6
e ← (c_i, d) if i < n, else (c_(n−1), d) ▷ end of the open contour - 7
R_i ← s, (W − d, d), (W − d, H − d), (d, H − d), (d, d), e - 8
A ← R_1 R_3 R_5 ... ▷ the inward spiral - 9
B ← R_2 R_4 R_6 ... ▷ the outward spiral, before reversal - 10
P ← A followed by B reversed ▷ the segment between them is the center join - 11
append (X, w/2) to P ▷ the exit, back to contour 1 - 12
return P
Each open contour goes counterclockwise from its start to its end . In line L8, the end of and the start of have the same abscissa, so consecutive contours of are joined by a vertical link at of length . That link crosses the bottom side of contour at , which is the middle of the gap of contour . Line L9 does the same for the even contours. Line L10 joins the last points of and , which are the ends of contours and and lie on the vertical line . Line L11 adds a last vertical piece from the start of contour 2 down through the gap of contour 1.
The bounds of line L2 make every piece fit. The end of contour must lie right of its left side, , which is . The start of each contour must lie left of its right side, , which is for every . A valid exists if and only if . A square with has no valid in this form. The code of this page rejects it.
Example
Take , , and . Line L1 gives (with and ), and line L2 needs .
| line | value |
|---|---|
| L5 to L7, | : , , , , , |
| L5 to L7, | : , , , , , |
| L8, L9 | , |
| L10 | , then , , , , , |
| L11 |
The path has 13 points and length 23. It starts at and ends at , one bead width to the left. The center join is the segment from up to . A square bead of side 1 along the path covers area , and the covered region is the whole rectangle, so there is no gap and no overlap. Printed as two closed contour loops, the same layer needs two starts. Printed as this path, it needs one.
For , and , line L1 gives . The path has length 65, and the beads leave a strip of area at the center uncovered, because the height is not an even multiple of . A contour fill with the same contours leaves the same strip.
Correctness
Four facts hold for every input that passes line L2. The full proof is below.
- Simple. Every segment is horizontal or vertical. The contours are nested rectangles apart. A vertical link at spans the heights to , and so it meets only contours , and . It meets contour inside its gap, because . The links are at different abscissas , the center join is at , and the exit is at , inside the gap of contour 1. So no two segments meet except consecutive ones at their shared point.
- Inside. Every point has both coordinates at least from the boundary, so a bead of width stays inside the rectangle.
- Ends on the boundary. The path starts at and ends at , both on contour 1, at distance .
- Coverage. The square beads cover the whole rectangle except the core of points at distance more than from the boundary, which has area . The gap of contour is filled by the link at for , by the exit for , and needs nothing for , because its length is .
The length is : the perimeters of the contours, minus the gaps, plus the links, the join and the exit. If , the bead area equals , and the beads cover the rectangle with no overlap. If , the two long sides of contour are closer than , and the beads there overlap. These are properties of the construction on this page, proved for rectangles. This page makes no coverage claim for general regions.
Proof: The Fermat spiral of a rectangle is a simple path inside it that covers all but the corefull
Claim. Let and , let be the number of with , and let . Write . Then FERMAT-RECTANGLE stops and returns a polyline with these properties:
- every segment of is horizontal or vertical and has positive length, and two segments of meet only if they are consecutive, and then only at their shared point;
- every point of lies in ;
- starts at and ends at ;
- the union of the closed squares of side centered at the points of is the set of points of the rectangle at distance at most from its boundary, where the distance is .
Termination is clear: the loop of line L3 runs times, and every other line does a fixed amount of work.
Step 0 (two inequalities). For : , because (the left side decreases in for , and for it is exactly ). And , because . Also gives for all , and gives .
Step 1 (the pieces). Let be the rectangle , contour . By Step 0 it is not degenerate. The open contour of line L7 is without the open interval of its bottom side, where , for and . By Step 0, , so lies strictly inside the bottom side, and the five segments of have positive length. The other segments of are:
- the links of lines L8 and L9: for , the vertical segment at from (the end of ) to (the start of );
- the center join at from to : the last point of and the last point of are the ends and , in some order;
- the exit at from (the start of , which is the last point of reversed) to .
So is the chain , then , then the even contours in reverse with their links, then . Every segment is horizontal or vertical with positive length.
Step 2 (simple). The rectangles are nested and disjoint: lies in the interior of , since . So two different contours never meet. A vertical segment at abscissa with heights in meets only , and , and it meets only where it crosses or touches the bottom side , provided . This holds for the link at , : and . It holds for (contours and ): and by Step 0. It holds for (contours 1 and 2): and .
- meets only at its lower end and only at its upper end. It crosses the line at , and , so the crossing point lies in the gap if , or in if . So does not meet .
- spans and meets only and , at its ends.
- spans . It meets only at . At its point lies in , so it does not meet .
- Two of these vertical segments have different abscissas , and , so they are disjoint.
Within one , the five segments form a rectangle minus a gap, so only consecutive ones meet, at corners, and the first and the last do not meet because is not empty. A link meets the segments of and only at the shared end points. This proves part 1.
Step 3 (inside, ends). Every point of lies on some , and with . The first point of is and the last is . This proves parts 2 and 3.
Step 4 (coverage). For a set , let be the union of the closed squares of side centered at the points of , which is the set of points at distance at most from . For a rectangle, is the closed frame . Every segment of lies on some or between two of them, so .
For the other inclusion, fix and a point . If is within distance of a point of , it is covered. Otherwise its nearest points on lie in the gap, and so lies in the box . For the gap has length , so this box is the single segment , and its points are at distance exactly from both ends of , so they are covered. For the box is . If , the link at spans the heights to , so its square bead covers the heights to and the abscissas of the box. If , the exit at spans to , and its bead covers the heights to . So for every , and .
The core is the open rectangle , of area ; note follows from the bounds on . This proves part 4.
Complexity
The path has points, and each is found in time, so the time and the extra space are , with . The tests check simplicity by comparing all pairs of segments, which is and is not part of the algorithm.
For a general region, the cost of the method of Zhao and coauthors is dominated by the computation of the iso-contours of the distance field and by the smoothing and optimization steps. The paper does not state a single bound for the whole pipeline, and this page does not give one.
Properties
- One path. The layer is printed with one start and one stop, against one per contour for a contour fill.
- Spacing. Two parallel passes side by side are apart, except the two long sides of the innermost contour, which are apart. The tests check this on squares and rectangles. The proof page does not prove it.
- Both ends outside. The two ends lie on the outer contour, one bead width apart. A spiral can be opened there and spliced into a neighbor path.
- Follows the boundary. Like a contour fill, every pass is parallel to the boundary, so the outer surface is printed by a contour, not by the ends of raster lines.
- Few sharp turns on smooth regions. On a smooth region, the spirals turn as gently as the contours. On a rectangle, the corners stay.
- Exact. With rational input, every point is rational, and every claim above is checked exactly.
Variants and improvements
- General regions. For a region with holes or several lobes, the contours of the distance field change topology: a contour splits into two, or two merge. Zhao and coauthors split the region at these events into spiralable parts, each with nested contours, fill each part with a Fermat spiral, and connect the spirals into one path by a traversal of the tree of parts. Each connection opens a spiral at its two ends on the boundary and routes it through the neighbor. This page does not implement that pipeline.
- Smoothing. The paper smooths the path and adjusts the spacing to reduce sharp turns and gaps between beads. Those steps are not part of this page.
- Single spiral. A plain spiral links contour to contour and ends at the center. It is also one path, but its end is inside, so it cannot be linked to a neighbor without a jump.
- Other fills. A direction-parallel toolpath uses parallel lines joined end to end. It is simpler and gives the same pattern in every region, but it meets the boundary at the end of every line. See infill pattern for the sparse fills used inside parts.
When to use it
Use a connected Fermat spiral when the number of starts and stops matters, for example on extrusion printers where each start and stop leaves a mark or a weak spot, and when the fill should follow the boundary. Use a raster fill when the region is very thin or very complex, or when the slicer must be simple and fast. The claims of the paper about print quality are measured on test prints. The claims on this page are proved for rectangles only.
Pitfalls
- Spacing near the links. The pieces next to the links are short when is close to a bound of line L2. A piece of length much less than makes a tight U-turn, where real beads overlap. Choose near the middle of the interval.
- Even and odd heights. If is not an even multiple of , the center has a gap or an overlap. Adjust slightly, as the paper adjusts the spacing, or accept the error.
- Squares. A square of side works in this form only if , for example or with . A square of side has no valid link position. Use a different place for the links, or change slightly.
- The exit fills a gap. Contour 1 has a gap of , and only the exit passes through it. If the exit is left out, a square of side next to the start stays empty.
- Floating-point offsets. For general regions, offsets in floating point can make two contours touch or cross. Snap the result and check for self-intersection.
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/fermat-spiral-toolpath/. The authors are listed in prov/RPHNQ4.jsonl.
"""A connected Fermat spiral on an axis-aligned rectangle, with exact offsets.
This is the basic step of Zhao et al. (2016) on the simplest region. The
iso-contours of the distance to the boundary at spacing w are the rectangles
inset by d_i = (i - 1/2) w. Each contour is cut open on its bottom edge. The
odd contours are linked into one inward spiral, the even contours into a
second one, and the two spirals are joined at the center. The result is one
path that goes in and comes out again, and both of its ends lie on the outer
contour, at distance w from each other.
The general pipeline of the paper (contours of a distance field on any region,
the split into spiralable parts, and the linking of many spirals into one
path) is not implemented here.
Coordinates are int or Fraction, so every test on the result is exact.
"""
from fractions import Fraction
def ring_count(height, w):
"""Number of contours i >= 1 with (i - 1/2) w < height / 2."""
half = Fraction(height) / 2
n = 0
while (n + Fraction(1, 2)) * w < half:
n += 1
return n
def link_range(width, height, w):
"""The open interval of link abscissas X that give a valid path."""
width, height, w = Fraction(width), Fraction(height), Fraction(w)
n = ring_count(height, w)
return n, (2 * n - Fraction(3, 2)) * w, width - Fraction(3, 2) * w
def fermat_rectangle(width, height, w, x_link=None):
"""Return the path as a list of (x, y) points.
The rectangle is [0, width] x [0, height] with width >= height, and w is
the spacing. x_link is the abscissa X of the links. It must satisfy
(2n - 3/2) w < X < width - 3w/2. The default is the midpoint.
Raises ValueError if no valid path of this form exists.
"""
width, height, w = Fraction(width), Fraction(height), Fraction(w)
if height > width:
raise ValueError("expects width >= height; swap the axes")
n, lo, hi = link_range(width, height, w) # @line L1
if x_link is None:
x_link = (lo + hi) / 2
x_link = Fraction(x_link)
if n < 2 or not lo < x_link < hi: # @line L2
raise ValueError("the rectangle is too small or too narrow for this spacing")
rings = []
for i in range(1, n + 1): # @line L3
d = (i - Fraction(1, 2)) * w # @line L4
s = (x_link - (i - 2) * w, d) # @line L5
e = (x_link - min(i, n - 1) * w, d) # @line L6
rings.append([s, (width - d, d), (width - d, height - d), (d, height - d), (d, d), e]) # @line L7
odd = [p for ring in rings[0::2] for p in ring] # @line L8
even = [p for ring in rings[1::2] for p in ring] # @line L9
path = odd + even[::-1] # @line L10
path.append((x_link, w / 2)) # the exit: back down to contour 1 # @line L11
return path # @line L12
def segments(path):
return [(path[i], path[i + 1]) for i in range(len(path) - 1)]
def length(path):
"""Length of the path. Every segment is axis-parallel."""
return sum(abs(b[0] - a[0]) + abs(b[1] - a[1]) for a, b in segments(path))
if __name__ == "__main__":
p = fermat_rectangle(6, 4, 1, Fraction(7, 2))
print(" ".join("(%s, %s)" % (x, y) for x, y in p))
print("length", length(p))
test_fermat_spiral_toolpath.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fermat-spiral-toolpath/. The authors are listed in prov/RPHNQ4.jsonl.
import random
from fractions import Fraction as F
import pytest
from fermat_spiral_toolpath import fermat_rectangle, length, link_range, ring_count, segments
def box(seg):
(x0, y0), (x1, y1) = seg
return min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)
def meet(a, b):
"""Intersection of two axis-parallel segments as a box, or None."""
a, b = box(a), box(b)
lo_x, lo_y, hi_x, hi_y = max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])
if lo_x > hi_x or lo_y > hi_y:
return None
return lo_x, lo_y, hi_x, hi_y
def union_area(rects):
"""Exact area of a union of boxes by coordinate compression (brute force)."""
xs = sorted({r[0] for r in rects} | {r[2] for r in rects})
ys = sorted({r[1] for r in rects} | {r[3] for r in rects})
total = F(0)
for i in range(len(xs) - 1):
cx = (xs[i] + xs[i + 1]) / 2
col = [r for r in rects if r[0] < cx < r[2]]
for j in range(len(ys) - 1):
cy = (ys[j] + ys[j + 1]) / 2
if any(r[1] < cy < r[3] for r in col):
total += (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j])
return total
def bead(path, w):
"""The square bead of side w swept along each segment."""
h = w / 2
return [(b[0] - h, b[1] - h, b[2] + h, b[3] + h) for b in map(box, segments(path))]
def random_case(rng):
w = F(rng.choice([1, 1, 2, 3]), rng.choice([1, 2]))
height = w * F(rng.randint(31, 130), 10) # height > 3w, so n >= 2
n = ring_count(height, w)
width = max(height, 2 * n * w) + w * F(rng.randint(1, 60), 10)
n, lo, hi = link_range(width, height, w)
x = lo + (hi - lo) * F(rng.randint(1, 99), 100)
return width, height, w, x
def check_simple(path):
seg = segments(path)
for i, a in enumerate(seg):
assert a[0] != a[1] and (a[0][0] == a[1][0] or a[0][1] == a[1][1]) # nonzero, axis-parallel
for j in range(i + 1, len(seg)):
m = meet(a, seg[j])
if j == i + 1:
assert m == (a[1][0], a[1][1], a[1][0], a[1][1]) # only the shared vertex
else:
assert m is None
def test_page_example():
p = fermat_rectangle(6, 4, 1, F(7, 2))
h = F(1, 2)
want = [(9 * h, h), (11 * h, h), (11 * h, 7 * h), (h, 7 * h), (h, h), (5 * h, h),
(5 * h, 3 * h), (3 * h, 3 * h), (3 * h, 5 * h), (9 * h, 5 * h), (9 * h, 3 * h), (7 * h, 3 * h), (7 * h, h)]
assert p == want
assert length(p) == 23
assert union_area(bead(p, F(1))) == 24 # covers the whole 6 x 4 rectangle
def test_simple_inside_and_ends_on_the_boundary():
rng = random.Random(4)
for _ in range(150):
width, height, w, x = random_case(rng)
p = fermat_rectangle(width, height, w, x)
check_simple(p)
assert all(w / 2 <= px <= width - w / 2 and w / 2 <= py <= height - w / 2 for px, py in p)
(sx, sy), (ex, ey) = p[0], p[-1]
assert sy == ey == w / 2 and sx - ex == w # both ends on contour 1, side by side
def test_length_formula():
rng = random.Random(5)
for _ in range(150):
width, height, w, x = random_case(rng)
n = ring_count(height, w)
assert length(fermat_rectangle(width, height, w, x)) == 2 * n * (width + height) - 4 * w * n * n - w
def test_coverage_and_overlap():
rng = random.Random(6)
exact = 0
for _ in range(60):
width, height, w, x = random_case(rng)
if rng.random() < 0.3: # make the height an even multiple of w
height = 2 * w * rng.randint(2, 6)
width = max(width, height + w)
n, lo, hi = link_range(width, height, w)
x = (lo + hi) / 2
p = fermat_rectangle(width, height, w, x)
n = ring_count(height, w)
covered = union_area(bead(p, w))
core = (width - 2 * n * w) * max(F(0), height - 2 * n * w)
assert covered == width * height - core
material = length(p) * w + w * w
assert material >= covered
if height == 2 * n * w:
exact += 1
assert covered == material == width * height # no gap and no overlap
assert exact > 5
def parallel_gap(a, b):
"""Distance of two parallel segments whose projections overlap with positive length, else None."""
(ax0, ay0), (ax1, ay1) = a
(bx0, by0), (bx1, by1) = b
if ay0 == ay1 and by0 == by1:
if min(max(ax0, ax1), max(bx0, bx1)) > max(min(ax0, ax1), min(bx0, bx1)):
return abs(ay0 - by0)
if ax0 == ax1 and bx0 == bx1:
if min(max(ay0, ay1), max(by0, by1)) > max(min(ay0, ay1), min(by0, by1)):
return abs(ax0 - bx0)
return None
def test_spacing_of_passes_on_squares_and_rectangles():
rng = random.Random(8)
cases = [(F(7), F(7), F(1)), (F(21, 2), F(21, 2), F(1)), (F(9), F(9), F(1))]
cases += [random_case(rng)[:3] for _ in range(40)]
for width, height, w in cases:
p = fermat_rectangle(width, height, w)
seg = segments(p)
gaps = [parallel_gap(seg[i], seg[j]) for i in range(len(seg)) for j in range(i + 1, len(seg))]
n = ring_count(height, w)
inner = height - (2 * n - 1) * w # distance of the long sides of the innermost contour
assert min(g for g in gaps if g is not None) == min(w, inner)
def test_feasibility_interval():
rng = random.Random(7)
for _ in range(60):
width, height, w, _ = random_case(rng)
n, lo, hi = link_range(width, height, w)
for bad in (lo, hi, lo - w / 7, hi + w / 7):
with pytest.raises(ValueError):
fermat_rectangle(width, height, w, bad)
check_simple(fermat_rectangle(width, height, w, lo + (hi - lo) / 1000))
check_simple(fermat_rectangle(width, height, w, hi - (hi - lo) / 1000))
with pytest.raises(ValueError):
fermat_rectangle(6, 6, 1) # n = 3 needs width > 6
with pytest.raises(ValueError):
fermat_rectangle(10, 2, 1) # one contour only
check_simple(fermat_rectangle(7, 6, 1))
def test_without_the_bounds_the_path_breaks():
# At X = hi the first piece of each contour has length zero.
width, height, w = F(10), F(7), F(1)
n, lo, hi = link_range(width, height, w)
p = fermat_rectangle(width, height, w, hi - F(1, 10 ** 6))
assert min(abs(b[0] - a[0]) + abs(b[1] - a[1]) for a, b in segments(p)) == F(1, 10 ** 6)
History
Zhao, Gu, Huang, Garcia, Chen, Tu, Benes, Zhang, Cohen-Or and Chen presented connected Fermat spirals for layered fabrication at SIGGRAPH 2016, in ACM Transactions on Graphics. The name comes from the Fermat spiral , which has two arms that wind into the center and meet there. Earlier fill paths for printing and for pocket milling were contour loops or zigzag lines.
References
- Haisen Zhao, Fanglin Gu, Qi-Xing Huang, Jorge Garcia, Yong Chen, Changhe Tu, Bedrich Benes, Hao Zhang, Daniel Cohen-Or and Baoquan Chen, Connected Fermat spirals for layered fabrication, ACM Transactions on Graphics 35(4), Article 100, 2016, the construction of a Fermat spiral from the iso-contours of a spiralable region, and the connection of the spirals of all regions into one path
- Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the discussion of contour and raster fill paths for extrusion processes
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 RPHNQ4 Edit this page History Report an error Markdown