Skip to main content

brep_offset/offset/offset_shell/
solid.rs

1//! Whole-solid offset (D3).
2//!
3//! `offset_solid` runs the shell pipeline in its WHOLE-BODY mode
4//! (`Body::Whole`): every face is retained, there is no opening and no wall,
5//! the source's own faces are not assembled, and the body is the offset
6//! carriers alone, closed at every sharp junction by the extend-and-intersect
7//! the pipeline already does for a shell's retained faces.
8//!
9//! The sign is the natural one: a positive distance grows the body along its
10//! outward normals, a negative one shrinks it. `offset_shell` takes the
11//! opposite sign (positive = inward wall), so the pipeline is asked for
12//! `-distance`.
13//!
14//! `OffsetCorners::Rounded` (D3) is the true parallel body, the Minkowski sum
15//! with a ball of radius `|d|`: the sharp body with every convex edge image
16//! (outward) or concave edge image (inward) rolled by the blend network at
17//! radius `|d|`, which is what puts the exact cylinder or torus cap on each
18//! straight or circular edge and the corner ball at each vertex. The blend's
19//! constructions are reused through `fillet_edges`, never rebuilt here.
20use super::debug_enabled;
21use super::pipeline::{offset_body, Body};
22use super::{OffsetFaceRole, OffsetShellFaceImageRecord, OffsetShellResultRecord};
23use crate::classification::PolygonClass;
24use crate::topology::{BrepSolid, EdgeRecord, FaceRecord};
25use crate::{
26    boolean_operation, fillet_edges, project_point_to_surface, BooleanOperation, BooleanOptions,
27    KernelRefusal, KernelStage, OrRefuse, RefusalClass, Vec2, Vec3,
28};
29use rustc_hash::FxHashMap as HashMap;
30use serde::{Deserialize, Serialize};
31
32/// How the offset body closes the joins between offset faces.
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
34#[serde(rename_all = "lowercase")]
35pub enum OffsetCorners {
36    #[default]
37    Sharp,
38    /// The exact parallel body: convex joins (outward) or concave joins
39    /// (inward) carry the rolling ball's cylinder, torus or sphere.
40    Rounded,
41}
42
43/// Offset every face of `source` by `distance` (positive grows) and join the
44/// offset faces into a closed body.
45pub fn offset_solid(
46    source: &BrepSolid,
47    distance: f64,
48    corners: OffsetCorners,
49) -> Result<OffsetShellResultRecord, KernelRefusal> {
50    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_solid")? {
51        let mut record = offset_solid(&scaled.source, scaled.distance, corners).map_err(|error| scaled.refusal(error))?;
52        record.solid = scaled.back(&record.solid, "offset_solid")?;
53        return Ok(record);
54    }
55    let built = offset_solid_unread(source, distance, corners)?;
56    if corners == OffsetCorners::Rounded {
57        if let Some(refusal) = super::rim_witness::rim_witness_refusal(source, &built.solid, distance) {
58            return Err(refusal);
59        }
60    }
61    Ok(built)
62}
63
64/// [`offset_solid`] before its result is read back ([`super::rim_witness`]).
65fn offset_solid_unread(
66    source: &BrepSolid,
67    distance: f64,
68    corners: OffsetCorners,
69) -> Result<OffsetShellResultRecord, KernelRefusal> {
70    let grown = offset_solid_joined(source, distance, corners)?;
71    if corners == OffsetCorners::Rounded && distance > 0.0 {
72        if let Some(carved) = super::bore_dimples::carve_bore_dimples(source, &grown.solid, distance) {
73            let operands = grown
74                .solid
75                .shells
76                .iter()
77                .flat_map(|shell| &shell.faces)
78                .zip(&grown.face_images)
79                .map(|(face, image)| (face, image.clone()))
80                .collect::<Vec<_>>();
81            let cap = OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 };
82            if let Ok(face_images) = provenance_by_surface(&carved, &operands, Some(&cap)) {
83                return Ok(OffsetShellResultRecord { solid: carved, face_images });
84            }
85        }
86    }
87    Ok(grown)
88}
89
90/// [`offset_solid`] before the bore dimples ([`super::bore_dimples`]): the
91/// sharp body, or its rounding, or a decomposition's.
92fn offset_solid_joined(
93    source: &BrepSolid,
94    distance: f64,
95    corners: OffsetCorners,
96) -> Result<OffsetShellResultRecord, KernelRefusal> {
97    // A right prism over a smooth convex profile grows by its parts, the
98    // rims' tubes fitted about the profile (`BREP_OFFSET_PRISM_GROWTH`).
99    if corners == OffsetCorners::Rounded && distance > 0.0 {
100        if let Some(grown) = super::prism_growth::prism_growth(source, distance) {
101            return Ok(grown);
102        }
103    }
104    // A solid of revolution grows by its half-section's growth revolved,
105    // exact, ahead of the pipeline and the blend that rounds its rims
106    // (`BREP_OFFSET_REVOLVED_FIRST`).
107    if corners == OffsetCorners::Rounded && distance > 0.0 && revolved_first_on() {
108        if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
109            return Ok(grown);
110        }
111    }
112    if corners == OffsetCorners::Rounded && distance > 0.0 {
113        if let Some(grown) = grown_across_reflex_edges(source, distance) {
114            return Ok(grown);
115        }
116    }
117    // A right prism over a polygon whose shrink drops an edge or splits the
118    // body: the planar erosion extruded, exact and without a boolean
119    // (`BREP_OFFSET_PRISM_EROSION`); a solid of revolution over a polygon
120    // section likewise, its section eroded and revolved
121    // (`BREP_OFFSET_REVOLVED_EROSION`).
122    if corners == OffsetCorners::Rounded && distance < 0.0 {
123        if let Some(eroded) = super::prism_erosion::prism_erosion(source, distance, true) {
124            return Ok(eroded);
125        }
126        if let Some(eroded) = super::revolved_erosion::revolved_erosion(source, distance, true) {
127            return Ok(eroded);
128        }
129    }
130    let widened_before = super::outward_side_widen::widened_count();
131    let sharp = match offset_body(source, &[], -distance, Body::Whole, "offset_solid") {
132        // A rounded growth whose sharp body was assembled only because a
133        // curved face's side was widened (`outward_side_widen`) used to be
134        // refused there and built by the revolved-parallel lane, which is
135        // exact; a solid of revolution keeps that lane, and any other body
136        // (the lane declines it) rounds the sharp body.
137        Ok(_) if corners == OffsetCorners::Rounded
138            && distance > 0.0
139            && super::outward_side_widen::widened_count() != widened_before
140            && super::revolved_parallel::revolved_parallel(source, distance).is_some() =>
141        {
142            return Ok(super::revolved_parallel::revolved_parallel(source, distance).unwrap());
143        }
144        Ok(sharp) => sharp,
145        Err(error) => {
146            if corners == OffsetCorners::Rounded {
147                if let Some(eroded) = super::prism_erosion::prism_erosion(source, distance, false) {
148                    return Ok(eroded);
149                }
150                if distance < 0.0 {
151                    if let Some(eroded) = super::revolved_erosion::revolved_erosion(source, distance, false) {
152                        return Ok(eroded);
153                    }
154                }
155                if let Some(grown) = grown_by_pieces(source, distance)? {
156                    return Ok(grown);
157                }
158                if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
159                    return Ok(grown);
160                }
161                if let Some(grown) = super::pipe_parallel::pipe_parallel(source, distance) {
162                    return Ok(grown);
163                }
164            }
165            // A right prism shrunk past its profile's curvature: the trimmed
166            // inward offset extruded between the moved caps (sharp and rounded
167            // joins agree on a convex prism's shrink).
168            if distance < 0.0 {
169                if let Some(shrunk) = super::prism_parallel::prism_parallel(source, distance)? {
170                    return Ok(shrunk);
171                }
172            }
173            return Err(error);
174        }
175    };
176    match corners {
177        OffsetCorners::Sharp => Ok(sharp),
178        OffsetCorners::Rounded => match round_offset_joins(sharp, distance) {
179            Ok(rounded) => Ok(rounded),
180            // A mitred body cannot carry the ball over a vertex of degree four
181            // or more; a convex polyhedron's parallel body is built directly.
182            Err(error) => match crate::blend::convex_parallel::convex_polyhedron_parallel(source, distance) {
183                Ok(Some((solid, images))) if solid.validate().is_empty() => {
184                    let face_images = images
185                        .into_iter()
186                        .map(|image| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: image.unwrap_or(0) })
187                        .collect();
188                    Ok(OffsetShellResultRecord { solid, face_images })
189                }
190                _ => super::revolved_parallel::revolved_parallel(source, distance)
191                    .or_else(|| super::pipe_parallel::pipe_parallel(source, distance))
192                    .ok_or(error),
193            },
194        },
195    }
196}
197
198/// `BREP_OFFSET_REVOLVED_FIRST` (default on; `=0` restores): the revolved-parallel lane
199/// answers a rounded growth before the pipeline, not only after its refusal.
200fn revolved_first_on() -> bool {
201    switch!("BREP_OFFSET_REVOLVED_FIRST", true)
202}
203
204
205/// `BREP_OFFSET_GROW_BY_PIECES` (default on; `=0` restores): [`grown_by_pieces`].
206fn grow_by_pieces_enabled() -> bool {
207    switch!("BREP_OFFSET_GROW_BY_PIECES", true)
208}
209
210
211/// The ROUNDED growth of a body whose own offset body the pipeline could not
212/// assemble, as the union of its pieces' growths: the parallel body of a
213/// union is the union of the parallel bodies, `(A ∪ B) ⊕ D = (A ⊕ D) ∪
214/// (B ⊕ D)`, for any pieces whose union is the body.
215///
216/// Cause (a drum with a groove 1.6 wide grown by 1, brep-bench
217/// offset/grooved-drum-grown): the groove's walls offset across each other,
218/// "a skin partly shadowed that way is not yet assembled", and even assembled
219/// the sharp body would have no groove left to round, while the case's notch
220/// is the two tori about the groove's outer rims. Cut at the planes of its
221/// planar faces the drum is three cylinders; each grows by the pipeline's own
222/// rounded offset, and their union carries the notch where the two rim tori
223/// cross.
224///
225/// The cuts are chosen by [`thin_pair_planes`] (the planes parallel to a pair
226/// of planar faces whose offsets cross), each kept only where it divides a
227/// piece (`split_solid_by_plane`). A SHRINK runs the same construction on the
228/// body's complement in a frame box ([`shrunk_by_pieces`]). Every piece must
229/// grow and the union must validate; anything else declines and the
230/// pipeline's own refusal stands. The faces are all `Offset` images with
231/// `source_face_id` 0, as the rounded caps are: a face of the union may carry
232/// the growth of several source faces' pieces.
233///
234/// A decline is `Ok(None)`; the one refusal that comes through is a shrink
235/// whose grown complement covers the whole body, which is the answer itself.
236fn grown_by_pieces(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
237    if !grow_by_pieces_enabled() {
238        return Ok(None);
239    }
240    match grown_by_pieces_impl(source, distance) {
241        Ok(result) => Ok(result),
242        Err(error) if matches!(&error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "offset_solid_shrinks_to_nothing") => Err(error),
243        Err(error) => {
244            os_debug!("grow by pieces declined: {error}");
245            Ok(None)
246        }
247    }
248}
249
250fn grown_by_pieces_impl(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
251    if distance < 0.0 {
252        return shrunk_by_pieces(source, -distance);
253    }
254    let Some(sets) = thin_pair_planes(source, distance, true)? else {
255        return Ok(None);
256    };
257    let mut answer = None;
258    for planes in &sets {
259        match grown_union(source, planes, distance) {
260            Ok(Some(solid)) => {
261                answer = Some(solid);
262                break;
263            }
264            Ok(None) => {}
265            Err(error) => os_debug!("grow by pieces: {} plane(s) declined: {error}", planes.len()),
266        }
267    }
268    let Some(solid) = answer else {
269        return Ok(None);
270    };
271    let face_images = solid
272        .shells
273        .iter()
274        .flat_map(|shell| &shell.faces)
275        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
276        .collect();
277    Ok(Some(OffsetShellResultRecord { solid, face_images }))
278}
279
280/// Roll the sharp body's joins that the ball of radius `|distance|` rounds:
281/// the convex edges of an outward offset, the concave edges of an inward one.
282/// A body with no such edge is already the parallel body and is returned as
283/// it is. Provenance: a face still on a sharp-body surface keeps that face's
284/// image; a cap (a cylinder, torus or corner ball the blend built, which lies
285/// on no offset face) is an `Offset` image with `source_face_id` 0, because it
286/// rounds a JOIN between source faces and has no single source face.
287fn round_offset_joins(
288    sharp: OffsetShellResultRecord,
289    distance: f64,
290) -> Result<OffsetShellResultRecord, KernelRefusal> {
291    let wanted_convex = distance > 0.0;
292    let midpoints = sharp_join_midpoints(&sharp.solid, wanted_convex)?;
293    if midpoints.is_empty() {
294        return Ok(sharp);
295    }
296    let solid = fillet_edges(&sharp.solid, &midpoints, None, distance.abs(), false, None)
297        .map_err(|error| {
298            error.with_message(|message| {
299                format!(
300                    "offset_solid: the rounded joins of the offset body could not be built \
301                     ({} edge(s) at radius {:.6}): {message}",
302                    midpoints.len(),
303                    distance.abs()
304                )
305            })
306        })?;
307    let operands = sharp
308        .solid
309        .shells
310        .iter()
311        .flat_map(|shell| &shell.faces)
312        .zip(&sharp.face_images)
313        .map(|(face, image)| (face, image.clone()))
314        .collect::<Vec<_>>();
315    let cap = OffsetShellFaceImageRecord {
316        role: OffsetFaceRole::Offset,
317        source_face_id: 0,
318    };
319    let face_images = provenance_by_surface(&solid, &operands, Some(&cap))?;
320    Ok(OffsetShellResultRecord { solid, face_images })
321}
322
323/// Per-face provenance of a body whose faces lie on its operands' surfaces (a
324/// boolean result, a blend's untouched faces): each result face takes the
325/// image of the FIRST operand face whose surface carries an interior point of
326/// it and whose trim contains that point's foot. Operands are matched in the
327/// order given, so a coincident pair (a held face and the opening it copies)
328/// resolves to whichever is listed first. A face on no operand surface takes
329/// `unmatched`, or refuses by name when there is none.
330pub(super) fn provenance_by_surface(
331    result: &BrepSolid,
332    operands: &[(&FaceRecord, OffsetShellFaceImageRecord)],
333    unmatched: Option<&OffsetShellFaceImageRecord>,
334) -> Result<Vec<OffsetShellFaceImageRecord>, KernelRefusal> {
335    let band = 1e-6 * crate::solid_scale(result).max(1.0);
336    let mut images = Vec::new();
337    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
338        let seeds = super::source_seeds(result, face.id)?;
339        let seed = seeds[0];
340        let point = face.surface.evaluate(seed.x, seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
341        let mut found = None;
342        for (operand, image) in operands {
343            let Ok(foot) = project_point_to_surface(&operand.surface, point) else { continue };
344            if foot.distance > band {
345                continue;
346            }
347            let inside = super::parameter_point_in_face(operand, Vec2 { x: foot.u, y: foot.v }, 1e-8)
348                .is_ok_and(|class| class != PolygonClass::Outside);
349            if inside {
350                found = Some(image.clone());
351                break;
352            }
353        }
354        match found.or_else(|| unmatched.cloned()) {
355            Some(image) => images.push(image),
356            None => {
357                return Err(KernelRefusal::internal(
358                    KernelStage::Sew,
359                    "offset_shell_provenance_lost",
360                    format!(
361                        "offset_shell: result face {} at ({:.4}, {:.4}, {:.4}) lies on no operand face",
362                        face.id, point.x, point.y, point.z
363                    ),
364                ))
365            }
366        }
367    }
368    Ok(images)
369}
370
371/// Midpoints of the SHARP edges of `solid` whose convexity is `convex`: an
372/// edge bordering two different faces whose outward normals differ there, read
373/// at the edge midpoint. Tangent junctions (a blend face meeting its support)
374/// and face-local seams are not joins and are skipped.
375fn sharp_join_midpoints(solid: &BrepSolid, convex: bool) -> Result<Vec<Vec3>, KernelRefusal> {
376    // Cosine of the dihedral angle above which two faces read as tangent.
377    const TANGENT_COSINE: f64 = 1.0 - 1e-6;
378    let faces = solid
379        .shells
380        .iter()
381        .flat_map(|shell| &shell.faces)
382        .collect::<Vec<_>>();
383    let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
384    for face in &faces {
385        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
386            uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
387        }
388    }
389    let mut midpoints = Vec::new();
390    for edge in &solid.edges {
391        if edge.degenerate {
392            continue;
393        }
394        let Some(pair) = uses.get(&edge.id) else { continue };
395        if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
396            continue;
397        }
398        if edge_is_convex_join(edge, pair[0], pair[1].0, TANGENT_COSINE)? == Some(convex) {
399            midpoints.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Classify, "evaluate")?);
400        }
401    }
402    Ok(midpoints)
403}
404
405/// `Some(true)` for a convex join, `Some(false)` for a concave one, `None` for
406/// a tangent junction. With `t` the direction the first face's coedge runs
407/// along the edge and `n_a` that face's outward normal, `n_a × t` points into
408/// the first face; the join is convex when the second face's outward normal
409/// points away from there.
410fn edge_is_convex_join(
411    edge: &EdgeRecord,
412    (first, first_forward): (&FaceRecord, bool),
413    second: &FaceRecord,
414    tangent_cosine: f64,
415) -> Result<Option<bool>, KernelRefusal> {
416    let t = 0.5 * (edge.t0 + edge.t1);
417    let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
418    let point = derivatives[0];
419    let mut tangent = derivatives[1].normalized().or_refuse(KernelStage::Classify, "normalized")?;
420    if !first_forward {
421        tangent = tangent.scale(-1.0);
422    }
423    let normal_a = outward_normal_at(first, point)?;
424    let normal_b = outward_normal_at(second, point)?;
425    if normal_a.dot(normal_b) >= tangent_cosine {
426        return Ok(None);
427    }
428    Ok(Some(normal_b.dot(normal_a.cross(tangent)) < 0.0))
429}
430
431fn outward_normal_at(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
432    let foot = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
433    super::face_normal(face, foot.u, foot.v)
434}
435
436// ---------------------------------------------------------------------------
437// Shell as a boolean
438// ---------------------------------------------------------------------------
439
440/// The textbook shell: the offset body with the opening faces HELD (copied at
441/// distance zero, so they cancel in the difference), then `source − body` for
442/// an inward shell and `body − source` for an outward one. The walls at the
443/// openings come out of the boolean. `distance` carries `offset_shell`'s sign
444/// (positive inward).
445///
446/// This is the lane `offset_shell` falls back to when its direct construction
447/// refuses by one of its own names (`direct_refusal_takes_the_boolean_lane`);
448/// it is public so the two can be compared on any fixture. The result's
449/// `face_images` are read back from the operands by surface
450/// (`provenance_by_surface`): `Offset` for a face of the body's skins,
451/// `Wall` for a held opening face, `Source` for a face of the source.
452pub fn offset_shell_by_boolean(
453    source: &BrepSolid,
454    opening_face_ids: &[u64],
455    distance: f64,
456) -> Result<OffsetShellResultRecord, KernelRefusal> {
457    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
458        let mut record = offset_shell_by_boolean(&scaled.source, opening_face_ids, scaled.distance)
459            .map_err(|error| scaled.refusal(error))?;
460        record.solid = scaled.back(&record.solid, "offset_shell")?;
461        return Ok(record);
462    }
463    if opening_face_ids.is_empty() {
464        return Err(KernelRefusal::input(
465            KernelStage::Collect,
466            "offset_shell_no_opening",
467            "offset_shell: at least one opening face is required",
468        ));
469    }
470    let body = offset_body(source, opening_face_ids, distance, Body::Whole, "offset_shell_by_boolean")
471        .or_else(|error| {
472            if !direct_refusal_takes_the_boolean_lane(&error) {
473                return Err(error);
474            }
475            let result = super::joint_offset::build(source, opening_face_ids, distance);
476            if let Err(reason) = &result {
477                os_debug!("joint offset refused: {reason}");
478            }
479            result.map_err(|_| error)
480        })?;
481    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
482    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
483        .map_err(|error| {
484            error.with_message(|message| {
485                format!("offset_shell: the boolean lane's difference could not be built: {message}")
486            })
487        })?;
488    // The body's faces first, so the ring on a held face's plane reads as
489    // that face's `Wall` rather than as the coincident source opening.
490    let mut operands = body
491        .solid
492        .shells
493        .iter()
494        .flat_map(|shell| &shell.faces)
495        .zip(&body.face_images)
496        .map(|(face, image)| (face, image.clone()))
497        .collect::<Vec<_>>();
498    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
499        (
500            face,
501            OffsetShellFaceImageRecord {
502                role: OffsetFaceRole::Source,
503                source_face_id: face.id,
504            },
505        )
506    }));
507    let face_images = provenance_by_surface(&solid, &operands, None)?;
508    Ok(OffsetShellResultRecord { solid, face_images })
509}
510
511/// Lane O row 34: the CLOSED hollow, a shell with no openings. The offset
512/// body, the whole source grown or shrunk with sharp joins, against the
513/// source: `source − body` inward and `body − source` outward, so the result
514/// is the outer shell and the inner void's shell, with the walls of the band
515/// between them. `distance` carries `offset_shell`'s sign (positive inward).
516/// `face_images` are read back from the operands by surface as in
517/// [`offset_shell_by_boolean`]: `Offset` for the body's faces, `Source` for
518/// the source's.
519///
520/// The construction checks itself: the result is exactly two shells and its
521/// volume is the difference of the operands' volumes.
522pub fn offset_shell_closed(source: &BrepSolid, distance: f64) -> Result<OffsetShellResultRecord, KernelRefusal> {
523    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell_closed")? {
524        let mut record = offset_shell_closed(&scaled.source, scaled.distance).map_err(|error| scaled.refusal(error))?;
525        record.solid = scaled.back(&record.solid, "offset_shell_closed")?;
526        return Ok(record);
527    }
528    let body = offset_body(source, &[], distance, Body::Whole, "offset_shell_closed")?;
529    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
530    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
531        .map_err(|error| {
532            error.with_message(|message| format!("offset_shell: the closed hollow's difference could not be built: {message}"))
533        })?;
534    let volume = |solid: &BrepSolid| {
535        crate::solid_mass_properties(solid)
536            .map(|properties| properties.volume)
537            .or_refuse(KernelStage::Validate, "solid_mass_properties")
538    };
539    let expected = volume(kept)? - volume(removed)?;
540    let measured = volume(&solid)?;
541    if solid.shells.len() != 2 || !(expected > 0.0) || !((measured - expected).abs() <= 1e-9 * expected) {
542        return Err(KernelRefusal::internal(
543            KernelStage::Validate,
544            "offset_shell_closed_hollow",
545            format!(
546                "offset_shell: the closed hollow is not the band between its operands ({} shells, volume {measured} against {expected})",
547                solid.shells.len()
548            ),
549        ));
550    }
551    let mut operands = body
552        .solid
553        .shells
554        .iter()
555        .flat_map(|shell| &shell.faces)
556        .zip(&body.face_images)
557        .map(|(face, image)| (face, image.clone()))
558        .collect::<Vec<_>>();
559    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
560        (face, OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
561    }));
562    let face_images = provenance_by_surface(&solid, &operands, None)?;
563    Ok(OffsetShellResultRecord { solid, face_images })
564}
565
566/// Whether a refusal of the direct pipeline is one of its OWN named
567/// inabilities, the ones the boolean recipe can answer differently: an
568/// `offset_shell_*` unsupported-geometry or internal refusal, or the
569/// assembler's typed non-integral-genus and degenerate-arrangement refusals
570/// that `cause_in_front` carries a shell cause through. Input refusals
571/// (distance, foreign opening, no retained face) and soundness refusals are
572/// not: the first name a caller's mistake, the second a body that must not be
573/// shipped by any route.
574pub fn direct_refusal_takes_the_boolean_lane(refusal: &KernelRefusal) -> bool {
575    match &refusal.class {
576        RefusalClass::UnsupportedGeometry { what } | RefusalClass::Internal { what } => {
577            what.starts_with("offset_shell_")
578        }
579        RefusalClass::NonIntegralGenus { .. } => {
580            refusal.message.starts_with("offset_shell")
581                || (bare_genus_takes_the_boolean_lane() && refusal.message.starts_with("boolean assembly:"))
582        }
583        RefusalClass::DegenerateArrangement { .. } => refusal.message.starts_with("offset_shell"),
584        _ => false,
585    }
586}
587
588/// `BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE` (default on; `=0` restores): the
589/// direct pipeline's assembly refusing a non-integral genus takes the boolean
590/// lane even with no shell cause put in front of it. Which sentence a refusal
591/// carries says nothing about whether the lane can answer:
592/// `inbox_20261017_negative_shell` only reached the lane through the note of
593/// an omission, and the omission was a misread fillet's true skin; reading
594/// that skin correctly (`BREP_OFFSET_TANGENT_EDGE_EUCLID`) left the same
595/// failed assembly with no note, and the shell was refused.
596fn bare_genus_takes_the_boolean_lane() -> bool {
597    crate::switch!("BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE", true)
598}
599
600/// The cut planes: every planar face's plane parallel to a THIN PAIR, two
601/// planar faces with opposite outward normals closer than `2·amount` that face
602/// each other across void (`grow`) or across material (shrink) — the pair
603/// whose offsets cross. Deduplicated. Two sets are offered in turn: every
604/// planar face's plane parallel to a thin pair, then the thin pairs' own
605/// planes alone (when fewer), because the boolean that unions the grown
606/// pieces can fail on where one set's pieces meet and not the other's (the
607/// dumbbell's complement cut at all four y planes left sliver edges where the
608/// neck-mouth rounds of adjacent pieces cross). `None` when there is no thin
609/// pair or every set has more than eight planes.
610fn thin_pair_planes(solid: &BrepSolid, amount: f64, grow: bool) -> Result<Option<Vec<Vec<(Vec3, Vec3)>>>, KernelRefusal> {
611    let band = 1e-9 * crate::solid_scale(solid).max(1.0);
612    // Each planar face's plane, its OUTWARD normal.
613    let mut faces: Vec<(Vec3, Vec3)> = Vec::new();
614    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
615        let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
616            continue;
617        };
618        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
619        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
620        let Ok(outward) = super::face_normal(face, 0.5 * (u0 + u1), 0.5 * (v0 + v1)) else {
621            continue;
622        };
623        faces.push((point, if outward.dot(normal) < 0.0 { normal.scale(-1.0) } else { normal }));
624    }
625    let mut directions: Vec<Vec3> = Vec::new();
626    let mut pairs: Vec<(usize, usize)> = Vec::new();
627    for (index, (point, normal)) in faces.iter().enumerate() {
628        for (offset, (other, other_normal)) in faces[index + 1..].iter().enumerate() {
629            if normal.dot(*other_normal) > -1.0 + 1e-12 {
630                continue;
631            }
632            // Signed gap from this face's plane to the other's, along this
633            // face's outward normal: positive across void, negative across
634            // material.
635            let gap = other.sub(*point).dot(*normal);
636            let thin = if grow { gap > band && gap < 2.0 * amount } else { gap < -band && -gap < 2.0 * amount };
637            if thin {
638                pairs.push((index, index + 1 + offset));
639                if !directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
640                    directions.push(*normal);
641                }
642            }
643        }
644    }
645    if directions.is_empty() {
646        return Ok(None);
647    }
648    let push = |planes: &mut Vec<(Vec3, Vec3)>, point: Vec3, normal: Vec3| {
649        let seen = planes
650            .iter()
651            .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
652        if !seen {
653            planes.push((point, normal));
654        }
655    };
656    let mut parallel: Vec<(Vec3, Vec3)> = Vec::new();
657    for (point, normal) in &faces {
658        if directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
659            push(&mut parallel, *point, *normal);
660        }
661    }
662    let mut paired: Vec<(Vec3, Vec3)> = Vec::new();
663    for (first, second) in &pairs {
664        push(&mut paired, faces[*first].0, faces[*first].1);
665        push(&mut paired, faces[*second].0, faces[*second].1);
666    }
667    let mut sets = Vec::new();
668    if parallel.len() <= 8 {
669        sets.push(parallel.clone());
670    }
671    if paired.len() <= 8 && paired.len() < parallel.len() {
672        sets.push(paired);
673    }
674    Ok((!sets.is_empty()).then_some(sets))
675}
676
677/// `solid` cut by every plane that divides a piece of it.
678fn cut_by_planes(solid: &BrepSolid, planes: &[(Vec3, Vec3)]) -> Vec<BrepSolid> {
679    let mut pieces = vec![solid.clone()];
680    for (point, normal) in planes {
681        let mut next = Vec::with_capacity(pieces.len() * 2);
682        for piece in pieces {
683            match crate::split_solid_by_plane(&piece, *point, *normal) {
684                Ok((below, above)) => {
685                    next.push(below);
686                    next.push(above);
687                }
688                Err(_) => next.push(piece),
689            }
690        }
691        pieces = next;
692    }
693    pieces
694}
695
696/// The SHRINK by `amount` through the complement: `S ⊖ D = S − ((F − S) ⊕ D)`
697/// for a frame box `F` reaching past `S` by more than `amount`, where the
698/// complement's growth is the union of its pieces' growths, the pieces cut at
699/// the planes of `S`'s planar faces.
700///
701/// Cause (a drum with a flange 1.6 thick shrunk by 1, brep-bench
702/// offset/flanged-drum-shrunk): the flange's two faces offset across each
703/// other ("a skin partly shadowed that way is not yet assembled"), and the
704/// low ridge the case reads is the two concave tori about the flange's inner
705/// rims, which the complement's pieces carry as the rounds of their own
706/// convex rims.
707fn shrunk_by_pieces(source: &BrepSolid, amount: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
708    let Some(sets) = thin_pair_planes(source, amount, false)? else {
709        return Ok(None);
710    };
711    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
712    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
713    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
714        for control in face.surface.control_points.iter().flatten() {
715            let Ok(point) = control.point() else { return Ok(None) };
716            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
717            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
718        }
719    }
720    let margin = 3.0 * amount;
721    let corner = low.sub(Vec3::new(margin, margin, margin));
722    let size = high.sub(low).add(Vec3::new(2.0 * margin, 2.0 * margin, 2.0 * margin));
723    let frame = crate::make_box_brep(corner, size.x, size.y, size.z).or_refuse(KernelStage::Refine, "make_box_brep")?;
724    let options = BooleanOptions::default();
725    let outside = boolean_operation(&frame, source, BooleanOperation::Subtract, &options)?;
726    let mut answer = None;
727    // Each plane set's grown pieces, kept for the subtraction below: growing
728    // them is most of a set's cost (a cut, a sharp offset and a rounding per
729    // piece), and the subtraction reads exactly the pieces the union did.
730    let mut grown_sets: Vec<Result<Option<Vec<BrepSolid>>, KernelRefusal>> = Vec::with_capacity(sets.len());
731    for planes in &sets {
732        let grown = grown_pieces(&outside, planes, amount);
733        let attempt = match &grown {
734            Ok(Some(grown)) => union_of_grown(grown),
735            Ok(None) => Ok(None),
736            Err(error) => Err(error.clone()),
737        }
738        .and_then(|reach| match reach {
739            Some(reach) => boolean_operation(source, &reach, BooleanOperation::Subtract, &options).map(Some),
740            None => Ok(None),
741        });
742        grown_sets.push(grown);
743        match attempt {
744            Ok(Some(solid)) if solid.validate().is_empty() => {
745                answer = Some(solid);
746                break;
747            }
748            Ok(_) => {}
749            Err(error) => os_debug!("shrink by pieces: {} plane(s) declined: {error}", planes.len()),
750        }
751    }
752    if answer.is_none() && shrink_by_subtraction_enabled() {
753        for (planes, grown) in sets.iter().zip(grown_sets) {
754            match grown.and_then(|grown| subtracted_one_by_one(source, grown)) {
755                Ok(Some(solid)) => {
756                    answer = Some(solid);
757                    break;
758                }
759                Ok(None) => {}
760                Err(error) => os_debug!("shrink by subtraction: {} plane(s) declined: {error}", planes.len()),
761            }
762        }
763    }
764    let Some(solid) = answer else {
765        return Ok(None);
766    };
767    // The grown complement covering the whole body is the shrink's answer
768    // "nothing", and an empty solid validates: it is refused by name, never
769    // returned as a body (the elliptic cylinder shrunk by 6 once read as a
770    // solid of no faces).
771    if solid.shells.iter().all(|shell| shell.faces.is_empty()) {
772        return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_solid_shrinks_to_nothing", format!(
773            "offset_solid: the shrink by {amount:.6} leaves nothing: the complement grown by that much covers the whole body"
774        )));
775    }
776    let face_images = solid
777        .shells
778        .iter()
779        .flat_map(|shell| &shell.faces)
780        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
781        .collect();
782    Ok(Some(OffsetShellResultRecord { solid, face_images }))
783}
784
785/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins,
786/// and the growths' union; `None` when the planes leave one piece or the
787/// union does not validate.
788fn grown_union(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
789    let Some(grown) = grown_pieces(solid, planes, amount)? else {
790        return Ok(None);
791    };
792    union_of_grown(&grown)
793}
794
795/// The union of grown pieces; `None` when it does not validate.
796fn union_of_grown(grown: &[BrepSolid]) -> Result<Option<BrepSolid>, KernelRefusal> {
797    let union = crate::boolean_operation_nary(grown, BooleanOperation::Union)?;
798    Ok(union.validate().is_empty().then_some(union))
799}
800
801/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins;
802/// `None` when the planes leave one piece.
803fn grown_pieces(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
804    let pieces = cut_by_planes(solid, planes);
805    if pieces.len() < 2 {
806        return Ok(None);
807    }
808    os_debug!("by pieces: {} plane(s) cut the body into {} piece(s)", planes.len(), pieces.len());
809    let mut grown = Vec::with_capacity(pieces.len());
810    for (index, piece) in pieces.iter().enumerate() {
811        let sharp = offset_body(piece, &[], -amount, Body::Whole, "offset_solid_piece")
812            .map_err(|error| error.with_message(|message| format!("piece {index}: {message}")))?;
813        grown.push(round_offset_joins(sharp, amount)?.solid);
814    }
815    Ok(Some(grown))
816}
817
818/// `BREP_OFFSET_SHRINK_BY_SUBTRACTION` (default on; `=0` restores): where the union of a
819/// shrink's grown complement pieces cannot be assembled, the pieces are
820/// subtracted from the body one at a time instead.
821///
822/// Cause (the dumbbell plate shrunk by 1.5, brep-bench
823/// shell/dumbbell-neck-filled): the grown pieces' concave rounds about the
824/// neck mouths cross at y = 5, and their n-ary union failed ("boolean assembly
825/// produced invalid topology (S=3 genus=2)", one-use edges ~3e-5 long near
826/// (8.882, 5, 1.5)) for every plane set. `S − (A ∪ B) = (S − A) − B`.
827fn shrink_by_subtraction_enabled() -> bool {
828    switch!("BREP_OFFSET_SHRINK_BY_SUBTRACTION", true)
829}
830
831
832/// `source` less each of the grown pieces `grown` in turn (`None` when there
833/// are none, as [`grown_pieces`] gives none for a set leaving one piece, or
834/// when the result does not validate).
835fn subtracted_one_by_one(source: &BrepSolid, grown: Option<Vec<BrepSolid>>) -> Result<Option<BrepSolid>, KernelRefusal> {
836    let Some(grown) = grown else {
837        return Ok(None);
838    };
839    let options = BooleanOptions::default();
840    let mut body = source.clone();
841    for (index, piece) in grown.iter().enumerate() {
842        body = boolean_operation(&body, piece, BooleanOperation::Subtract, &options)
843            .map_err(|error| error.with_message(|message| format!("subtracting grown piece {index}: {message}")))?;
844    }
845    Ok(body.validate().is_empty().then_some(body))
846}
847
848/// `BREP_OFFSET_REFLEX_BY_PIECES` (default on; `=0` restores): [`grown_across_reflex_edges`].
849fn reflex_by_pieces_enabled() -> bool {
850    switch!("BREP_OFFSET_REFLEX_BY_PIECES", true)
851}
852
853
854/// The ROUNDED growth of a body with CONCAVE (reflex) edges between planar
855/// faces, as the union of its pieces' growths, the pieces cut at those
856/// faces' planes; `None` (and the ordinary sharp body + rounds) where the body
857/// has none, or a piece or the union fails.
858///
859/// Cause (an L-shaped plate grown by 1, brep-bench offset/l-block-grown, read
860/// volume +0.041 and area −0.061 against the closed form): the sharp body is
861/// right, but where its reflex edge meets the top and bottom, the rounds of
862/// the two convex edges beside it must meet in a sharp concave crease, and
863/// `fillet_edges` blends that corner instead. Cut at x = 5 the plate is two
864/// boxes; each grows to a rounded box exactly, and their union carries the
865/// crease as the two rounds' own intersection.
866fn grown_across_reflex_edges(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
867    if !reflex_by_pieces_enabled() {
868        return None;
869    }
870    let attempt = || -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
871        let band = 1e-9 * crate::solid_scale(source).max(1.0);
872        let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
873        let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
874        for face in &faces {
875            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
876                uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
877            }
878        }
879        let mut planes: Vec<(Vec3, Vec3)> = Vec::new();
880        for edge in &source.edges {
881            if edge.degenerate {
882                continue;
883            }
884            let Some(pair) = uses.get(&edge.id) else { continue };
885            if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
886                continue;
887            }
888            if edge_is_convex_join(edge, pair[0], pair[1].0, 1.0 - 1e-6)? != Some(false) {
889                continue;
890            }
891            for (face, _) in pair {
892                let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
893                    continue;
894                };
895                let seen = planes
896                    .iter()
897                    .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
898                if !seen {
899                    planes.push((point, normal));
900                }
901            }
902        }
903        if planes.is_empty() || planes.len() > 8 {
904            return Ok(None);
905        }
906        // One plane per reflex edge is enough, and fewer pieces meet in fewer
907        // places: try each plane alone first, then all of them.
908        let mut sets = planes.iter().map(|plane| vec![*plane]).collect::<Vec<_>>();
909        if planes.len() > 1 {
910            sets.push(planes.clone());
911        }
912        for set in &sets {
913            match grown_union(source, set, distance) {
914                Ok(Some(solid)) => {
915                    os_debug!("reflex by pieces: {} plane(s)", set.len());
916                    let face_images = solid
917                        .shells
918                        .iter()
919                        .flat_map(|shell| &shell.faces)
920                        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
921                        .collect();
922                    return Ok(Some(OffsetShellResultRecord { solid, face_images }));
923                }
924                Ok(None) => {}
925                Err(error) => os_debug!("reflex by pieces: {} plane(s) declined: {error}", set.len()),
926            }
927        }
928        Ok(None)
929    };
930    match attempt() {
931        Ok(result) => result,
932        Err(error) => {
933            os_debug!("reflex by pieces declined: {error}");
934            None
935        }
936    }
937}