Algorithmcore
Triangle mesh slicing
Also called plane mesh slicing, contour construction.
Intersects each triangle with the planes it spans and links the segments into oriented polygons with a hash of endpoints, in O(n log k + k + m) time.
- Time
- O(n log k + k + m log m) worstO(n log k + k + m) expected
- Space
- O(n + k) extra
- Where
- k = number of slicing planes; m = number of triangle-plane segments; n = number of triangles
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rodrigo Minetto, Neri Volpato, Jorge Stolfi, Rodrigo M. M. H. Gregori, Murilo V. G. da Silva, 2017
Triangle mesh slicing cuts a closed triangle mesh with the horizontal planes and returns, for each plane, the closed polygons where the plane meets the solid. Each triangle that crosses a plane gives one segment. The segments of one plane are then linked end to end into loops. The method on this page is the one of Minetto, Volpato, Stolfi, Gregori and da Silva (2017). It puts each triangle into the bucket of the first plane above its lowest vertex with a binary search, sweeps the planes from the bottom up with a list of active triangles, and links the segments with a hash table keyed by the crossed mesh edge. It runs in expected time for triangles and segments, which matches their lower bound. It is the first step of most slicers for additive manufacturing.
In plain words
Think of a model made of many small flat triangles, like a paper shell. You cut it with flat horizontal knives at different heights, and for each knife you want the outline of the cut.
A triangle meets a knife only if the knife is between its lowest and its highest corner. So go up through the knives one by one, and keep a list of the triangles that the current knife can touch. Add a triangle when the knives reach its lowest corner, and drop it when they pass its highest corner.
Each touched triangle gives one short straight piece of the outline. Pieces from neighbouring triangles meet on their common edge, so a table keyed by edges gives the next piece. Follow the pieces until you come back to the start, and you have one closed outline.
The problem
The input is a mesh with vertices and triangles given as index triples, an indexed face set. The mesh is closed, oriented and edge-manifold: each edge belongs to exactly two triangles, and they traverse it in opposite directions. Each triangle is listed counterclockwise as seen from outside, so its normal points out by the right-hand rule. The input also has plane heights .
The output is, for each , a set of closed polygons in the plane . They are the boundary of the cross-section of the solid, with the solid on the left of each directed segment: outer loops run counterclockwise as seen from above, and holes run clockwise. This is the convention of polygon orientation and of polygons with holes. The total shoelace area of the loops of one plane is then the area of the cross-section.
Degenerate cases. A vertex can lie exactly at a plane height, an edge can lie in a plane, and a whole face can lie in a plane. Real models have many such cases, because layer heights are round numbers and so are the coordinates of flat faces. The rule of this page treats them as part of the input: a vertex with counts as above the plane. This is the same as moving the plane to for an infinitely small , a simple form of simulation of simplicity. With the rule, a triangle crosses the plane exactly when , it has then exactly one vertex alone on its side, and it gives exactly one segment. A face that lies in the plane gives no segment.
The algorithm
For a triangle and a height , CROSS marks each vertex as above () or below (). In the cyclic order of , exactly one edge goes from an above vertex to a below vertex, and exactly one edge goes from below to above. CROSS returns , the point where meets the plane, and . An edge key is the unordered pair of its vertex indices. For the edge from to , , and because one end is above and the other below. The segment of runs from to the point on .
SLICE(V, T, Z) ▷ mesh (V, T), heights Z[1] < ... < Z[k]- 1
B[1..k+1] ← empty lists - 2
for each triangle t ∈ T do - 3
j ← number of i with Z[i] ≤ zmin(t) ▷ binary search - 4
append t to B[j + 1] ▷ first plane above zmin(t) - 5
A ← empty list ▷ active triangles - 6
for j ← 1 to k do - 7
A ← A + B[j] - 8
remove from A each t with zmax(t) < Z[j] - 9
S ← empty hash table ▷ edge key → (point, edge key) - 10
for each t ∈ A do - 11
(e_out, p, e_in) ← CROSS(t, Z[j]) - 12
S[e_out] ← (p, e_in) - 13
P[j] ← LINK(S) - 14
return P[1..k] LINK(S)- 15
C ← empty list - 16
while S is not empty do - 17
e0 ← any key of S; e ← e0; L ← empty loop - 18
repeat - 19
(p, e') ← S[e]; delete S[e]; append p to L; e ← e' - 20
until e = e0 - 21
append L to C - 22
return C
Lines L1 to L4 put each triangle into the bucket of the first plane strictly above its lowest vertex. Line L8 drops the triangles whose highest vertex is below the plane. After line L8, a triangle is in exactly when , so every triangle in crosses the plane. Line L12 files the segment of under the edge where it starts. The segment that follows it in the loop starts where it ends, on the edge , so line L19 finds it with one lookup.
The key is the edge and not the point. A vertex on the plane is the crossing point of several edges, so points are not unique keys there, but edges are. The loop then contains the vertex more than once, and a triangle with a vertex on the plane and an edge with both ends at the same side can give a segment of length zero. A later pass can remove repeated points. They do not change the area or the orientation of the loop.
Exact arithmetic. The only predicate is the comparison of two input numbers, so the topology of the loops is exact even in floating point, if each plane height is one stored number and each vertex has one stored . The points are constructions. With integer or rational input and exact geometric computation they are exact rationals, as in the code of this page. In floating point they are rounded, and the result depends on the direction of the edge. For the edge from to and , the formula from gives , and the same formula from gives . A slicer that links segments by equal points then breaks a loop at such an edge. Edge keys avoid this, and so does computing each crossing point once per edge.
Example
Take the tetrahedron with , , and , with the faces , , and , all counterclockwise from outside (the signed volume is ). The planes are .
| step | value |
|---|---|
| L1 to L4 | . Buckets: , and because |
| , L10 to L12 | , , |
| , LINK | from : , back to . Area |
| is on the plane and counts as above. is not active. Loop , area | |
| , L7 | . No triangle is dropped, since |
| , L11 | gives a segment of length zero at . starts at , at , at |
| , LINK | , area |
| , L8 | is dropped, since . Loop , area |
All four loops are counterclockwise, as outer loops must be. At the cut points lie on the edges , and at the fractions , and , and the shoelace formula on them gives directly. At the loop is the triangle , , of area 9, with written twice.
Correctness
After line L8 the active list holds exactly the triangles with , because the planes increase, so a triangle that is dropped never crosses a later plane. Each such triangle has one or two above vertices and one or two below vertices, so its cyclic order has exactly one edge from above to below and one from below to above. A crossing edge belongs to two triangles that traverse it in opposite directions, so it is of one of them and of the other. The map from a segment to the segment that starts at its end edge is therefore a permutation of the segments of the plane, and LINK writes out its cycles, which are closed loops. A computation with the cross product shows that the outward normal of the triangle points to the right of its segment, so the solid is on the left. The full proof is below.
Proof: The bucket and sweep slicer returns closed loops with the solid on their leftfull
Claim. Let be a closed, oriented, edge-manifold triangle mesh: each edge belongs to exactly two triangles, one of them has right after in its cyclic order and the other has right after . Let , and let all coordinates be exact numbers. Then SLICE stops, and for each :
- every triangle with gives exactly one segment, and no other triangle gives one;
- LINK partitions these segments into closed loops, where each segment ends at the start of the next one;
- the horizontal part of the outward normal of each triangle points to the right of its segment, or the segment has length zero.
Here a vertex counts as above the plane when and below when .
Step 1 (the active list). Fix a triangle and let be the bucket of line L4, so is the number of planes with . Since the heights increase, holds exactly for . The triangle enters at step (line L7) and stays until the first step with (line L8). It never comes back, because implies for all . So after line L8 of step , if and only if and , that is, if and only if . If , the triangle is in the bucket , which the loop never reads, and indeed it crosses no plane.
Step 2 (one segment per active triangle). Let be active at step . The vertex of height is below and the vertex of height is above, so both labels occur. Go around the cycle . The label changes an even number of times, at least once, and at most three times, so exactly twice: once from above to below (the edge ) and once from below to above (the edge ). So CROSS is well defined, and on each of these two edges the heights of the ends differ, so the crossing point is defined. A triangle that is not active has all three labels equal and gives no segment. This proves part 1.
Step 3 (the successor map). Let be the set of edges with one end above and one end below. For every edge , both triangles of are active, since each has a vertex above and a vertex below. The two triangles traverse in opposite directions, so goes from above to below in exactly one of them and from below to above in the other. So is of exactly one segment and of exactly one segment. Line L12 therefore never writes a key twice, and the keys of are exactly . Define of the segment filed under . Each is of exactly one segment, so is a bijection of the finite set , a permutation.
The end point of the segment filed under is the crossing point of the edge , and the segment filed under starts at the crossing point of the same edge. The crossing point of an edge depends only on the edge and the plane: the formula of line L11 applied from either end gives the same exact point, because with and . So each segment ends where its successor starts.
Step 4 (LINK). Each pass of the repeat loop of lines L18 to L20 starts at a key and visits , deleting each key it reads. A permutation of a finite set is a union of disjoint cycles, so the sequence returns to after the length of the cycle of , and the keys are different from and from each other. They are all still in : a key leaves only when it is read, and the keys read in earlier passes belong to other cycles. So line L19 never reads a missing key, the pass stops with , and it has deleted exactly one cycle. Each pass deletes at least one key, so the outer loop stops after at most passes, and the passes write out every cycle once. By Step 3 consecutive points of a pass are the start and end of one segment, and the last segment ends at the first point. This proves part 2.
Step 5 (orientation). Let be active, with the outward normal for its cyclic order . A cyclic shift does not change , so let be the vertex that is alone on its side. Write and for the start and the end of the segment, , and .
Case 1: is below and , are above. Then goes from below to above, so , and goes from above to below, so , with . Then . Also with . Here because and lie in the plane, and . With ,
So , a positive multiple of turned clockwise by a right angle.
Case 2: is above and , are below. Then on the edge , and on the edge , with . If , then , , and the segment has length zero. Otherwise and . Now with and . So , again a positive multiple of turned clockwise.
In both cases the outward direction lies to the right of , so the inside of the solid lies to the left. This proves part 3.
Remark (area). Parts 2 and 3 say that the loops of plane are the boundary of the cross-section at height , traversed with the region on the left. By Green's theorem the sum of their shoelace areas is then the area of that cross-section. This step uses Green's theorem and is not proved here. The tests check the identity exactly on a cube, a tetrahedron and a square frame with a hole, and they check the inside and outside of random sample points against a vertical ray count in the mesh.
Termination. The loops of lines L2 and L6 are over finite lists, line L8 and line L10 scan the finite list , and Step 4 shows that LINK stops.
Complexity
Lines L1 to L4 take time for the binary searches and for the buckets. In the loop of line L6, every triangle is added once. At plane , line L8 scans triangles, and each of them is either dropped, which happens once per triangle, or kept and gives a segment. So all scans together take time. Lines L10 to L22 do hash operations per segment. With hashing, each operation takes expected time (see universal hashing), so the total is expected time. With a balanced search tree in place of the hash table, the same steps take time in the worst case.
When the planes are evenly spaced, , line L3 is the arithmetic , clamped to the range from to , and the first term becomes . Minetto et al. state for this case, and also when the triangles come sorted by their lowest vertex. They also prove a lower bound of in the worst case for planes with arbitrary spacing, so the method is asymptotically optimal. The extra space is for the buckets and the active list, and the table of one plane holds at most entries. The output itself has size .
Properties
- Exact. With integer or rational coordinates, every point and every area is exact, also when planes pass through vertices, edges or faces.
- Closed loops. On a closed, oriented, edge-manifold mesh, every loop is closed, and every segment is in exactly one loop.
- Oriented. The solid is on the left of every segment. Outer loops are counterclockwise and holes are clockwise as seen from , so the sum of signed areas is the area of the cross-section.
- One sided rule. A vertex on the plane counts as above, so the result is the cross-section at . The plane through the bottom face of a cube gives nothing, and the plane through the top face gives the full square.
- Output sensitive. The cost depends on , not on .
- Only one predicate. The topology depends only on comparisons of input heights.
Variants and improvements
- One plane at a time. The simplest slicer tests every triangle against every plane, in time. It is the brute force that the tests of this page compare against.
- Sorted triangles. Sorting the triangles by and sweeping gives . The buckets of line L4 replace the sort and give in place of .
- Interval structures. Each triangle is the interval , and a plane needs all intervals that contain it, a stabbing query in an interval tree or a segment tree. This also allows planes in any order, at a cost of per plane.
- Edge numbers. If the mesh is stored with numbered edges, for example in a doubly connected edge list, the table can be an array indexed by the edge number, a direct address table. Resetting only the entries in use gives the bound in the worst case.
- Meshes from STL. STL files store each triangle with its own three points and no shared indices. Vertex welding must first merge equal points into shared vertices. If the file has gaps or flipped faces, mesh repair and consistent orientation come first, or the loops do not close.
- Variable layers. Adaptive slicing chooses the heights from the surface slope. The method of this page then slices at those heights unchanged.
When to use it
Use it to turn a mesh into layer outlines for additive manufacturing, for the planar toolpaths of machining, or for cross-section views. It needs a watertight, consistently oriented mesh with shared vertices. If the mesh may have holes or self-intersections, repair it first, or use a method that does not rely on edge adjacency, such as sampling an inside test on a grid and tracing the result with marching squares. If you need only one plane, test each triangle once and skip the buckets.
Pitfalls
- Linking by points. Floating point crossing points depend on the direction of the edge, and a vertex on the plane is the end of several segments. Key the table by the edge.
- Epsilon shifts. Moving every plane by a fixed small number, such as , makes vertex hits rarer but not impossible, and the right value depends on the scale of the model. The symbolic rule handles every case.
- Rules that differ between triangles. If one triangle counts a vertex as above and its neighbour counts it as below, the loop breaks. The rule must depend on the vertex only.
- Unwelded meshes. A mesh read from STL has no shared vertices, so the edge keys of neighbouring triangles never match.
- Wrong orientation. One flipped face reverses its segment, and the successor lookup fails at both of its ends. Check orientation before slicing.
- Zero-length segments. Faces with a vertex on the plane give repeated points. They are harmless for areas, but they can upset an offset or a toolpath step that expects distinct points.
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/triangle-mesh-slicing/. The authors are listed in prov/ETJZAW.jsonl.
"""Slice a closed triangle mesh by horizontal planes into closed, oriented contours.
The method is the plane sweep of Minetto, Volpato, Stolfi, Gregori and da Silva
(2017). Each triangle goes into the bucket of the first plane above its lowest
vertex (binary search), the planes are swept from the bottom up with a list of
active triangles, and the segments of one plane are linked into loops with a
hash table keyed by the crossed mesh edge.
Input: vertices as (x, y, z) tuples of int or Fraction, faces as index triples
in counterclockwise order seen from outside (outward normal by the right-hand
rule), and strictly increasing plane heights. The mesh must be closed, oriented
and edge-manifold. A vertex at the height of a plane counts as above it, so the
plane z = Z acts as the plane z = Z - epsilon for a tiny epsilon > 0.
Output: for each plane, a list of loops, each a list of (x, y) points. Outer
loops are counterclockwise seen from above and holes are clockwise.
"""
from bisect import bisect_right
from fractions import Fraction
def crossing(vertices, face, z):
"""Return (e_out, p, e_in) for the face at height z, or None.
e_out is the edge that goes from above to below in the face order, p its
crossing point, and e_in the edge that goes from below to above. Edges are
keys (min index, max index).
"""
above = [vertices[v][2] >= z for v in face]
if all(above) or not any(above):
return None
e_out = e_in = p = None
for i in range(3):
a, b = face[i], face[(i + 1) % 3]
if above[i] and not above[(i + 1) % 3]:
e_out, p = (min(a, b), max(a, b)), edge_point(vertices[a], vertices[b], z)
elif not above[i] and above[(i + 1) % 3]:
e_in = (min(a, b), max(a, b))
return e_out, p, e_in
def edge_point(a, b, z):
"""Exact (x, y) where the segment ab meets the plane of height z (a[2] != b[2])."""
t = Fraction(z - a[2]) / (b[2] - a[2])
return (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)
def link(segments):
"""Link segments {e_out: (p, e_in)} into loops of points."""
loops = [] # @line L15
while segments: # @line L16
e0 = next(iter(segments)) # @line L17
e, loop = e0, []
while True: # @line L18
p, e = segments.pop(e) # @line L19
loop.append(p)
if e == e0: # @line L20
break
loops.append(loop) # @line L21
return loops # @line L22
def slice_mesh(vertices, faces, planes):
"""Return one list of loops for each plane height, in the order of planes."""
k = len(planes)
if any(planes[i] >= planes[i + 1] for i in range(k - 1)):
raise ValueError("plane heights must be strictly increasing")
zmin = [min(vertices[v][2] for v in f) for f in faces]
zmax = [max(vertices[v][2] for v in f) for f in faces]
buckets = [[] for _ in range(k + 1)] # @line L1
for t in range(len(faces)): # @line L2
j = bisect_right(planes, zmin[t]) # @line L3
buckets[j].append(t) # @line L4
active = [] # @line L5
result = []
for j in range(k): # @line L6
active.extend(buckets[j]) # @line L7
active = [t for t in active if zmax[t] >= planes[j]] # @line L8
segments = {} # @line L9
for t in active: # @line L10
e_out, p, e_in = crossing(vertices, faces[t], planes[j]) # @line L11
segments[e_out] = (p, e_in) # @line L12
result.append(link(segments)) # @line L13
return result # @line L14
def signed_area(loop):
"""Shoelace signed area of a closed loop of (x, y) points."""
s = 0
for i in range(len(loop)):
(x0, y0), (x1, y1) = loop[i], loop[(i + 1) % len(loop)]
s += x0 * y1 - x1 * y0
return Fraction(s) / 2
if __name__ == "__main__":
cube_v = [(x, y, z) for z in (0, 2) for y in (0, 2) for x in (0, 2)]
cube_f = [(0, 2, 1), (1, 2, 3), (4, 5, 6), (5, 7, 6), (0, 1, 4), (1, 5, 4),
(2, 6, 3), (3, 6, 7), (0, 4, 2), (2, 4, 6), (1, 3, 5), (3, 7, 5)]
for z, loops in zip([0, 1, 2], slice_mesh(cube_v, cube_f, [0, 1, 2])):
print(z, [[(str(x), str(y)) for x, y in lp] for lp in loops], [str(signed_area(lp)) for lp in loops])
test_triangle_mesh_slicing.py 284 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triangle-mesh-slicing/. The authors are listed in prov/ETJZAW.jsonl.
import random
from collections import Counter
from fractions import Fraction
import pytest
from triangle_mesh_slicing import crossing, edge_point, signed_area, slice_mesh
# ---- meshes ----
def box(x0, y0, z0, x1, y1, z1):
v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
f = [(0, 2, 1), (1, 2, 3), (4, 5, 6), (5, 7, 6), (0, 1, 4), (1, 5, 4),
(2, 6, 3), (3, 6, 7), (0, 4, 2), (2, 4, 6), (1, 3, 5), (3, 7, 5)]
return v, f
def tetrahedron():
v = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
f = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)]
return v, f
def ring_solid(rings, cap_low, cap_high, rng=None):
"""Closed mesh from horizontal rings of points around the z axis.
rings is a list of (z, [(x, y), ...]) with z strictly increasing and the
points in counterclockwise order. The caps are fans from (0, 0, cap_low)
and (0, 0, cap_high). If rng is given, each quad gets a random diagonal.
"""
v, f = [], []
c = len(rings[0][1])
for z, pts in rings:
v.extend((x, y, z) for x, y in pts)
idx = lambda i, j: i * c + (j % c)
for i in range(len(rings) - 1):
for j in range(c):
a, b, cc, d = idx(i, j), idx(i, j + 1), idx(i + 1, j + 1), idx(i + 1, j)
if rng is not None and rng.random() < 0.5:
f += [(a, b, d), (b, cc, d)]
else:
f += [(a, b, cc), (a, cc, d)]
lo, hi = len(v), len(v) + 1
v += [(0, 0, cap_low), (0, 0, cap_high)]
top = len(rings) - 1
for j in range(c):
f.append((lo, idx(0, j + 1), idx(0, j)))
f.append((hi, idx(top, j), idx(top, j + 1)))
return v, f
DIRS = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
def random_ring_solid(rng):
heights = sorted(rng.sample(range(0, 12), 4))
rings = [(z, [(r * dx, r * dy) for dx, dy in DIRS for r in [rng.randint(1, 4)]]) for z in heights]
low = heights[0] - rng.randint(0, 2)
high = heights[-1] + rng.randint(0, 2)
return ring_solid(rings, low, high, rng)
def frame():
"""Square frame [0,4]^2 minus [1,3]^2, height 2 (a torus, genus 1)."""
outer = [(0, 0), (4, 0), (4, 4), (0, 4)]
inner = [(1, 1), (3, 1), (3, 3), (1, 3)]
v = [(x, y, z) for z in (0, 2) for x, y in outer + inner]
O = lambda z, j: (0 if z == 0 else 8) + j % 4
I = lambda z, j: (0 if z == 0 else 8) + 4 + j % 4
f = []
for j in range(4):
f += [(O(0, j), O(0, j + 1), O(2, j + 1)), (O(0, j), O(2, j + 1), O(2, j))] # outer walls
f += [(I(0, j + 1), I(0, j), I(2, j)), (I(0, j + 1), I(2, j), I(2, j + 1))] # inner walls
f += [(O(2, j), O(2, j + 1), I(2, j + 1)), (O(2, j), I(2, j + 1), I(2, j))] # top
f += [(O(0, j + 1), O(0, j), I(0, j)), (O(0, j + 1), I(0, j), I(0, j + 1))] # bottom
return v, f
def check_closed_oriented(v, f):
directed = Counter()
for a, b, c in f:
for e in ((a, b), (b, c), (c, a)):
directed[e] += 1
assert all(n == 1 for n in directed.values())
assert all(directed[(b, a)] == 1 for a, b in directed)
# signed volume by the divergence theorem must be positive
vol = 0
for a, b, c in f:
p, q, r = v[a], v[b], v[c]
vol += (p[0] * (q[1] * r[2] - q[2] * r[1]) - p[1] * (q[0] * r[2] - q[2] * r[0])
+ p[2] * (q[0] * r[1] - q[1] * r[0]))
assert vol > 0
# ---- independent checks ----
def brute_segments(v, f, z):
"""Directed segments of every face at height z, without buckets or a sweep."""
out = Counter()
for face in f:
lo = min(v[i][2] for i in face)
hi = max(v[i][2] for i in face)
if not (lo < z <= hi):
continue
ends = {}
for i in range(3):
a, b = face[i], face[(i + 1) % 3]
sa, sb = v[a][2] >= z, v[b][2] >= z
if sa != sb:
ends["out" if sa else "in"] = edge_point(v[a], v[b], z)
out[(ends["out"], ends["in"])] += 1
return out
def loop_segments(loops):
out = Counter()
for lp in loops:
for i in range(len(lp)):
out[(lp[i], lp[(i + 1) % len(lp)])] += 1
return out
def orient2d(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def on_segment(p, a, b):
return (orient2d(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]))
def winding(p, loops):
w = 0
for lp in loops:
for i in range(len(lp)):
a, b = lp[i], lp[(i + 1) % len(lp)]
if a[1] <= p[1] < b[1] and orient2d(a, b, p) > 0:
w += 1
elif b[1] <= p[1] < a[1] and orient2d(a, b, p) < 0:
w -= 1
return w
def inside_by_vertical_ray(v, f, p, z):
"""Parity of the faces above (p, z - eps) on the vertical line through p.
Returns None if the line meets a face boundary, so the sample is skipped.
"""
count = 0
for face in f:
a, b, c = (v[i] for i in face)
a2, b2, c2 = a[:2], b[:2], c[:2]
area = orient2d(a2, b2, c2)
if any(on_segment(p, s, t) for s, t in ((a2, b2), (b2, c2), (c2, a2))):
return None
if area == 0:
continue
u, w, x = orient2d(b2, c2, p), orient2d(c2, a2, p), orient2d(a2, b2, p)
if (u > 0 and w > 0 and x > 0) or (u < 0 and w < 0 and x < 0):
h = (Fraction(u) * a[2] + Fraction(w) * b[2] + Fraction(x) * c[2]) / area
if h >= z:
count += 1
return count % 2 == 1
# ---- tests ----
def test_page_example_cube():
v, f = box(0, 0, 0, 2, 2, 2)
out = slice_mesh(v, f, [0, 1, 2])
assert out[0] == []
assert [signed_area(lp) for lp in out[1]] == [4]
assert [signed_area(lp) for lp in out[2]] == [4]
assert len(out[1][0]) == 8 # each side face gives one segment
def test_meshes_are_closed_and_oriented():
for v, f in [box(0, 0, 0, 2, 2, 2), tetrahedron(), frame()]:
check_closed_oriented(v, f)
rng = random.Random(5)
for _ in range(10):
check_closed_oriented(*random_ring_solid(rng))
def test_tetrahedron_area_exact():
v, f = tetrahedron()
zs = [Fraction(i, 7) for i in range(-1, 9)]
for z, loops in zip(zs, slice_mesh(v, f, zs)):
want = (1 - z) ** 2 / 2 if 0 < z <= 1 else 0
assert sum(signed_area(lp) for lp in loops) == want
assert len(loops) == (1 if 0 < z <= 1 else 0)
def test_frame_has_a_hole():
v, f = frame()
out = slice_mesh(v, f, [Fraction(1, 2), 1, 2])
for loops in out:
areas = sorted(signed_area(lp) for lp in loops)
assert areas == [-4, 16] # hole clockwise, outer counterclockwise
assert sum(areas) == 12
# Euler characteristic of the torus
edges = {tuple(sorted(e)) for a, b, c in f for e in ((a, b), (b, c), (c, a))}
assert len(v) - len(edges) + len(f) == 0
def test_against_direct_slicing():
rng = random.Random(11)
for _ in range(25):
v, f = random_ring_solid(rng)
zs = sorted({vz for _, _, vz in v} | {Fraction(rng.randrange(-6, 45), 3) for _ in range(6)})
out = slice_mesh(v, f, zs)
for z, loops in zip(zs, out):
assert loop_segments(loops) == brute_segments(v, f, z)
def test_every_contour_is_closed_and_consistent():
rng = random.Random(3)
for _ in range(25):
v, f = random_ring_solid(rng)
zs = sorted({vz for _, _, vz in v}) # planes through vertices only
for z, loops in zip(zs, slice_mesh(v, f, zs)):
for lp in loops:
assert len(lp) >= 2
segs = loop_segments(loops)
starts = Counter(s for s, _ in segs.elements())
ends = Counter(e for _, e in segs.elements())
assert starts == ends # every point is entered as often as it is left
def test_point_membership_against_vertical_rays():
rng = random.Random(7)
checked = 0
for _ in range(8):
v, f = random_ring_solid(rng)
zs = sorted({vz for _, _, vz in v} | {Fraction(rng.randrange(0, 36), 3) for _ in range(3)})
for z, loops in zip(zs, slice_mesh(v, f, zs)):
for _ in range(15):
p = (Fraction(rng.randrange(-4500, 4500), 997), Fraction(rng.randrange(-4500, 4500), 997))
inside = inside_by_vertical_ray(v, f, p, z)
if inside is None:
continue
if any(on_segment(p, lp[i], lp[(i + 1) % len(lp)]) for lp in loops for i in range(len(lp))):
continue
assert winding(p, loops) == (1 if inside else 0)
checked += 1
assert checked > 500
def test_vertex_on_plane_counts_as_above():
v, f = tetrahedron()
face = (0, 1, 3) # vertices at z = 0, 0, 1
assert crossing(v, face, 0) is None
e_out, p, e_in = crossing(v, face, 1)
assert p == (0, 0) # both crossing points are the apex
assert edge_point(v[0], v[3], 1) == (0, 0)
def test_planes_must_increase():
v, f = box(0, 0, 0, 1, 1, 1)
with pytest.raises(ValueError):
slice_mesh(v, f, [1, 1])
def test_float_points_depend_on_edge_direction():
"""Why loops are linked by edge keys and not by rounded points."""
rng = random.Random(1)
differ = 0
for _ in range(2000):
a = (rng.random(), rng.random(), rng.random())
b = (rng.random(), rng.random(), rng.random() + 1.0)
z = rng.uniform(a[2], b[2])
ta = (z - a[2]) / (b[2] - a[2])
tb = (z - b[2]) / (a[2] - b[2])
pa = (a[0] + (b[0] - a[0]) * ta, a[1] + (b[1] - a[1]) * ta)
pb = (b[0] + (a[0] - b[0]) * tb, b[1] + (a[1] - b[1]) * tb)
if pa != pb:
differ += 1
assert differ > 0
History
Slicers have cut triangle meshes into layers since the first stereolithography machines of the late 1980s, which read the STL format. For a long time the usual method tested each triangle against each plane, or sorted the triangles and swept, and linked the segments by comparing end points. Minetto, Volpato, Stolfi, Gregori and da Silva published the bucket and sweep method in Computer-Aided Design in 2017. They proved the bound, the matching lower bound, and the linear bound for evenly spaced planes. In 2018 Minetto and Stolfi published a corrigendum that states the bounds of the hash-based loop step as expected time.
References
- Rodrigo Minetto, Neri Volpato, Jorge Stolfi, Rodrigo M. M. H. Gregori and Murilo V. G. da Silva, An optimal algorithm for 3D triangle mesh slicing, Computer-Aided Design 92, 2017, 1 to 10, the slicing algorithm with buckets and a sweep, the lower bound, and the linking of segments with a hash table
- Rodrigo Minetto and Jorge Stolfi, Corrigendum to An optimal algorithm for 3D triangle mesh slicing, Computer-Aided Design 98, 2018, 39, the correction that the bounds of the loop step hold in expected time
- Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the chapter on the generalized additive manufacturing process chain (STL input and slicing)
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, A K Peters, 2010, the chapter on mesh data structures (face sets, shared vertices and halfedges)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ETJZAW Edit this page History Report an error Markdown