Skip to main content

brep_boolean/edit/
split.rs

1//! Cut / split a body by a plane (Golovanov §6.4).
2//!
3//! The split reuses the ROBUST boolean rather than a bespoke classifier: the
4//! plane is realised as two very large half-space TOOL boxes (one covering each
5//! side of the plane), and each output piece is `Intersect(solid, tool)`. The
6//! boolean machinery imprints the cut plane onto the solid and re-closes the
7//! shell, so both pieces inherit the kernel's validated, watertight topology.
8
9use crate::boolean::{boolean_operation, BooleanOperation, BooleanOptions};
10use crate::spatial::Aabb;
11use crate::topology::{make_box_brep, make_cylinder_brep, BrepSolid};
12use crate::transform_topology::{transform_brep, AffineTransform};
13use crate::{
14    make_cone_brep, make_sphere_brep, make_torus_brep, AnalyticSurface, NurbsSurface, Vec3,
15};
16use serde::Deserialize;
17
18/// Axis-aligned bounding box of a solid: its vertices, and the control points
19/// of every face's surface and every edge's curve.
20///
21/// The vertices alone do not bound a body whose faces bulge past them: a torus
22/// has one vertex, so the box read as degenerate and the split refused; a
23/// sphere's are its two poles, a segment on the axis. A rational patch or curve
24/// with positive weights lies in the hull of its control points, so they bound
25/// it (loosely, which a tool three diagonals wide does not mind).
26fn solid_aabb(solid: &BrepSolid) -> Aabb {
27    let mut bounds = Aabb::empty();
28    for vertex in &solid.vertices {
29        bounds.include_point(vertex.point);
30    }
31    let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
32    let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
33    for control in surfaces.chain(curves) {
34        if let Ok(point) = control.point() {
35            bounds.include_point(point);
36        }
37    }
38    bounds
39}
40
41/// A boolean result counts as an empty piece when it carries no face geometry —
42/// i.e. the half-space tool did not overlap the solid on that side.
43fn is_empty_piece(solid: &BrepSolid) -> bool {
44    solid.shells.is_empty() || solid.shells.iter().all(|shell| shell.faces.is_empty())
45}
46
47/// Build the affine placing a local, origin-centred cube so its local +Z axis
48/// maps to `n`, +X to `u`, +Y to `v`, and its centre lands at `center`. The
49/// columns of the rotation are `[u v n]` (a right-handed, det = +1 frame), so
50/// the map is a proper rigid motion (no orientation reversal needed).
51fn frame_transform(u: Vec3, v: Vec3, n: Vec3, center: Vec3) -> Result<AffineTransform, String> {
52    AffineTransform::new([
53        u.x, v.x, n.x, center.x, //
54        u.y, v.y, n.y, center.y, //
55        u.z, v.z, n.z, center.z, //
56        0.0, 0.0, 0.0, 1.0,
57    ])
58}
59
60/// Split `solid` into two pieces by the plane through `plane_point` with normal
61/// `plane_normal`. Returns `(below, above)` where `below` is the piece on the
62/// −n side of the plane and `above` the piece on the +n side.
63///
64/// Contract: when the plane misses the solid's box this returns
65/// `Err("split_solid_by_plane: plane does not intersect the solid")`; when a
66/// cut fails the error names the boolean's own refusal; when the plane meets
67/// the box but a piece comes out empty (a tangent plane, or a plane through
68/// the box beside the body) the error says which piece. It never returns a
69/// degenerate or empty piece.
70pub fn split_solid_by_plane(
71    solid: &BrepSolid,
72    plane_point: Vec3,
73    plane_normal: Vec3,
74) -> Result<(BrepSolid, BrepSolid), String> {
75    if plane_misses_box(solid, plane_point, plane_normal) {
76        return Err("split_solid_by_plane: plane does not intersect the solid".into());
77    }
78    let options = BooleanOptions::default();
79    let cut = |cover: f64| -> Result<_, String> {
80        let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
81        Ok((
82            boolean_operation(solid, &tool_below, BooleanOperation::Intersect, &options),
83            boolean_operation(solid, &tool_above, BooleanOperation::Intersect, &options),
84        ))
85    };
86    // Three diagonals first, as every caller has read the pieces' cap
87    // carriers. Where that cut fails, a box 1.2 diagonals across, which still
88    // covers the solid: the wider cut face resolves small sections on it
89    // coarser, and a ball 1.8e-4 wider than its rod, a plate with a grid of
90    // holes and a chain of links each came back from the 3x box with an open
91    // loop and cut cleanly at 1.2x.
92    let (mut below, mut above) = cut(3.0)?;
93    if below.is_err() || above.is_err() {
94        (below, above) = cut(1.2)?;
95    }
96
97    match (below, above) {
98        (Ok(below), Ok(above)) => match (is_empty_piece(&below), is_empty_piece(&above)) {
99            (false, false) => Ok((below, above)),
100            (below_empty, above_empty) => Err(format!(
101                "split_solid_by_plane: the plane crosses the solid's box but the cut left the piece {} the plane empty",
102                match (below_empty, above_empty) {
103                    (true, true) => "on each side of",
104                    (true, false) => "below",
105                    _ => "above",
106                },
107            )),
108        },
109        (Err(error), _) | (_, Err(error)) => Err(format!("split_solid_by_plane: the cut failed: {error}")),
110    }
111}
112
113/// Whether every corner of the solid's control-point box lies strictly on one
114/// side of the plane, so the plane cannot meet the solid at all.
115fn plane_misses_box(solid: &BrepSolid, plane_point: Vec3, plane_normal: Vec3) -> bool {
116    let (bounds, Ok(n)) = (solid_aabb(solid), plane_normal.normalized()) else {
117        return false;
118    };
119    if !bounds.minimum.x.is_finite() {
120        return false;
121    }
122    let (lo, hi) = (bounds.minimum, bounds.maximum);
123    let reach = 1e-9 * bounds.diagonal().max(1.0);
124    let sides = (0..8).map(|corner| {
125        let point = Vec3::new(
126            if corner & 1 == 0 { lo.x } else { hi.x },
127            if corner & 2 == 0 { lo.y } else { hi.y },
128            if corner & 4 == 0 { lo.z } else { hi.z },
129        );
130        point.sub(plane_point).dot(n)
131    });
132    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
133    for side in sides {
134        low = low.min(side);
135        high = high.max(side);
136    }
137    low > reach || high < -reach
138}
139
140/// The piece of `solid` on one side of the plane through `plane_point` with
141/// normal `plane_normal`: the −n side when `above` is false, the +n side when
142/// it is true. The cutting box spans `cover` times the diagonal of the
143/// solid's control-point box (at least 1; [`split_solid_by_plane`] uses 3),
144/// centred on that box's centre projected onto the plane, so it covers every
145/// part of the solid on its side whenever the plane meets that box.
146/// `Ok(None)` when nothing of the solid lies on that side; an error only when
147/// the cut itself fails, so a caller can tell a plane that misses from a
148/// boolean that declined.
149pub fn solid_piece_by_plane(
150    solid: &BrepSolid,
151    plane_point: Vec3,
152    plane_normal: Vec3,
153    above: bool,
154    cover: f64,
155) -> Result<Option<BrepSolid>, String> {
156    if !(cover >= 1.0 && cover.is_finite()) {
157        return Err("solid_piece_by_plane: the cover must be at least 1".into());
158    }
159    let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
160    let tool = if above { tool_above } else { tool_below };
161    let piece = boolean_operation(solid, &tool, BooleanOperation::Intersect, &BooleanOptions::default())
162        .map_err(|error| format!("solid_piece_by_plane: {error}"))?;
163    Ok((!is_empty_piece(&piece)).then_some(piece))
164}
165
166/// The two half-space tool boxes of a plane cut of `solid`, each `cover`
167/// times the solid's diagonal on a side: (below, above).
168fn plane_tools(
169    solid: &BrepSolid,
170    plane_point: Vec3,
171    plane_normal: Vec3,
172    cover: f64,
173) -> Result<(BrepSolid, BrepSolid), String> {
174    let n = plane_normal.normalized()?;
175    // Orthonormal frame (n, u, v): u ⟂ n (unit), v = n × u (unit); [u v n] is
176    // right-handed so the tool placement is a proper rotation.
177    let u = n.perpendicular()?;
178    let v = n.cross(u);
179
180    let bounds = solid_aabb(solid);
181    if !bounds.minimum.x.is_finite() {
182        return Err("split_solid_by_plane: solid has no geometry".into());
183    }
184    let diagonal = bounds.diagonal();
185    if diagonal <= 0.0 {
186        return Err("split_solid_by_plane: solid is degenerate".into());
187    }
188    // A tool box `cover` × the solid diagonal on every side (3× for the
189    // split) covers the body in the plane's tangent directions.
190    let length = cover * diagonal;
191    let half = 0.5 * length;
192
193    // Centre the tool in the tangent (u, v) plane on the projection of the AABB
194    // centre onto the cut plane, so the box brackets the whole solid regardless
195    // of where `plane_point` sits within it. Along n it is offset by ±half so
196    // the tool's cut face lands exactly on the plane.
197    let center = bounds.minimum.add(bounds.maximum).scale(0.5);
198    let center_on_plane = center.sub(n.scale(center.sub(plane_point).dot(n)));
199
200    // Local cube centred at the local origin, spanning [-half, half]³.
201    let cube = make_box_brep(Vec3::new(-half, -half, -half), length, length, length)?;
202
203    // BELOW: tool centred at plane − n·half, so its +n face lies on the plane
204    // and it extends distance `length` along −n, covering the −n side.
205    let below_center = center_on_plane.sub(n.scale(half));
206    let tool_below = transform_brep(&cube, frame_transform(u, v, n, below_center)?, false)?;
207
208    // ABOVE: mirror to the +n side (centre at plane + n·half).
209    let above_center = center_on_plane.add(n.scale(half));
210    let tool_above = transform_brep(&cube, frame_transform(u, v, n, above_center)?, false)?;
211    Ok((tool_below, tool_above))
212}
213
214// ---------------------------------------------------------------------------
215// Generalized split by an analytic surface (Golovanov §6.4).
216//
217// The plane case above splits a body against two large half-space TOOL boxes.
218// The analytic cases generalize that idea: an unbounded/bounded analytic
219// surface (cylinder, cone, sphere, torus) is realised as ONE CLOSED SOLID
220// region big enough to span the body wherever it matters, and the two output
221// pieces are the boolean `Intersect` (inside the tool region) and `Subtract`
222// (outside it) of the body against that region.  Because every cut runs
223// through the validated boolean machinery, each piece inherits watertight
224// topology, the cut surface is imprinted onto the body, and the two volumes
225// sum to the original.
226// ---------------------------------------------------------------------------
227
228/// A closed analytic tool region used to cut a body.  Each variant is realised
229/// as a closed solid (unbounded carriers are capped well beyond the body) whose
230/// interior is one side of the analytic surface.
231#[derive(Clone, Copy, Debug, Deserialize)]
232#[serde(tag = "type", rename_all = "lowercase")]
233pub enum SplitSurface {
234    /// Infinite plane through `point` with `normal`; delegates to the plane path.
235    Plane { point: Vec3, normal: Vec3 },
236    /// Infinite cylinder about the axis line through `axis_point` along
237    /// `axis_dir`, of the given `radius`.  Interior = inside the cylinder.
238    Cylinder {
239        axis_point: Vec3,
240        axis_dir: Vec3,
241        radius: f64,
242    },
243    /// Sphere centred at `center`.  Interior = inside the ball.
244    Sphere { center: Vec3, radius: f64 },
245    /// Single-nappe cone with its apex at `apex`, opening along `+axis_dir`,
246    /// with the given `half_angle` (radians, apex half-angle).  Interior =
247    /// inside the cone.
248    Cone {
249        apex: Vec3,
250        axis_dir: Vec3,
251        half_angle: f64,
252    },
253    /// Torus centred at `center` about `axis_dir`.  Interior = inside the tube.
254    Torus {
255        center: Vec3,
256        axis_dir: Vec3,
257        major_radius: f64,
258        minor_radius: f64,
259    },
260}
261
262/// Bounds + a sane margin/diagonal for a body, erroring on empty/degenerate
263/// geometry the same way the plane path does.
264fn solid_extent(solid: &BrepSolid) -> Result<(Aabb, f64), String> {
265    let bounds = solid_aabb(solid);
266    if !bounds.minimum.x.is_finite() {
267        return Err("split_solid_by_surface: solid has no geometry".into());
268    }
269    let diagonal = bounds.diagonal();
270    if diagonal <= 0.0 {
271        return Err("split_solid_by_surface: solid is degenerate".into());
272    }
273    Ok((bounds, diagonal))
274}
275
276/// Build the closed tool solid for an analytic tool, sized to fully span the
277/// body wherever the analytic surface passes through it.
278fn build_tool_solid(solid: &BrepSolid, tool: &SplitSurface) -> Result<BrepSolid, String> {
279    let (_, diagonal) = solid_extent(solid)?;
280    let margin = diagonal.max(1.0);
281    match *tool {
282        SplitSurface::Plane { .. } => {
283            Err("build_tool_solid: plane is handled by the plane path".into())
284        }
285        SplitSurface::Cylinder {
286            axis_point,
287            axis_dir,
288            radius,
289        } => {
290            if radius <= 0.0 {
291                return Err("split_solid_by_surface: cylinder radius must be positive".into());
292            }
293            let axis = axis_dir.normalized()?;
294            // Extend the capped cylinder a full margin beyond the body's span
295            // along the axis so its caps never cut the body.
296            let (t_min, t_max) = axis_span(solid, axis_point, axis);
297            let base = axis_point.add(axis.scale(t_min - margin));
298            let height = (t_max - t_min) + 2.0 * margin;
299            make_cylinder_brep(base, axis, radius, height)
300        }
301        SplitSurface::Sphere { center, radius } => {
302            if radius <= 0.0 {
303                return Err("split_solid_by_surface: sphere radius must be positive".into());
304            }
305            // A sphere is already a closed, bounded region.
306            make_sphere_brep(center, radius, Vec3::new(0.0, 0.0, 1.0))
307        }
308        SplitSurface::Cone {
309            apex,
310            axis_dir,
311            half_angle,
312        } => {
313            if !(half_angle > 0.0 && half_angle < std::f64::consts::FRAC_PI_2) {
314                return Err("split_solid_by_surface: cone half-angle must be in (0, pi/2)".into());
315            }
316            let axis = axis_dir.normalized()?;
317            // Distance of the farthest body point along +axis from the apex.
318            let (_, d_max) = axis_span(solid, apex, axis);
319            if d_max <= 0.0 {
320                return Err(
321                    "split_solid_by_surface: cone does not reach the solid (body is behind the apex)"
322                        .into(),
323                );
324            }
325            let big_h = d_max + margin;
326            // Realise the nappe as a cone whose apex sits at `apex` and whose
327            // base cap lands `big_h` past it along +axis: base at apex+axis·H,
328            // built with axis pointing back to the apex so top(0-radius)=apex.
329            let base = apex.add(axis.scale(big_h));
330            let base_radius = big_h * half_angle.tan();
331            make_cone_brep(base, axis.scale(-1.0), base_radius, 0.0, big_h)
332        }
333        SplitSurface::Torus {
334            center,
335            axis_dir,
336            major_radius,
337            minor_radius,
338        } => {
339            if minor_radius <= 0.0 || major_radius <= 0.0 {
340                return Err("split_solid_by_surface: torus radii must be positive".into());
341            }
342            // A torus is already a closed, bounded region.
343            make_torus_brep(center, axis_dir, major_radius, minor_radius)
344        }
345    }
346}
347
348/// Signed span `[min, max]` of the body's vertices projected onto the axis line
349/// through `origin` along the unit direction `axis`.
350fn axis_span(solid: &BrepSolid, origin: Vec3, axis: Vec3) -> (f64, f64) {
351    let mut t_min = f64::INFINITY;
352    let mut t_max = f64::NEG_INFINITY;
353    for vertex in &solid.vertices {
354        let t = vertex.point.sub(origin).dot(axis);
355        t_min = t_min.min(t);
356        t_max = t_max.max(t);
357    }
358    (t_min, t_max)
359}
360
361/// Split `solid` into pieces by an analytic tool surface (Golovanov §6.4).
362///
363/// For the `Plane` tool this is exactly `split_solid_by_plane`, returned as
364/// `[below, above]`.  For a closed analytic tool region (cylinder / sphere /
365/// cone / torus) the two pieces are `[inside, outside]` where `inside =
366/// solid ∩ tool` and `outside = solid − tool`.  Both pieces are guaranteed
367/// non-empty and valid; their volumes sum to the original.
368///
369/// Contract: when the tool does not actually divide the body into two
370/// non-degenerate pieces (it misses the body, or wholly contains / is wholly
371/// contained so one side is empty), this returns a clear `Err` rather than a
372/// degenerate/empty piece.
373pub fn split_solid_by_surface(
374    solid: &BrepSolid,
375    tool: &SplitSurface,
376) -> Result<Vec<BrepSolid>, String> {
377    if let SplitSurface::Plane { point, normal } = *tool {
378        let (below, above) = split_solid_by_plane(solid, point, normal)?;
379        return Ok(vec![below, above]);
380    }
381
382    let tool_solid = build_tool_solid(solid, tool)?;
383    let options = BooleanOptions::default();
384    let inside = boolean_operation(solid, &tool_solid, BooleanOperation::Intersect, &options);
385    let outside = boolean_operation(solid, &tool_solid, BooleanOperation::Subtract, &options);
386
387    match (inside, outside) {
388        (Ok(inside), Ok(outside))
389            if !is_empty_piece(&inside)
390                && !is_empty_piece(&outside)
391                && inside.validate().is_empty()
392                && outside.validate().is_empty() =>
393        {
394            Ok(vec![inside, outside])
395        }
396        _ => Err("split_solid_by_surface: tool surface does not divide the solid".into()),
397    }
398}
399
400/// Map a face's exact analytic carrier to the closed tool region that splits a
401/// body by that surface.  Reuses the kernel's own analytic recognition so the
402/// caller only has to hand over the selected face's surface (no host-side
403/// geometry extraction).  Unrecognized / general-revolution carriers are
404/// reported as unsupported (deferred), never approximated.
405fn recognized_split_surface(surface: &NurbsSurface) -> Result<SplitSurface, String> {
406    let analytic = surface
407        .analytic()
408        .ok_or("split_solid_by_face_surface: selected face is not an analytic surface")?;
409    match analytic {
410        AnalyticSurface::Plane {
411            origin,
412            u_dir,
413            v_dir,
414            ..
415        } => {
416            let normal = u_dir.cross(*v_dir).normalized()?;
417            Ok(SplitSurface::Plane {
418                point: *origin,
419                normal,
420            })
421        }
422        AnalyticSurface::RuledRevolution {
423            frame,
424            rho0,
425            rho1,
426            height,
427        } => {
428            // Cylinder when the two radii coincide, otherwise a cone/frustum.
429            let scale = rho0.abs().max(rho1.abs()).max(1.0);
430            if (rho0 - rho1).abs() <= 1e-9 * scale {
431                Ok(SplitSurface::Cylinder {
432                    axis_point: frame.origin,
433                    axis_dir: frame.axis,
434                    radius: 0.5 * (rho0 + rho1),
435                })
436            } else {
437                // radius(axial) = rho0 + slope·axial, apex where radius = 0.
438                let slope = (rho1 - rho0) / height;
439                let axial_apex = -rho0 / slope;
440                let apex = frame.origin.add(frame.axis.scale(axial_apex));
441                // The nappe opens in the direction of increasing radius.
442                let axis_dir = if slope >= 0.0 {
443                    frame.axis
444                } else {
445                    frame.axis.scale(-1.0)
446                };
447                Ok(SplitSurface::Cone {
448                    apex,
449                    axis_dir,
450                    half_angle: slope.abs().atan(),
451                })
452            }
453        }
454        AnalyticSurface::Sphere { frame, radius } => Ok(SplitSurface::Sphere {
455            center: frame.origin,
456            radius: *radius,
457        }),
458        AnalyticSurface::Torus {
459            frame,
460            major_radius,
461            minor_radius,
462        } => Ok(SplitSurface::Torus {
463            center: frame.origin,
464            axis_dir: frame.axis,
465            major_radius: *major_radius,
466            minor_radius: *minor_radius,
467        }),
468        AnalyticSurface::Revolution { .. } => Err(
469            "split_solid_by_face_surface: general revolved surfaces are not supported as a cut tool"
470                .into(),
471        ),
472    }
473}
474
475/// Split `solid` by the analytic carrier of a selected face `surface`
476/// (Golovanov §6.4).  The face may be a plane, cylinder, cone, or sphere; the
477/// carrier is extended to fully span the body.  Returns the two pieces
478/// (`[below, above]` for a plane, `[inside, outside]` otherwise).  Errors on
479/// non-analytic / general-revolution faces, or when the carrier does not
480/// cleanly divide the body.
481pub fn split_solid_by_face_surface(
482    solid: &BrepSolid,
483    surface: &NurbsSurface,
484) -> Result<Vec<BrepSolid>, String> {
485    let tool = recognized_split_surface(surface)?;
486    split_solid_by_surface(solid, &tool)
487}
488