Skip to main content

lib_jsl_geometry/algorithms/
slicing.rs

1//! Slicing triangle meshes with planes into contours.
2//!
3//! Each triangle crossing the plane contributes one segment ([`triangle_plane`]); the segments are
4//! then chained end to end into polylines, closed where the cut goes all the way round. This is
5//! the core of layer-by-layer slicing for 3D printing and of cross-section views.
6//!
7//! See the book entry [Triangle meshes: smoothing, decimation and slicing](https://jwkunz.github.io/lib_jsl/book/geometry/meshes.html#slicing).
8
9use super::intersection::triangle_plane;
10use std::collections::HashMap;
11
12/// A chain of points where a plane cuts a mesh.
13#[derive(Debug, Clone, PartialEq)]
14
15pub struct Contour {
16    /// Vertices in order. For a closed contour the first vertex is *not* repeated at the end.
17    pub points: Vec<[f64; 3]>,
18    /// Whether the last vertex connects back to the first.
19    pub closed: bool,
20}
21
22impl Contour {
23    /// Total length (including the closing edge if closed).
24    pub fn length(&self) -> f64 {
25        let n = self.points.len();
26        let edges = if self.closed { n } else { n.saturating_sub(1) };
27        (0..edges)
28            .map(|i| {
29                let (a, b) = (self.points[i], self.points[(i + 1) % n]);
30                ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
31            })
32            .sum()
33    }
34
35    /// Removes interior vertices that lie on the straight line between their neighbours (within
36    /// `tol`), e.g. the extra points a cut makes where it crosses a flat face's diagonal.
37    pub fn simplified(&self, tol: f64) -> Contour {
38        let mut pts = self.points.clone();
39        let mut i = 0;
40        while pts.len() > 2 && i < pts.len() {
41            let n = pts.len();
42            if !self.closed && (i == 0 || i == n - 1) {
43                i += 1;
44                continue;
45            }
46            let (a, b, c) = (pts[(i + n - 1) % n], pts[i], pts[(i + 1) % n]);
47            let (ab, ac) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
48            let cr = [ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]];
49            let area2 = (cr[0] * cr[0] + cr[1] * cr[1] + cr[2] * cr[2]).sqrt();
50            let base = (ac[0] * ac[0] + ac[1] * ac[1] + ac[2] * ac[2]).sqrt();
51            if base == 0.0 || area2 / base <= tol {
52                pts.remove(i);
53                if self.closed && pts.len() < 3 {
54                    break;
55                }
56            } else {
57                i += 1;
58            }
59        }
60        let closed = self.closed && pts.len() >= 3;
61        Contour { points: pts, closed }
62    }
63}
64
65/// Slices the triangle mesh with the plane through `plane_point` with `normal`, returning the
66/// cut as contours. `tol` is the distance within which vertices count as on the plane and cut
67/// endpoints count as coincident; choose it relative to the mesh size (e.g. `1e-9 * extent`).
68///
69/// Triangles lying exactly in the plane contribute nothing (their boundary appears from the
70/// neighbouring triangles), and an edge lying in the plane is reported once even though both of
71/// its triangles cut there, so a plane through a ring of vertices gives one loop. Triangles with
72/// out-of-range indices are skipped.
73// ANCHOR: slice
74pub fn slice_mesh(vertices: &[[f64; 3]], triangles: &[[usize; 3]], plane_point: [f64; 3], normal: [f64; 3], tol: f64) -> Vec<Contour> {
75    let tol = tol.max(f64::MIN_POSITIVE);
76    // A mesh edge lying in the plane is reported by both triangles that share it; keep one copy.
77    let key = |p: [f64; 3]| -> (i64, i64, i64) { ((p[0] / tol).round() as i64, (p[1] / tol).round() as i64, (p[2] / tol).round() as i64) };
78    let mut seen = std::collections::HashSet::new();
79    let segments: Vec<([f64; 3], [f64; 3])> = triangles
80        .iter()
81        .filter_map(|t| {
82            let (a, b, c) = (*vertices.get(t[0])?, *vertices.get(t[1])?, *vertices.get(t[2])?);
83            triangle_plane(a, b, c, plane_point, normal, tol)
84        })
85        .filter(|&(p, q)| {
86            let (kp, kq) = (key(p), key(q));
87            seen.insert(if kp <= kq { (kp, kq) } else { (kq, kp) })
88        })
89        .collect();
90    chain_segments(&segments, tol)
91}
92// ANCHOR_END: slice
93
94/// Slices the mesh at each of `levels` along a coordinate axis (`0` = x, `1` = y, `2` = z),
95/// returning `(level, contours)` for every level, in the order given.
96pub fn slice_mesh_levels(vertices: &[[f64; 3]], triangles: &[[usize; 3]], axis: usize, levels: &[f64], tol: f64) -> Vec<(f64, Vec<Contour>)> {
97    assert!(axis < 3, "axis must be 0, 1 or 2");
98    let mut normal = [0.0; 3];
99    normal[axis] = 1.0;
100    levels
101        .iter()
102        .map(|&level| {
103            let mut p = [0.0; 3];
104            p[axis] = level;
105            (level, slice_mesh(vertices, triangles, p, normal, tol))
106        })
107        .collect()
108}
109
110fn chain_segments(segments: &[([f64; 3], [f64; 3])], tol: f64) -> Vec<Contour> {
111    // Snap endpoints to a grid of cell size `tol` so coincident ends share a key. Neighbouring
112    // cells are also probed so points straddling a cell boundary still match.
113    let key = |p: [f64; 3]| -> (i64, i64, i64) { ((p[0] / tol).round() as i64, (p[1] / tol).round() as i64, (p[2] / tol).round() as i64) };
114    let mut ends: HashMap<(i64, i64, i64), Vec<(usize, bool)>> = HashMap::new(); // (segment, is_second_end)
115    for (i, &(p, q)) in segments.iter().enumerate() {
116        ends.entry(key(p)).or_default().push((i, false));
117        ends.entry(key(q)).or_default().push((i, true));
118    }
119    let find_next = |pt: [f64; 3], used: &[bool]| -> Option<(usize, bool)> {
120        let (kx, ky, kz) = key(pt);
121        for dx in -1..=1 {
122            for dy in -1..=1 {
123                for dz in -1..=1 {
124                    if let Some(list) = ends.get(&(kx + dx, ky + dy, kz + dz)) {
125                        for &(s, second) in list {
126                            let e = if second { segments[s].1 } else { segments[s].0 };
127                            let d2 = (e[0] - pt[0]).powi(2) + (e[1] - pt[1]).powi(2) + (e[2] - pt[2]).powi(2);
128                            if !used[s] && d2 <= (2.0 * tol) * (2.0 * tol) {
129                                return Some((s, second));
130                            }
131                        }
132                    }
133                }
134            }
135        }
136        None
137    };
138
139    let mut used = vec![false; segments.len()];
140    let mut out = Vec::new();
141    for start in 0..segments.len() {
142        if used[start] {
143            continue;
144        }
145        used[start] = true;
146        let mut chain: std::collections::VecDeque<[f64; 3]> = [segments[start].0, segments[start].1].into();
147        // Grow forward from the tail, then backward from the head.
148        for forward in [true, false] {
149            loop {
150                let end = if forward { *chain.back().expect("non-empty") } else { *chain.front().expect("non-empty") };
151                let Some((s, second)) = find_next(end, &used) else { break };
152                used[s] = true;
153                let far = if second { segments[s].0 } else { segments[s].1 };
154                if forward { chain.push_back(far) } else { chain.push_front(far) }
155            }
156        }
157        let mut points: Vec<[f64; 3]> = chain.into();
158        let dist2 = |a: [f64; 3], b: [f64; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2);
159        let closed = points.len() >= 4 && dist2(points[0], points[points.len() - 1]) <= (2.0 * tol) * (2.0 * tol);
160        if closed {
161            points.pop();
162        }
163        out.push(Contour { points, closed });
164    }
165    out
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    /// A unit cube at the origin with 12 triangles.
173    fn cube() -> (Vec<[f64; 3]>, Vec<[usize; 3]>) {
174        let v: Vec<[f64; 3]> = (0..8).map(|i| [(i & 1) as f64, ((i >> 1) & 1) as f64, ((i >> 2) & 1) as f64]).collect();
175        let quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]];
176        let t = quads.iter().flat_map(|q| [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]).collect();
177        (v, t)
178    }
179
180    #[test]
181    fn cube_cross_section_is_one_closed_square() {
182        let (v, t) = cube();
183        let cuts = slice_mesh(&v, &t, [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], 1e-9);
184        assert_eq!(cuts.len(), 1);
185        assert!(cuts[0].closed);
186        assert!((cuts[0].length() - 4.0).abs() < 1e-9);
187        assert!(cuts[0].points.iter().all(|p| (p[2] - 0.5).abs() < 1e-12));
188        let s = cuts[0].simplified(1e-9);
189        assert_eq!(s.points.len(), 4);
190        assert!(s.closed && (s.length() - 4.0).abs() < 1e-9);
191        // An oblique cut through the cube's centre is a hexagon-or-larger loop, still closed.
192        let oblique = slice_mesh(&v, &t, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0], 1e-9);
193        assert_eq!(oblique.len(), 1);
194        assert!(oblique[0].closed);
195        assert_eq!(oblique[0].simplified(1e-9).points.len(), 6);
196    }
197
198    #[test]
199    fn plane_misses_and_stacked_levels() {
200        let (v, t) = cube();
201        assert!(slice_mesh(&v, &t, [0.0, 0.0, 2.0], [0.0, 0.0, 1.0], 1e-9).is_empty());
202        let layers = slice_mesh_levels(&v, &t, 2, &[0.25, 0.5, 0.75, 1.5], 1e-9);
203        let counts: Vec<usize> = layers.iter().map(|(_, c)| c.len()).collect();
204        assert_eq!(counts, vec![1, 1, 1, 0]);
205        assert!(layers[..3].iter().all(|(_, c)| (c[0].length() - 4.0).abs() < 1e-9));
206        // Slicing exactly on a face leaves the face's own triangles silent but the side walls
207        // still report their edge, so the boundary comes out as a loop.
208        let on_face = slice_mesh(&v, &t, [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 1e-9);
209        assert!(!on_face.is_empty());
210    }
211
212    #[test]
213    fn a_plane_through_a_ring_of_vertices_gives_one_loop() {
214        // A square tube from z = 0 to 2 with a ring of vertices at z = 1: each ring edge belongs
215        // to a triangle above and one below, and used to be reported twice.
216        let corners = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
217        let v: Vec<[f64; 3]> = (0..3).flat_map(|z| corners.iter().map(move |c| [c[0], c[1], z as f64])).collect();
218        let mut t = Vec::new();
219        for level in 0..2 {
220            for k in 0..4 {
221                let (a, b) = (4 * level + k, 4 * level + (k + 1) % 4);
222                t.push([a, b, b + 4]);
223                t.push([a, b + 4, a + 4]);
224            }
225        }
226        let cuts = slice_mesh(&v, &t, [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], 1e-9);
227        assert_eq!(cuts.len(), 1);
228        assert!(cuts[0].closed && (cuts[0].length() - 4.0).abs() < 1e-12);
229    }
230
231    #[test]
232    fn two_separate_solids_give_two_contours_and_open_meshes_give_open_chains() {
233        let (mut v, mut t) = cube();
234        let base = v.len();
235        v.extend(cube().0.into_iter().map(|p| [p[0] + 5.0, p[1], p[2]]));
236        t.extend(cube().1.into_iter().map(|tr| [tr[0] + base, tr[1] + base, tr[2] + base]));
237        let cuts = slice_mesh(&v, &t, [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], 1e-9);
238        assert_eq!(cuts.len(), 2);
239        assert!(cuts.iter().all(|c| c.closed));
240        // Drop the top face (two triangles): cutting just under the open top still closes via the
241        // walls, but cutting a lone wall quad yields an open chain.
242        let wall: Vec<[usize; 3]> = vec![[0, 1, 5], [0, 5, 4]]; // the y=0 wall
243        let open = slice_mesh(&v, &wall, [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], 1e-9);
244        assert_eq!(open.len(), 1);
245        assert!(!open[0].closed && (open[0].length() - 1.0).abs() < 1e-9);
246        // Bad indices are skipped rather than panicking.
247        assert!(slice_mesh(&v, &[[0, 1, 99]], [0.0, 0.0, 0.5], [0.0, 0.0, 1.0], 1e-9).is_empty());
248    }
249}