Skip to main content

brep_kernel/
plane_section.rs

1//! The cut of a solid by a plane: where the plane meets the boundary, as
2//! polylines, and the area of the cut.
3//!
4//! The solid is cut by the plane ([`solid_piece_by_plane`]); the piece below
5//! it (or above it, when that cut declines) carries one cap face on the plane for every region of the cut, bounded by
6//! the section curves themselves. The area is those faces' areas, and the
7//! curves are their edges, each sampled from end to end with every chord
8//! within the caller's tolerance of the edge curve. Every sample is a point of
9//! an edge curve, so it lies on the plane and on the boundary to the accuracy
10//! the boolean built those edges to.
11
12use crate::{face_area, shell_vector_areas, solid_piece_by_plane, BrepSolid, FaceRecord, KernelRefusal, KernelStage, NurbsCurve, Vec3};
13
14/// `BREP_SECTION_SUB_BAND_AREA` (default on, `=0` restores the refusal): a
15/// cut whose regions are thinner than the boolean's weld band is measured by
16/// [`sub_band_area`] instead of refused.
17fn sub_band_area_enabled() -> bool {
18    crate::switch!("BREP_SECTION_SUB_BAND_AREA", true)
19}
20
21/// What [`caps`] found.
22enum Cut {
23    /// The plane does not cut the solid.
24    Miss,
25    /// The piece on one side, and the indices of its faces on the plane.
26    Caps(BrepSolid, Vec<usize>),
27    /// The solid lies on both sides, but every region of the cut is thinner
28    /// than the boolean's weld band, so neither piece carries a face on the
29    /// plane; the cut's area, read by [`sub_band_area`].
30    SubBand(f64),
31}
32
33/// The covers [`caps`] cuts with, tightest first: a box just over the solid
34/// keeps the boolean's tolerances to the solid's own size.
35const COVERS: [f64; 4] = [1.2, 1.5, 2.0, 3.0];
36
37/// The faces of a piece of `solid` cut off by the plane through `origin`
38/// square to `normal` that lie in that plane (the caps), with the piece that
39/// holds them; `None` when the plane does not cut the solid.
40///
41/// The plane misses when every control point of the solid lies strictly on
42/// one side (each face and edge lies in the hull of its control points), and
43/// no boolean is run. Otherwise the piece below the plane is cut, then the
44/// piece above (both carry the same caps), with boxes from [`COVERS`] in turn
45/// until one cut goes through. A piece with no face on the plane is a miss when
46/// the other side is empty, or when the plane passes between the solid's lumps
47/// ([`lumps_part`]); a cut that declines at every box, or a solid on both
48/// sides with no face on the plane otherwise, is refused, never read as a miss.
49fn caps(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<Cut, KernelRefusal> {
50    let unit = normal
51        .normalized()
52        .map_err(|_| KernelRefusal::input(KernelStage::Collect, "section_normal", "section: the plane normal has no direction"))?;
53    let refuse = |message: String| KernelRefusal::internal(KernelStage::Fragment, "section_split", format!("section: {message}"));
54    let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
55    let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
56    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
57    for control in surfaces.chain(curves) {
58        let height = control.point().map_err(|message| refuse(message))?.sub(origin).dot(unit);
59        low = low.min(height);
60        high = high.max(height);
61    }
62    if !(low < 0.0 && high > 0.0) {
63        return Ok(Cut::Miss);
64    }
65    let mut declined = Vec::new();
66    let mut found = None;
67    'covers: for cover in COVERS {
68        for above in [false, true] {
69            match solid_piece_by_plane(solid, origin, unit, above, cover) {
70                Ok(piece) => {
71                    found = Some((piece, above));
72                    break 'covers;
73                }
74                Err(message) => declined.push(message),
75            }
76        }
77    }
78    let Some((piece, piece_above)) = found else {
79        return Err(refuse(declined.join("; ")));
80    };
81    // The control points straddle the plane, but the solid itself may not.
82    let Some(piece) = piece else {
83        return Ok(Cut::Miss);
84    };
85    let extent = piece.vertices.iter().fold(0.0f64, |extent, vertex| {
86        extent.max(vertex.point.x.abs()).max(vertex.point.y.abs()).max(vertex.point.z.abs())
87    });
88    let scale = 1.0 + extent;
89    let tolerance = 1e-9 * scale;
90    let on_plane = |face: &FaceRecord| -> bool {
91        if !face.surface.is_affine().unwrap_or(false) {
92            return false;
93        }
94        face.surface.control_points.iter().flatten().all(|control| {
95            control.point().is_ok_and(|point| point.sub(origin).dot(unit).abs() <= tolerance)
96        })
97    };
98    let faces: Vec<usize> = piece.shells.iter().flat_map(|shell| &shell.faces).enumerate().filter(|(_, face)| on_plane(face)).map(|(index, _)| index).collect();
99    if faces.is_empty() {
100        // No cap: the plane misses the solid when nothing of it lies on the
101        // other side (the piece is then the whole solid), or when the solid's
102        // lumps fall wholly to one side or the other: the two pieces then
103        // share out the solid's faces without cutting any, their volumes sum
104        // to the solid's, and every vertex of each lies clear of the plane on
105        // its own side.
106        let other = !piece_above;
107        let mut other_declined = Vec::new();
108        for cover in COVERS {
109            match solid_piece_by_plane(solid, origin, unit, other, cover) {
110                Ok(None) => return Ok(Cut::Miss),
111                Ok(Some(other_piece)) => {
112                    if lumps_part(solid, &piece, &other_piece, origin, unit, other, tolerance) {
113                        return Ok(Cut::Miss);
114                    }
115                    if sub_band_area_enabled() {
116                        if let Some(area) = sub_band_area(solid, &piece, &other_piece, unit, piece_above) {
117                            return Ok(Cut::SubBand(area));
118                        }
119                    }
120                    return Err(refuse("the solid lies on both sides of the plane but the cut left no face on it".into()));
121                }
122                Err(message) => other_declined.push(message),
123            }
124        }
125        return Err(refuse(format!(
126            "the cut left no face on the plane, and the other side declined: {}",
127            other_declined.join("; ")
128        )));
129    }
130    Ok(Cut::Caps(piece, faces))
131}
132
133/// The area of a cut that left no face on the plane although the solid lies
134/// on both sides of it: every region of the cut is thinner than the weld band
135/// (a ring a few micrometres thick around a rod), so the boolean sewed the
136/// faces either side straight across the plane. Each piece is then a closed
137/// shell short of its caps, and `∫ n dA = 0` over the whole boundary makes
138/// the caps' area the piece's own trim residual ([`shell_vector_areas`]):
139/// `−A n` for the piece below, `+A n` for the one above. It is read only when
140/// it is a measurement: every shell of both pieces closed and read to the
141/// end, each residual along the normal with its side's sign, the two areas
142/// agreeing, and the area clear of the noise (the solid's own residual, the
143/// residuals' components off the normal, the two pieces' disagreement, and
144/// every quadrature error) by a factor of ten. `None` otherwise, and the cut
145/// is refused as before.
146fn sub_band_area(solid: &BrepSolid, piece: &BrepSolid, other: &BrepSolid, unit: Vec3, piece_above: bool) -> Option<f64> {
147    // The summed residual of every shell, its quadrature error, or `None`
148    // when a shell is open, unread or abandoned.
149    let residual = |body: &BrepSolid| -> Option<(Vec3, f64)> {
150        let report = shell_vector_areas(body);
151        if !report.unreadable.is_empty() || report.shells.is_empty() {
152            return None;
153        }
154        let mut sum = Vec3::new(0.0, 0.0, 0.0);
155        let mut error = 0.0;
156        for shell in &report.shells {
157            if !shell.closed || shell.gave_up || !shell.trim_residual.length().is_finite() {
158                return None;
159            }
160            sum = sum.add(shell.trim_residual);
161            error += shell.quadrature_error;
162        }
163        Some((sum, error))
164    };
165    let (whole, whole_error) = residual(solid)?;
166    let (first, first_error) = residual(piece)?;
167    let (second, second_error) = residual(other)?;
168    // The piece above lacks caps facing −n, so its faces sum to +A n.
169    let (above, below) = if piece_above { (first, second) } else { (second, first) };
170    let (area_above, area_below) = (above.dot(unit), -below.dot(unit));
171    if !(area_above > 0.0 && area_below > 0.0) {
172        return None;
173    }
174    let off = |vector: Vec3, along: f64| vector.sub(unit.scale(along)).length();
175    let noise = whole.length()
176        + off(above, area_above)
177        + off(below, -area_below)
178        + (area_above - area_below).abs()
179        + 10.0 * (whole_error + first_error + second_error);
180    let area = 0.5 * (area_above + area_below);
181    (area > 10.0 * noise).then_some(area)
182}
183
184/// Whether `first` and `second`, the pieces of `solid` on the two sides of the
185/// plane (`second` above it when `second_above`), are its lumps parted whole:
186/// together they hold exactly the solid's faces, their volumes sum to the
187/// solid's, and every vertex of each lies more than `tolerance` from the plane
188/// on its own side. A cut that split a face adds faces, so a solid the plane
189/// truly crosses never passes.
190fn lumps_part(solid: &BrepSolid, first: &BrepSolid, second: &BrepSolid, origin: Vec3, unit: Vec3, second_above: bool, tolerance: f64) -> bool {
191    let faces = |body: &BrepSolid| body.shells.iter().map(|shell| shell.faces.len()).sum::<usize>();
192    if faces(first) + faces(second) != faces(solid) {
193        return false;
194    }
195    let side = |body: &BrepSolid, above: bool| {
196        body.vertices.iter().all(|vertex| {
197            let height = vertex.point.sub(origin).dot(unit);
198            if above { height > tolerance } else { height < -tolerance }
199        })
200    };
201    if !(side(first, !second_above) && side(second, second_above)) {
202        return false;
203    }
204    match (crate::solid_mass_properties(solid), crate::solid_mass_properties(first), crate::solid_mass_properties(second)) {
205        // A lost or turned lump moves the sum by a whole lump; the mass
206        // integrals of swept faces carry a few parts in 1e9.
207        (Ok(whole), Ok(a), Ok(b)) => (a.volume + b.volume - whole.volume).abs() <= 1e-6 * whole.volume.abs().max(f64::MIN_POSITIVE),
208        _ => false,
209    }
210}
211
212/// `curve` over `[t0, t1]` as points from end to end, every chord within
213/// `tolerance` of the curve at its quarter points: each knot span is halved
214/// until it is.
215fn sample_edge(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Result<Vec<Vec3>, String> {
216    let (low, high) = (t0.min(t1), t0.max(t1));
217    let mut breaks: Vec<f64> = vec![low];
218    breaks.extend(curve.knots.iter().copied().filter(|&knot| knot > low && knot < high));
219    breaks.push(high);
220    breaks.dedup();
221    let chord_error = |a: f64, b: f64| -> Result<f64, String> {
222        let (p, q) = (curve.evaluate(a)?, curve.evaluate(b)?);
223        let chord = q.sub(p);
224        let length = chord.length();
225        let mut worst = 0.0f64;
226        for fraction in [0.25, 0.5, 0.75] {
227            let point = curve.evaluate(a + (b - a) * fraction)?;
228            let offset = point.sub(p);
229            let along = if length > 0.0 { offset.dot(chord) / (length * length) } else { 0.0 };
230            worst = worst.max(offset.sub(chord.scale(along.clamp(0.0, 1.0))).length());
231        }
232        Ok(worst)
233    };
234    let mut parameters = vec![low];
235    for pair in breaks.windows(2) {
236        // Depth-first halving of the span, at most 24 levels deep.
237        let mut start = pair[0];
238        let mut pending = vec![(pair[1], 0u32)];
239        while let Some((end, depth)) = pending.pop() {
240            if depth < 24 && chord_error(start, end)? > tolerance {
241                let middle = 0.5 * (start + end);
242                pending.push((end, depth + 1));
243                pending.push((middle, depth + 1));
244                continue;
245            }
246            parameters.push(end);
247            start = end;
248        }
249    }
250    let mut points = parameters.iter().map(|&t| curve.evaluate(t)).collect::<Result<Vec<_>, _>>()?;
251    if t1 < t0 {
252        points.reverse();
253    }
254    Ok(points)
255}
256
257/// Where the plane through `origin` square to `normal` cuts the boundary of
258/// `solid`, in pieces in any order: each piece is one edge of the cut, as
259/// points along it from end to end, every chord within `chord_tolerance` of
260/// the edge curve. The pieces join end to end into the closed curves of the
261/// cut; a piece that is a whole closed curve ends on its first point. Empty
262/// when the plane misses the solid.
263pub fn solid_section(
264    solid: &BrepSolid,
265    origin: Vec3,
266    normal: Vec3,
267    chord_tolerance: f64,
268) -> Result<Vec<Vec<Vec3>>, KernelRefusal> {
269    if !(chord_tolerance > 0.0 && chord_tolerance.is_finite()) {
270        return Err(KernelRefusal::input(KernelStage::Collect, "section_tolerance", "section: the chord tolerance must be positive"));
271    }
272    let (below, faces) = match caps(solid, origin, normal)? {
273        Cut::Miss => return Ok(Vec::new()),
274        Cut::Caps(below, faces) => (below, faces),
275        Cut::SubBand(area) => {
276            return Err(KernelRefusal::internal(
277                KernelStage::Fragment,
278                "section_split",
279                format!(
280                    "section: every region of the cut is thinner than the boolean's weld band (area {area:.3e}), \
281                     so no face on the plane holds its curves"
282                ),
283            ))
284        }
285    };
286    let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
287    let mut pieces = Vec::new();
288    for index in faces {
289        for coedge in all[index].loops.iter().flat_map(|loop_record| &loop_record.coedges) {
290            let edge = below.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| {
291                KernelRefusal::internal(KernelStage::Collect, "section_edge", format!("section: edge {} is missing", coedge.edge_id))
292            })?;
293            if edge.degenerate {
294                continue;
295            }
296            let points = sample_edge(&edge.curve, edge.t0, edge.t1, chord_tolerance)
297                .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_sample", format!("section: {message}")))?;
298            pieces.push(points);
299        }
300    }
301    Ok(pieces)
302}
303
304/// The area of the cut of `solid` by the plane through `origin` square to
305/// `normal`: the area of the faces the split leaves on that plane. Zero when
306/// the plane misses the solid.
307pub fn solid_section_area(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<f64, KernelRefusal> {
308    let (below, faces) = match caps(solid, origin, normal)? {
309        Cut::Miss => return Ok(0.0),
310        Cut::Caps(below, faces) => (below, faces),
311        Cut::SubBand(area) => return Ok(area),
312    };
313    let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
314    let mut area = 0.0;
315    for index in faces {
316        area += face_area(all[index])
317            .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_area", format!("section area: {message}")))?;
318    }
319    Ok(area)
320}
321