Algorithm Search⌘K

Algorithmadvanced

Direct slicing of CAD models

Also called CAD-based slicing.

Cuts the exact CAD solid by each layer plane instead of a triangle mesh, so the layer contours are exact curves and the only error is the one chosen for the printer path.

Time
O(k t) conic_treesO(t n) polygons
Space
O(t + n) extra
Where
k = number of layers; n = total number of polygon vertices over all layers; t = number of nodes of the CSG tree
Properties
deterministicexactrecursive
Origin
Sashidhar Guduri, Richard H. Crawford, Joseph J. Beaman, Ron Jamieson, Herbert Hacker, 1992

Direct slicing computes the layers of a part for additive manufacturing from the exact CAD model, not from a triangle mesh. The usual chain exports the solid as an STL mesh and then cuts the triangles with the layer planes, as in triangle mesh slicing. The mesh only touches the true surface at its vertices, so every contour inherits the chord error of the export, and this error is fixed in 3D before anyone knows the layer height. Direct slicing intersects each layer plane with the true faces of the model. For a solid made of planes, spheres, cylinders and cones the section of each face is an exact conic with rational coefficients, and the layer is the same Boolean expression of these conics. For NURBS faces the section is a curve that a numerical method computes to a tolerance that the user sets per layer. Guduri, Crawford and Beaman (1992) did this for CSG solids of quadrics, and Jamieson and Hacker (1995) did it for the B-rep inside a CAD system. This page gives the exact version for a CSG tree of quadrics, proves that the section of the tree is the tree of the sections, and bounds the error of the polygon that is finally sent to the printer.

In plain words

To print a part, the printer needs its outline on each layer. The common way first turns the smooth part into many small flat triangles, then cuts the triangles. The triangles are a little off the real surface, so every outline is a little off too, and nothing later can fix it.

Direct slicing skips the triangles. It asks the CAD model itself where each layer crosses the surface. For a ball or a round hole the answer is an exact circle or oval. The outline only becomes straight segments at the very end, and the program picks as many segments as it needs to stay within the error that the user allows on that layer.

The problem

A solid is given as a CSG tree (constructive solid geometry). Each leaf is a quadric half-space: a symmetric 4×44 \times 4 matrix QQ, with the solid {p:p^TQp^≤0}\{p : \hat p^{\mathsf T} Q \hat p \le 0\} for p^=(x,y,z,1)\hat p = (x, y, z, 1). Each inner node is a union, an intersection or a difference of its two children. A ball of center cc and radius RR is ∣p−c∣2−R2≤0|p - c|^2 - R^2 \le 0. An infinite cylinder through the point qq with axis direction aa and radius rr is

∣p−q∣2−((p−q)⋅a)2∣a∣2−r2≤0,|p - q|^2 - \frac{((p - q) \cdot a)^2}{|a|^2} - r^2 \le 0,

and a half-space n⋅p≤dn \cdot p \le d is a quadric with no quadratic part. All input numbers are rational.

Given the tree TT, the layer heights Z1<⋯<ZkZ_1 < \dots < Z_k and a tolerance tol, the task is to give, for each layer, the exact set S(T)∩{z=Zi}S(T) \cap \{z = Z_i\}, and a set of polygons for the printer whose distance from the true contours is at most tol.

The algorithm

Substitute z=Zz = Z in the quadric. The result is a conic pˉTMpˉ≤0\bar p^{\mathsf T} M \bar p \le 0 with pˉ=(x,y,1)\bar p = (x, y, 1) and a symmetric 3×33 \times 3 matrix MM. The upper left 2×22 \times 2 block AA of MM is the same as in QQ, the last column picks up Qi3Z+Qi4Q_{i3} Z + Q_{i4}, and the corner is Q33Z2+2Q34Z+Q44Q_{33} Z^2 + 2 Q_{34} Z + Q_{44}. With rational QQ and ZZ these are rational numbers, computed without error.

  1. DIRECT-SLICE(T, Z, tol)
  2. 1for each leaf Q of T: M_Q ← SECTION(Q, Z) ▷ exact rational conic
  3. 2T_Z ← T with each leaf Q replaced by M_Q ▷ the exact layer
  4. 3contours ← empty list
  5. 4for each leaf M of T_Z do
  6. 5(kind, c, f_c) ← CLASSIFY(M)
  7. 6if kind = ellipse then P ← POLYLINE(M, tol)
  8. 7append the runs of vertices v of P with CLASSIFY-POINT(T_Z, v, M) = on
  9. 8return T_Z, contours
  10. CLASSIFY(M) ▷ A = 2×2 block, b = (M13, M23), f₀ = M33
  11. 9if det A = 0 then return parabolic
  12. 10c ← −A⁻¹ b; f_c ← f₀ + b·c ▷ the value of the conic at its center
  13. 11if A is positive definite then return ellipse, point or empty as f_c <, =, > 0
  14. 12return hyperbola, line pair or complement
  15. POLYLINE(M, tol) ▷ a ≥ b semi-axes, e₁, e₂ unit axes
  16. 13n ← max(3, ⌈π / arccos(1 − tol/a)⌉)
  17. 14return c + a cos(2πj/n) e₁ + b sin(2πj/n) e₂ for j = 0 … n−1

Lines L1 and L2 are the whole exact part: the layer is the tree TZT_Z, and a point (x,y)(x, y) is in the layer if and only if the same Boolean expression of the signs of the conics says so. CLASSIFY finds the center cc where the gradient of the conic vanishes, and the value fcf_c there. If the block AA is positive definite and fc<0f_c < 0, the leaf is an ellipse with squared semi-axes −fc/λ1-f_c/\lambda_1 and −fc/λ2-f_c/\lambda_2, where λ1,λ2\lambda_1, \lambda_2 are the eigenvalues of AA. The type, the center, fcf_c, det⁡A\det A and tr⁡A\operatorname{tr} A are exact. The semi-axes and their directions need square roots, so only they are floats.

POLYLINE is the only step that approximates. It places nn vertices on the ellipse, and nn is the least number of vertices for which the chord error a(1−cos⁡(π/n))a(1 - \cos(\pi/n)) is at most tol. Line L7 trims the polygon of one leaf to the boundary of the layer. A vertex is kept when it is on the boundary of TZT_Z with that leaf forced to "on", with the three valued rules: a union is in if one side is in, an intersection is out if one side is out, and a difference is an intersection with the complement, which swaps in and out.

A general CAD model is a B-rep whose faces are planes, quadrics, tori and NURBS patches. The same plan applies face by face: the section of a plane or a quadric face is a line or a conic, trimmed to the face boundary, and the section of a NURBS face is a curve that a surface-surface intersection method traces to a tolerance. The pieces are then linked into loops by their end points.

Example

A ball of radius 10 at the origin has a straight hole of radius 2 drilled through it. The hole has the axis direction a=(3,0,4)a = (3, 0, 4) through the origin, so it leans 36.87°36.87° from the vertical. The tree is T=ball∖cylinderT = \text{ball} \setminus \text{cylinder}. Slice it at Z=4Z = 4 with tol =0.01= 0.01.

Line L1 gives two conics. For the ball, M=diag⁡(1,1,−84)M = \operatorname{diag}(1, 1, -84): the circle x2+y2≤84x^2 + y^2 \le 84, which is R2−Z2=100−16R^2 - Z^2 = 100 - 16. For the cylinder, ∣a∣2=25|a|^2 = 25 and

M=(16/250−48/25010−48/25044/25),M = \begin{pmatrix} 16/25 & 0 & -48/25 \\ 0 & 1 & 0 \\ -48/25 & 0 & 44/25 \end{pmatrix},

which is 16x2+25y2−96x+44≤016 x^2 + 25 y^2 - 96 x + 44 \le 0 after multiplying by 25.

leaf kind center cc fcf_c det⁡A\det A squared semi-axes
ball ellipse (0,0)(0, 0) −84-84 1 84 and 84
cylinder ellipse (3,0)(3, 0) −4-4 16/2516/25 25/425/4 and 44

The cylinder gives the ellipse (x−3)2/6.25+y2/4≤1(x - 3)^2/6.25 + y^2/4 \le 1, with semi-axes 2.5 along xx and 2 along yy. The closed form agrees: the axis meets the plane at t=Z/az=1t = Z/a_z = 1, at (3,0,4)(3, 0, 4), and a cylinder of radius rr cut by a plane at angle gives the semi-axes rr and r∣a∣/∣az∣=2⋅5/4=2.5r|a|/|a_z| = 2 \cdot 5/4 = 2.5. All the numbers in the table are exact fractions.

The point (3,0)(3, 0) is in the hole: the ball conic is −75≤0-75 \le 0 and the cylinder conic is −100/25=−4≤0-100/25 = -4 \le 0, so the difference says out. The point (7,0)(7, 0) has the scaled cylinder value 16⋅49−96⋅7+44=156>016 \cdot 49 - 96 \cdot 7 + 44 = 156 > 0 and the ball value 49−84<049 - 84 < 0, so it is in the layer.

Line L13 gives n=68n = 68 for the outer circle (a=84≈9.165a = \sqrt{84} \approx 9.165) and n=36n = 36 for the hole (a=2.5a = 2.5). The hole lies inside the disk, so all the vertices of both polygons are "on", and the result is two closed loops. On the next layer only the numbers ZZ change in line L1, and the error stays at most 0.01 on every layer.

The same ball as a mesh. A UV sphere of radius 10 with 16 rings and 32 segments is within about 0.096 of the true sphere in 3D. Slice it at z=2.5z = 2.5: the section is a regular 32-gon with circumradius 9.641 and inradius 9.595, while the true circle has radius 93.75≈9.682\sqrt{93.75} \approx 9.682. The contour is off by up to 0.088. At z=−9.95z = -9.95, near the pole, the true radius is 0.999 and the mesh section has radius at most 0.508, so the contour is off by 0.49: the surface is almost flat there, and a small error in height becomes a large error in the layer. The direct section at z=2.5z = 2.5 is x2+y2≤375/4x^2 + y^2 \le 375/4, exactly.

Correctness

Three facts make the method correct. First, substituting z=Zz = Z in p^TQp^\hat p^{\mathsf T} Q \hat p gives pˉTMpˉ\bar p^{\mathsf T} M \bar p term by term, so each leaf conic is the exact section of its leaf. Second, the section by a plane commutes with union, intersection and difference: (A∪B)∩Π=(A∩Π)∪(B∩Π)(A \cup B) \cap \Pi = (A \cap \Pi) \cup (B \cap \Pi), and the same for the other two. By induction on the tree, TZT_Z describes exactly the section of the solid. Third, the polygon of POLYLINE is the affine image of a regular nn-gon inscribed in the unit circle. Pairing each point of the circle with the point of the nn-gon on the same ray moves it by a factor between cos⁡(π/n)\cos(\pi/n) and 1. The affine map stretches no vector by more than aa, so the Hausdorff distance between the polygon and the ellipse is at most a(1−cos⁡(π/n))≤tola(1 - \cos(\pi/n)) \le \text{tol}.

One caveat: CAD kernels use regularized Boolean operations, and regularization does not commute with the section. At a plane that only touches a face, the exact section can have a lower dimension part, such as the single point x2+y2≤0x^2 + y^2 \le 0 at the pole of a ball. The regularized layer drops it. The trimming of line L7 is a float test, and near a point where two conics cross, a kept run ends up to one edge before the crossing. The full proof is in the correctness proof.

What the tests check. They compare the sphere section with r2=R2−(Z−cz)2r^2 = R^2 - (Z - c_z)^2 and the cylinder section with the semi-axes rr and r∣a∣/∣az∣r|a|/|a_z| on random rational input, exactly. They compare the 2D membership with the 3D membership on random trees and points, and they measure the Hausdorff distance of the polygons against tol.

Proof: The plane section of a quadric CSG solid is the same Boolean tree of exact conics, and the polygon output is within the tolerancefull

Setting. A leaf is a symmetric 4×44 \times 4 matrix QQ, and the leaf solid is SQ={p∈R3:p^TQp^≤0}S_Q = \{p \in \mathbb R^3 : \hat p^{\mathsf T} Q \hat p \le 0\} with p^=(x,y,z,1)\hat p = (x, y, z, 1). A tree TT is a leaf or (op,T1,T2)(\mathrm{op}, T_1, T_2) with op in {∪,∩,∖}\{\cup, \cap, \setminus\}, and its solid S(T)S(T) is defined by the same recursion. For a height ZZ let ΠZ={(x,y,Z)}\Pi_Z = \{(x, y, Z)\}, and identify ΠZ\Pi_Z with R2\mathbb R^2. Lines L1 and L2 build the tree TZT_Z with each leaf QQ replaced by the 3×33 \times 3 matrix M=SECTION(Q,Z)M = \text{SECTION}(Q, Z):

Mij=Qij (i,j≤2),Mi3=M3i=Qi3Z+Qi4 (i≤2),M33=Q33Z2+2Q34Z+Q44.M_{ij} = Q_{ij}\ (i, j \le 2),\qquad M_{i3} = M_{3i} = Q_{i3} Z + Q_{i4}\ (i \le 2),\qquad M_{33} = Q_{33} Z^2 + 2 Q_{34} Z + Q_{44}.

The set of a conic leaf is CM={(x,y):pˉTMpˉ≤0}C_M = \{(x, y) : \bar p^{\mathsf T} M \bar p \le 0\} with pˉ=(x,y,1)\bar p = (x, y, 1), and S(TZ)S(T_Z) is built from these sets by the same operations.

Claim.

  1. S(TZ)=S(T)∩ΠZS(T_Z) = S(T) \cap \Pi_Z as point sets, and every entry of every MM is rational when QQ and ZZ are rational.
  2. CLASSIFY returns the right type for an ellipse leaf, its center cc and the value fcf_c at the center, and the squared semi-axes are −fc/λ1-f_c / \lambda_1 and −fc/λ2-f_c / \lambda_2, where λ1,λ2\lambda_1, \lambda_2 are the eigenvalues of the 2×22 \times 2 block.
  3. For an ellipse with largest semi-axis aa and a tolerance 0<tol<a0 < \text{tol} < a, the polygon of POLYLINE has nn vertices on the ellipse, with nn the least integer at least 3 such that a(1−cos⁡(π/n))≤tola(1 - \cos(\pi/n)) \le \text{tol}, and its Hausdorff distance from the ellipse is at most tol.
  4. The algorithm stops after O(∣T∣)O(|T|) exact operations for the tree and O(∣T∣∑ni)O(|T| \sum n_i) float operations for the polygons.

Step 1 (one leaf). Let p=(x,y,Z)p = (x, y, Z) and pˉ=(x,y,1)\bar p = (x, y, 1). Write p^TQp^=∑i,jQijp^ip^j\hat p^{\mathsf T} Q \hat p = \sum_{i, j} Q_{ij} \hat p_i \hat p_j and split the indices into {1,2}\{1, 2\}, {3}\{3\} and {4}\{4\}, with p^3=Z\hat p_3 = Z and p^4=1\hat p_4 = 1. The terms with i,j≤2i, j \le 2 give ∑i,j≤2Qijpˉipˉj\sum_{i,j \le 2} Q_{ij} \bar p_i \bar p_j. The terms with one index i≤2i \le 2 and the other in {3,4}\{3, 4\} give 2∑i≤2(Qi3Z+Qi4)pˉi2 \sum_{i \le 2} (Q_{i3} Z + Q_{i4}) \bar p_i, by symmetry of QQ. The terms with both indices in {3,4}\{3, 4\} give Q33Z2+2Q34Z+Q44Q_{33} Z^2 + 2 Q_{34} Z + Q_{44}. This sum is pˉTMpˉ\bar p^{\mathsf T} M \bar p term by term. So p^TQp^=pˉTMpˉ\hat p^{\mathsf T} Q \hat p = \bar p^{\mathsf T} M \bar p for every (x,y)(x, y), and CM=SQ∩ΠZC_M = S_Q \cap \Pi_Z. The entries of MM are sums and products of entries of QQ and of ZZ, so they are rational when the input is rational.

Step 2 (the tree). By induction on TT. For a leaf this is step 1. For an inner node, intersection with a fixed set distributes over the three operations:

(A∪B)∩Π=(A∩Π)∪(B∩Π),(A∩B)∩Π=(A∩Π)∩(B∩Π),(A∖B)∩Π=(A∩Π)∖(B∩Π).(A \cup B) \cap \Pi = (A \cap \Pi) \cup (B \cap \Pi),\quad (A \cap B) \cap \Pi = (A \cap \Pi) \cap (B \cap \Pi),\quad (A \setminus B) \cap \Pi = (A \cap \Pi) \setminus (B \cap \Pi).

With the induction hypothesis for T1T_1 and T2T_2 this gives S(TZ)=S(T)∩ΠZS(T_Z) = S(T) \cap \Pi_Z. This proves claim 1.

The claim is about the plain set operations. A CAD kernel uses regularized operations, which take the closure of the interior of the result. Regularization does not commute with the section. The ball x2+y2+z2≤25x^2 + y^2 + z^2 \le 25 meets the plane z=5z = 5 in the single point (0,0)(0, 0), and its leaf conic is x2+y2≤0x^2 + y^2 \le 0, which is that point. The regularized 2D set of a point is empty. So at a plane that touches a face, the exact set of claim 1 can have parts of lower dimension, and the printer must drop them. The membership test of the code is the set of claim 1.

Step 3 (CLASSIFY). Write the conic as f(x)=xTAx+2bTx+f0f(x) = x^{\mathsf T} A x + 2 b^{\mathsf T} x + f_0 with AA the 2×22 \times 2 block, b=(M13,M23)b = (M_{13}, M_{23}) and f0=M33f_0 = M_{33}. If det⁡A≠0\det A \ne 0, the gradient 2(Ax+b)2(A x + b) is zero exactly at c=−A−1bc = -A^{-1} b, which is the formula of the code by Cramer's rule. Substitute x=c+wx = c + w: f=wTAw+2wT(Ac+b)+cTAc+2bTc+f0=wTAw+fcf = w^{\mathsf T} A w + 2 w^{\mathsf T}(A c + b) + c^{\mathsf T} A c + 2 b^{\mathsf T} c + f_0 = w^{\mathsf T} A w + f_c, because Ac+b=0A c + b = 0 and cTAc=−bTcc^{\mathsf T} A c = -b^{\mathsf T} c, so fc=f0+bTcf_c = f_0 + b^{\mathsf T} c. If det⁡A>0\det A > 0 and A11>0A_{11} > 0, then AA is positive definite and {wTAw≤−fc}\{w^{\mathsf T} A w \le -f_c\} is an ellipse with center cc if fc<0f_c < 0, the point cc if fc=0f_c = 0, and empty if fc>0f_c > 0. In the orthonormal eigenbasis of AA the set is λ1w12+λ2w22≤−fc\lambda_1 w_1^2 + \lambda_2 w_2^2 \le -f_c, so the squared semi-axes are −fc/λ1-f_c/\lambda_1 and −fc/λ2-f_c/\lambda_2. Their product is fc2/det⁡Af_c^2 / \det A and their sum is −fctr⁡(A)/det⁡A-f_c \operatorname{tr}(A) / \det A, both rational. This proves claim 2. The other types are reported but give no loop in the code.

Step 4 (the polygon). Let the ellipse be E={c+Lu:∣u∣=1}E = \{c + L u : |u| = 1\} with L=[a1e1, a2e2]L = [a_1 e_1,\ a_2 e_2], e1⊥e2e_1 \perp e_2 unit vectors and a=a1≥a2a = a_1 \ge a_2. Then ∣Lv∣≤a∣v∣|L v| \le a |v| for every vv. The polygon PP has the vertices c+Lukc + L u_k with uk=(cos⁡(2πk/n),sin⁡(2πk/n))u_k = (\cos(2\pi k/n), \sin(2\pi k/n)), so its vertices are on EE, and PP is the image under x↦c+Lxx \mapsto c + L x of the regular nn-gon P0P_0 inscribed in the unit circle.

Pair each point of the unit circle with a point of P0P_0 along the same ray from the origin. On the arc between uku_k and uk+1u_{k+1}, the point at angle θ\theta from the middle of the arc, with ∣θ∣≤π/n|\theta| \le \pi/n, pairs with the point of the chord at distance ρ=cos⁡(π/n)/cos⁡θ\rho = \cos(\pi/n)/\cos\theta from the origin, and cos⁡(π/n)≤ρ≤1\cos(\pi/n) \le \rho \le 1. This pairing is a bijection between the circle and the boundary of P0P_0, because every ray from the origin meets each of them once. For a pair (u,ρu)(u, \rho u) the image points differ by L((1−ρ)u)L((1 - \rho) u), of length at most a(1−ρ)≤a(1−cos⁡(π/n))a(1 - \rho) \le a(1 - \cos(\pi/n)). So every point of EE has a point of PP within that distance, and every point of PP has a point of EE within it. The Hausdorff distance is at most a(1−cos⁡(π/n))a(1 - \cos(\pi/n)), which is at most tol by the choice of nn. For tol <a< a the value 1−tol/a1 - \text{tol}/a is in (0,1)(0, 1), the smallest real nn with cos⁡(π/n)≥1−tol/a\cos(\pi/n) \ge 1 - \text{tol}/a is π/arccos⁡(1−tol/a)\pi / \arccos(1 - \text{tol}/a), and nn is its ceiling, at least 3. The code adds 1 to nn while the float test fails, which only increases nn. This proves claim 3.

Step 5 (termination and cost). SECTION does a fixed number of exact operations on one leaf, and lines L1 and L2 visit each node once. CLASSIFY is a fixed number of operations. Membership of one point visits each node once. POLYLINE makes nin_i vertices for leaf ii, and the trimming test of line L7 classifies each vertex against the tree in O(∣T∣)O(|T|) time. No step loops without bound, so the algorithm stops. This proves claim 4.

What is not proved. The trimming of line L7 keeps the vertices that are on the boundary of the layer. It works with floats and a small ε\varepsilon, and near a point where two conics cross, the kept run ends at the last vertex before the crossing, up to one edge away from it. The exact crossing points are the roots of a quartic and are not computed here. The bound of claim 3 is for a full ellipse, not for a trimmed run.

Complexity

For one layer, line L1 does a fixed number of exact operations per leaf, so the conic tree costs O(t)O(t), and kk layers cost O(kt)O(k t). The rational numbers grow with the size of the input fractions and of ZZ, not with the number of layers, because each layer starts again from QQ. Testing one point against TZT_Z costs O(t)O(t).

The polygon of an ellipse with largest semi-axis aa has n=⌈π/arccos⁡(1−tol/a)⌉≈πa/(2 tol)n = \lceil \pi / \arccos(1 - \text{tol}/a) \rceil \approx \pi \sqrt{a / (2\,\text{tol})} vertices, because 1−cos⁡x≈x2/21 - \cos x \approx x^2/2. A tolerance 10 times smaller needs about 10≈3.2\sqrt{10} \approx 3.2 times more vertices: for a=93.75a = \sqrt{93.75} the counts are 22, 70 and 219 for tol 0.1, 0.01 and 0.001. Trimming tests each vertex against the tree, so nn output vertices over all layers cost O(tn)O(t n). A mesh slicer runs in time linear in the number of triangles, but the mesh must be fine everywhere to be accurate on the worst layer.

For NURBS faces the cost depends on the intersection method and the tolerance, and no simple bound covers it.

Properties

  • No tessellation error. The layer is the exact section of the model. For quadric solids it is exact in rational arithmetic.
  • Error chosen per layer. The only approximation is the polygon output, with an error bound that the user sets, and it can change from layer to layer.
  • No mesh repair. The input is a valid solid, so the gaps, flipped triangles and self intersections of bad STL files do not occur.
  • Depends on the CAD kernel. The slicer needs the CAD model or a STEP file, and a surface intersection routine for each face type.
  • Boundary cases. At a plane that touches a face, the exact section can contain points or curves of lower dimension, which regularization removes.

Variants and improvements

  • B-rep slicing. Jamieson and Hacker (1995) cut each face of the B-rep inside the CAD system, which gives the section curves of planes, quadrics and spline faces.
  • NURBS by ray casting. Starly and coauthors (2005) read NURBS faces from a STEP file and compute the contours as raster lines with ray casting, together with adaptive layer heights.
  • Adaptive direct slicing. The exact model gives the surface normal at each contour point, so the cusp height of adaptive slicing can be computed from the true surface instead of from triangle normals.
  • Implicit and volume models. A model given as an implicit surface or a signed distance field is sliced by contouring each plane of the field, for example with marching squares.
  • Curved layers. When the layers are not planes, the same idea cuts the model with a family of surfaces. See curved layer printing.

When to use it

Use direct slicing when the CAD model is available and the surface quality matters: large parts with gently sloped faces, where the error of the mesh near the flat regions shows on the layers, or parts for which a fine STL file would be very large. It also helps when the mesh export produces bad geometry. Use mesh slicing when only a mesh exists (scans, models from other tools), when the slicer must accept any input, or when the printer software only reads STL.

Pitfalls

  • Calling NURBS slicing exact. The section of a NURBS face is not a closed form curve. It is computed numerically to a tolerance. Direct slicing removes the error of the tessellation, not every error.
  • Float conics. Computing the conic coefficients in floats loses the exact type at tangent planes. A sphere cut at its pole can come out as a tiny ellipse or as empty.
  • Ignoring regularization. Point and curve parts of a section at a tangent plane must be removed before the path planner sees them.
  • Too few vertices for the large axis. The vertex count must use the largest semi-axis. Using the smaller one breaks the bound on long thin ellipses, for example the section of a steep cylinder.
  • Trimming by samples. A trimmed polygon run ends at a vertex near the crossing of two conics, not at the crossing. Compute the crossing points when the corners must be sharp.

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.

direct_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-slicing/. The authors are listed in prov/YQA8PY.jsonl.

"""Direct slicing of a CSG solid built from quadric half-spaces.

A leaf of the tree is a symmetric 4 x 4 matrix Q. A point p = (x, y, z) is
inside the leaf when X^T Q X <= 0 with X = (x, y, z, 1). Spheres, cylinders,
cones and planes are leaves of this form. Inner nodes are ("union", A, B),
("inter", A, B) and ("diff", A, B).

The plane z = Z cuts each leaf in a conic, given by the symmetric 3 x 3 matrix
M with [x y 1] M [x y 1]^T = X^T Q X. With rational input every entry of M is
rational, so the section is exact. The only approximation is the optional
polyline that is made for the printer, and its error is bounded by tol.
"""

import math
from fractions import Fraction as F

# ---------------------------------------------------------------- leaves


def sphere(center, r2):
    """Ball |p - c|^2 - r2 <= 0. r2 is the squared radius."""
    cx, cy, cz = (F(v) for v in center)
    q = [[F(0)] * 4 for _ in range(4)]
    for i in range(3):
        q[i][i] = F(1)
    q[0][3] = q[3][0] = -cx
    q[1][3] = q[3][1] = -cy
    q[2][3] = q[3][2] = -cz
    q[3][3] = cx * cx + cy * cy + cz * cz - F(r2)
    return q


def cylinder(point, axis, r2):
    """Infinite solid cylinder |p - a|^2 - ((p - a).u)^2 / |u|^2 - r2 <= 0."""
    p = [F(v) for v in point]
    a = [F(v) for v in axis]
    n2 = sum(v * v for v in a)
    if n2 == 0:
        raise ValueError("zero axis")
    # quadratic part I - a a^T / |a|^2
    m = [[(F(1) if i == j else F(0)) - a[i] * a[j] / n2 for j in range(3)] for i in range(3)]
    mp = [sum(m[i][j] * p[j] for j in range(3)) for i in range(3)]
    q = [[F(0)] * 4 for _ in range(4)]
    for i in range(3):
        for j in range(3):
            q[i][j] = m[i][j]
        q[i][3] = q[3][i] = -mp[i]
    q[3][3] = sum(p[i] * mp[i] for i in range(3)) - F(r2)
    return q


def half_space(normal, offset):
    """Half-space n.p - offset <= 0, a quadric with no quadratic part."""
    n = [F(v) for v in normal]
    q = [[F(0)] * 4 for _ in range(4)]
    for i in range(3):
        q[i][3] = q[3][i] = n[i] / 2
    q[3][3] = -F(offset)
    return q


def quadric_value(q, p):
    x = [F(p[0]), F(p[1]), F(p[2]), F(1)]
    return sum(x[i] * q[i][j] * x[j] for i in range(4) for j in range(4))


def inside_3d(tree, p):
    """Exact membership of a 3D point, used as the reference."""
    if tree[0] == "leaf":
        return quadric_value(tree[1], p) <= 0
    a, b = inside_3d(tree[1], p), inside_3d(tree[2], p)
    return combine(tree[0], a, b)


def combine(op, a, b):
    if op == "union":
        return a or b
    if op == "inter":
        return a and b
    if op == "diff":
        return a and not b
    raise ValueError(op)


# ---------------------------------------------------------------- section


def section(q, z):
    """The conic matrix M of the leaf q on the plane z = Z. Exact."""
    z = F(z)
    m = [[F(0)] * 3 for _ in range(3)]
    for i in range(2):
        for j in range(2):
            m[i][j] = q[i][j]
        m[i][2] = m[2][i] = q[i][2] * z + q[i][3]
    m[2][2] = q[2][2] * z * z + 2 * q[2][3] * z + q[3][3]
    return m


def slice_tree(tree, z):
    """Lines L1 and L2: replace every quadric leaf by its conic."""
    if tree[0] == "leaf":
        return ("leaf", section(tree[1], z))  # @line L1
    return (tree[0], slice_tree(tree[1], z), slice_tree(tree[2], z))


def conic_value(m, p):
    x = [F(p[0]), F(p[1]), F(1)]
    return sum(x[i] * m[i][j] * x[j] for i in range(3) for j in range(3))


def inside_2d(tree2, p):
    """Exact membership of a point of the layer."""
    if tree2[0] == "leaf":
        return conic_value(tree2[1], p) <= 0
    return combine(tree2[0], inside_2d(tree2[1], p), inside_2d(tree2[2], p))


def classify(m):
    """Line L5. Return (kind, center, fc, det) for a conic matrix.

    det is the determinant of the 2 x 2 block, center solves the 2 x 2 system
    when det != 0, and fc is the value of the conic at the center. Kinds:
    "ellipse", "point", "empty" (positive definite block), "hyperbola",
    "line pair", "parabolic" (det = 0), "complement" (negative definite block:
    the region f <= 0 lies outside an ellipse, or is the whole plane).
    """
    a, b, c = m[0][0], m[0][1], m[1][1]
    d, e, f = m[0][2], m[1][2], m[2][2]
    det = a * c - b * b
    if det == 0:  # @line L9
        return ("parabolic", None, None, det)
    cx = (b * e - c * d) / det
    cy = (b * d - a * e) / det
    fc = f + d * cx + e * cy  # @line L10
    if det > 0 and a > 0:  # @line L11
        kind = "ellipse" if fc < 0 else ("point" if fc == 0 else "empty")
    elif det > 0:  # @line L12
        kind = "complement"
    else:
        kind = "line pair" if fc == 0 else "hyperbola"
    return (kind, (cx, cy), fc, det)


def ellipse_axes(m):
    """Squared semi-axes and unit axis directions of an ellipse (floats).

    The squared semi-axes are -fc / lambda_i, where lambda_i are the
    eigenvalues of the 2 x 2 block.
    """
    kind, center, fc, det = classify(m)
    if kind != "ellipse":
        raise ValueError("not an ellipse: " + kind)
    a, b, c = float(m[0][0]), float(m[0][1]), float(m[1][1])
    mean = (a + c) / 2
    rad = math.hypot((a - c) / 2, b)
    lam1, lam2 = mean - rad, mean + rad  # lam1 <= lam2, both > 0
    if b == 0 and a <= c:
        v1 = (1.0, 0.0)
    elif b == 0:
        v1 = (0.0, 1.0)
    else:
        v1 = (lam1 - c, b)
        n = math.hypot(*v1)
        v1 = (v1[0] / n, v1[1] / n)
    v2 = (-v1[1], v1[0])
    s1, s2 = -float(fc) / lam1, -float(fc) / lam2  # s1 >= s2
    return (float(center[0]), float(center[1])), s1, s2, v1, v2


def vertex_count(a, tol):
    """The least n >= 3 with a (1 - cos(pi / n)) <= tol."""
    if tol >= a:
        return 3
    n = math.ceil(math.pi / math.acos(1 - tol / a))
    n = max(3, n)
    while a * (1 - math.cos(math.pi / n)) > tol:  # guard against rounding
        n += 1
    return n


def ellipse_polyline(m, tol):
    """Line L6. A closed polygon with vertices on the ellipse and
    Hausdorff distance at most tol from it."""
    (cx, cy), s1, s2, v1, v2 = ellipse_axes(m)
    a1, a2 = math.sqrt(s1), math.sqrt(s2)
    n = vertex_count(a1, tol)  # @line L13
    pts = []
    for k in range(n):  # @line L14
        t = 2 * math.pi * k / n
        u, w = a1 * math.cos(t), a2 * math.sin(t)
        pts.append((cx + u * v1[0] + w * v2[0], cy + u * v1[1] + w * v2[1]))
    return pts


# ------------------------------------------------- boundary classification

IN, ON, OUT = -1, 0, 1


def _combine3(op, a, b):
    if op == "union":
        if IN in (a, b):
            return IN
        return OUT if a == b == OUT else ON
    if op == "inter":
        if OUT in (a, b):
            return OUT
        return IN if a == b == IN else ON
    if op == "diff":
        return _combine3("inter", a, -b)
    raise ValueError(op)


def classify_point(tree2, p, leaf, eps):
    """Three-valued membership, with the given leaf forced to ON.

    Other leaves are ON when |f| <= eps, so a point on two conics at once is
    ON. Two ON values in a union give ON, which is right for contours that
    cross but not for two solids that touch along a curve.
    """
    if tree2[0] == "leaf":
        if tree2 is leaf:
            return ON
        v = conic_value_float(tree2[1], p)
        return ON if abs(v) <= eps else (IN if v < 0 else OUT)
    return _combine3(tree2[0], classify_point(tree2[1], p, leaf, eps), classify_point(tree2[2], p, leaf, eps))


def conic_value_float(m, p):
    x = (p[0], p[1], 1.0)
    return sum(x[i] * float(m[i][j]) * x[j] for i in range(3) for j in range(3))


def leaves(tree2):
    if tree2[0] == "leaf":
        return [tree2]
    return leaves(tree2[1]) + leaves(tree2[2])


def direct_slice(tree, z, tol, eps=1e-12):
    """DIRECT-SLICE. Return the exact conic tree of the layer and the
    contour pieces as lists of points (open runs, or closed loops with the
    first point repeated at the end)."""
    tree2 = slice_tree(tree, z)  # @line L2
    contours = []  # @line L3
    for leaf in leaves(tree2):  # @line L4
        kind = classify(leaf[1])[0]  # @line L5
        if kind != "ellipse":
            continue  # points, empty sets and unbounded conics give no loop here
        poly = ellipse_polyline(leaf[1], tol)  # @line L6
        keep = [classify_point(tree2, p, leaf, eps) == ON for p in poly]  # @line L7
        if all(keep):
            contours.append(poly + [poly[0]])
            continue
        n = len(poly)
        start = keep.index(False)
        run = []
        for k in range(1, n + 1):
            i = (start + k) % n
            if keep[i]:
                run.append(poly[i])
            elif run:
                contours.append(run)
                run = []
        if run:
            contours.append(run)
    return tree2, contours  # @line L8


# --------------------------------------------- mesh slice, for comparison


def uv_sphere_section_radii(r, rings, segments, z):
    """Slice a UV-sphere mesh of radius r at height z (|z| < r, z not at a
    ring). Return (min, max) distance from the axis to the polygon of the
    section. The true section is a circle of radius sqrt(r^2 - z^2)."""
    lats = [math.pi * k / rings - math.pi / 2 for k in range(rings + 1)]
    zs = [r * math.sin(t) for t in lats]
    k = max(i for i in range(rings) if zs[i] < z)
    r0, r1 = r * math.cos(lats[k]), r * math.cos(lats[k + 1])
    t = (z - zs[k]) / (zs[k + 1] - zs[k])
    rho = r0 + t * (r1 - r0)  # the section is a regular polygon with this circumradius
    return rho * math.cos(math.pi / segments), rho
test_direct_slicing.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-slicing/. The authors are listed in prov/YQA8PY.jsonl.

import math
import random
from fractions import Fraction as F

from direct_slicing import (
    classify,
    cylinder,
    direct_slice,
    ellipse_axes,
    ellipse_polyline,
    half_space,
    inside_2d,
    inside_3d,
    section,
    slice_tree,
    sphere,
    uv_sphere_section_radii,
    vertex_count,
)


def test_sphere_slice_is_the_closed_form_circle() -> None:
    rng = random.Random(1)
    for _ in range(200):
        c = [F(rng.randint(-20, 20), rng.randint(1, 5)) for _ in range(3)]
        r2 = F(rng.randint(1, 400), rng.randint(1, 4))
        z = F(rng.randint(-100, 100), rng.randint(1, 7))
        kind, center, fc, det = classify(section(sphere(c, r2), z))
        want = r2 - (z - c[2]) ** 2
        if want > 0:
            assert kind == "ellipse"
            assert center == (c[0], c[1])
            assert det == 1 and -fc == want  # radius^2 = R^2 - (Z - c_z)^2, exactly
        elif want == 0:
            assert kind == "point" and center == (c[0], c[1])
        else:
            assert kind == "empty"


def test_sphere_pole_gives_a_point() -> None:
    kind, center, fc, _ = classify(section(sphere((0, 0, 0), 25), 5))
    assert kind == "point" and center == (0, 0) and fc == 0
    kind, _, fc, _ = classify(section(sphere((0, 0, 0), 25), 3))
    assert kind == "ellipse" and -fc == 16


def test_cylinder_slice_is_the_closed_form_ellipse() -> None:
    rng = random.Random(2)
    for _ in range(200):
        p = [F(rng.randint(-10, 10)) for _ in range(3)]
        a = [F(rng.randint(-4, 4)) for _ in range(2)] + [F(rng.choice([-3, -2, -1, 1, 2, 3]))]
        r2 = F(rng.randint(1, 50), rng.randint(1, 3))
        z = F(rng.randint(-30, 30), rng.randint(1, 4))
        kind, center, fc, det = classify(section(cylinder(p, a, r2), z))
        assert kind == "ellipse"
        t = (z - p[2]) / a[2]  # the axis meets the plane at p + t a
        assert center == (p[0] + t * a[0], p[1] + t * a[1])
        n2 = sum(v * v for v in a)
        # squared semi-axes r^2 and r^2 |a|^2 / a_z^2
        s1, s2 = r2 * n2 / a[2] ** 2, r2
        assert det == a[2] ** 2 / n2  # eigenvalues 1 and a_z^2 / |a|^2
        assert fc * fc / det == s1 * s2  # product of the squared semi-axes
        trace = section(cylinder(p, a, r2), z)[0][0] + section(cylinder(p, a, r2), z)[1][1]
        assert -fc * trace / det == s1 + s2  # sum of the squared semi-axes
        _, f1, f2, _, _ = ellipse_axes(section(cylinder(p, a, r2), z))
        assert math.isclose(f1, float(s1), rel_tol=1e-9) and math.isclose(f2, float(s2), rel_tol=1e-9)


def test_vertical_cylinder_has_the_same_circle_on_every_layer() -> None:
    q = cylinder((1, 2, 0), (0, 0, 1), 9)
    for z in range(-5, 6):
        kind, center, fc, det = classify(section(q, z))
        assert (kind, center, -fc, det) == ("ellipse", (1, 2), 9, 1)


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        k = rng.randrange(3)
        if k == 0:
            q = sphere([rng.randint(-3, 3) for _ in range(3)], rng.randint(1, 16))
        elif k == 1:
            q = cylinder([rng.randint(-3, 3) for _ in range(3)], [rng.randint(-2, 2), rng.randint(-2, 2), rng.randint(1, 2)], rng.randint(1, 9))
        else:
            q = half_space([rng.randint(-2, 2) for _ in range(3)], rng.randint(-3, 3))
        return ("leaf", q)
    op = rng.choice(["union", "inter", "diff"])
    return (op, random_tree(rng, depth - 1), random_tree(rng, depth - 1))


def test_layer_membership_equals_solid_membership() -> None:
    rng = random.Random(3)
    for _ in range(60):
        tree = random_tree(rng, 3)
        z = F(rng.randint(-12, 12), 4)
        tree2 = slice_tree(tree, z)
        for _ in range(40):
            x, y = F(rng.randint(-24, 24), 4), F(rng.randint(-24, 24), 4)
            assert inside_2d(tree2, (x, y)) == inside_3d(tree, (x, y, z))


def dist_point_segment(p, a, b):
    ax, ay = b[0] - a[0], b[1] - a[1]
    t = ((p[0] - a[0]) * ax + (p[1] - a[1]) * ay) / (ax * ax + ay * ay)
    t = max(0.0, min(1.0, t))
    return math.hypot(p[0] - a[0] - t * ax, p[1] - a[1] - t * ay)


def test_polyline_error_is_within_tolerance() -> None:
    q = cylinder((0, 0, 0), (1, 1, 2), 4)
    m = section(q, F(1, 3))
    (cx, cy), s1, s2, v1, v2 = ellipse_axes(m)
    a1, a2 = math.sqrt(s1), math.sqrt(s2)
    for tol in (0.5, 0.1, 0.01, 0.001):
        poly = ellipse_polyline(m, tol)
        n = len(poly)
        assert n == vertex_count(a1, tol)
        for p in poly:  # vertices lie on the ellipse
            assert abs(float(sum(x * float(m[i][j]) * y for i, x in enumerate((p[0], p[1], 1.0)) for j, y in enumerate((p[0], p[1], 1.0))))) < 1e-9
        worst = 0.0
        for k in range(20 * n):  # ellipse to polygon
            t = 2 * math.pi * k / (20 * n)
            u, w = a1 * math.cos(t), a2 * math.sin(t)
            e = (cx + u * v1[0] + w * v2[0], cy + u * v1[1] + w * v2[1])
            worst = max(worst, min(dist_point_segment(e, poly[i], poly[(i + 1) % n]) for i in range(n)))
        assert worst <= tol + 1e-12
        if n > 3:  # one vertex fewer would break the bound
            assert a1 * (1 - math.cos(math.pi / (n - 1))) > tol


def test_trimmed_contours_lie_on_the_boundary() -> None:
    # a ball minus a vertical hole: the layer is an annulus with two loops
    tree = ("diff", ("leaf", sphere((0, 0, 0), 100)), ("leaf", cylinder((0, 0, 0), (0, 0, 1), 9)))
    tree2, contours = direct_slice(tree, 6, 0.01)
    assert len(contours) == 2
    radii = sorted(round(math.hypot(*c[0]), 9) for c in contours)
    assert radii == [3.0, 8.0]  # 8 = sqrt(100 - 36)
    # two overlapping balls: each circle keeps only its outer arc
    tree = ("union", ("leaf", sphere((0, 0, 0), 25)), ("leaf", sphere((6, 0, 0), 25)))
    tree2, contours = direct_slice(tree, 0, 0.001)
    assert len(contours) == 2
    for run in contours:
        for p in run:
            d0, d1 = math.hypot(p[0], p[1]), math.hypot(p[0] - 6, p[1])
            assert min(abs(d0 - 5), abs(d1 - 5)) < 1e-9  # on one circle
            assert min(d0, d1) >= 5 - 1e-9  # and not inside the other ball


def test_mesh_slice_has_chordal_error_and_direct_slice_has_none() -> None:
    lo, hi = uv_sphere_section_radii(10.0, 16, 32, 2.5)
    true = math.sqrt(100 - 2.5**2)
    assert 0.08 < true - lo < 0.09  # the mesh section misses the circle by 0.0876
    lo, hi = uv_sphere_section_radii(10.0, 16, 32, -9.95)
    assert math.sqrt(100 - 9.95**2) - hi > 0.4  # near the pole the error is ten times larger
    kind, center, fc, _ = classify(section(sphere((0, 0, 0), 100), F(5, 2)))
    assert kind == "ellipse" and -fc == F(375, 4)  # exactly true^2

History

Guduri, Crawford and Beaman (1992, 1993) described the exact contours of CSG solids built from quadric primitives at the Solid Freeform Fabrication Symposium in Austin. Jamieson and Hacker (1995) sliced the B-rep inside the CAD system and avoided the STL file, which gave the method its name. Later work moved the method to exchange formats: Starly, Lau, Sun, Lau and Bradbury (2005) sliced NURBS models read from STEP files. Most printer software still slices meshes, because the input is usually an STL or 3MF file.

References

  1. Sashidhar Guduri, Richard H. Crawford and Joseph J. Beaman, A method to generate exact contour files for solid freeform fabrication, Solid Freeform Fabrication Symposium 1992, University of Texas at Austin, 95 to 101, exact contours of CSG solids built from quadric primitives
  2. Sashidhar Guduri, Richard H. Crawford and Joseph J. Beaman, Direct generation of contour files from constructive solid geometry representations, Solid Freeform Fabrication Symposium 1993, University of Texas at Austin, 291 to 302, the contours of a layer computed from the CSG tree without a tessellation (general locator)
  3. Ron Jamieson and Herbert Hacker, Direct slicing of CAD models for rapid prototyping, Rapid Prototyping Journal 1(2), 1995, 4 to 12, slicing the B-rep model inside the CAD system, with the plane section of each face, instead of an STL file
  4. Binil Starly, Alan Lau, Wei Sun, Wing Lau and Tom Bradbury, Direct slicing of STEP based NURBS models for layered manufacturing, Computer-Aided Design 37(4), 2005, 387 to 397, the contours of NURBS faces read from a STEP file, computed by ray casting along raster lines, with adaptive layer thickness

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.conic_trees
  • a full proof of time.polygons
  • 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