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/// The rounded growth of a piece another lane assembles ([`super::corner_tubes`]):
65/// [`offset_solid`]'s own route, unread.
66pub(super) fn offset_solid_unread_for_pieces(source: &BrepSolid, distance: f64) -> Result<BrepSolid, KernelRefusal> {
67    Ok(offset_solid_unread(source, distance, OffsetCorners::Rounded)?.solid)
68}
69
70/// [`offset_solid`] before its result is read back ([`super::rim_witness`]).
71fn offset_solid_unread(
72    source: &BrepSolid,
73    distance: f64,
74    corners: OffsetCorners,
75) -> Result<OffsetShellResultRecord, KernelRefusal> {
76    let grown = offset_solid_joined(source, distance, corners)?;
77    if corners == OffsetCorners::Rounded && distance > 0.0 {
78        if let Some(carved) = super::bore_dimples::carve_bore_dimples(source, &grown.solid, distance) {
79            let operands = grown
80                .solid
81                .shells
82                .iter()
83                .flat_map(|shell| &shell.faces)
84                .zip(&grown.face_images)
85                .map(|(face, image)| (face, image.clone()))
86                .collect::<Vec<_>>();
87            let cap = OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 };
88            if let Ok(face_images) = provenance_by_surface(&carved, &operands, Some(&cap)) {
89                return Ok(OffsetShellResultRecord { solid: carved, face_images });
90            }
91        }
92    }
93    Ok(grown)
94}
95
96/// [`offset_solid`] before the bore dimples ([`super::bore_dimples`]): the
97/// sharp body, or its rounding, or a decomposition's.
98fn offset_solid_joined(
99    source: &BrepSolid,
100    distance: f64,
101    corners: OffsetCorners,
102) -> Result<OffsetShellResultRecord, KernelRefusal> {
103    // A torus grown exactly to its hole is the horn torus (`BREP_OFFSET_HORN_TORUS`).
104    if corners == OffsetCorners::Rounded {
105        if let Some(grown) = super::convex_erosion::horn_torus_growth(source, distance) {
106            return Ok(grown);
107        }
108    }
109    // A right prism over a smooth convex profile grows by its parts, the
110    // rims' tubes fitted about the profile (`BREP_OFFSET_PRISM_GROWTH`).
111    if corners == OffsetCorners::Rounded && distance > 0.0 {
112        if let Some(grown) = super::prism_growth::prism_growth(source, distance) {
113            return Ok(grown);
114        }
115    }
116    // A solid of revolution grows by its half-section's growth revolved,
117    // exact, ahead of the pipeline and the blend that rounds its rims
118    // (`BREP_OFFSET_REVOLVED_FIRST`).
119    if corners == OffsetCorners::Rounded && distance > 0.0 && revolved_first_on() {
120        if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
121            return Ok(grown);
122        }
123    }
124    // A convex body of planes, cylinders and spheres whose sharp edges are
125    // closed loops grows exactly by its moved faces and the pipe about each
126    // source edge (`pipe_parallel`), ahead of the pipeline whose blend marches
127    // those same rounds (`BREP_OFFSET_PIPE_FIRST`).
128    let pipe_mode = pipe_first_mode();
129    let pipe_first = (corners == OffsetCorners::Rounded && distance > 0.0 && pipe_mode != crate::env_read::Mode::Off)
130        .then(|| super::pipe_parallel::pipe_parallel(source, distance))
131        .flatten();
132    if pipe_mode == crate::env_read::Mode::On {
133        if let Some(grown) = pipe_first {
134            return Ok(grown);
135        }
136    }
137    let checked = |result: Result<OffsetShellResultRecord, KernelRefusal>| {
138        if let (Some(pipe), Ok(built)) = (&pipe_first, &result) {
139            let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).map(|m| m.volume).ok();
140            let (a, b) = (volume(&pipe.solid), volume(&built.solid));
141            let agrees = matches!((a, b), (Some(a), Some(b)) if (a - b).abs() <= 1e-6 * a.abs().max(b.abs()));
142            if !agrees {
143                eprintln!("offset.pipe_first DISAGREES: pipe volume {a:?}, pipeline volume {b:?}");
144            }
145        }
146        result
147    };
148    if pipe_first.is_some() {
149        return checked(offset_solid_joined_rest(source, distance, corners));
150    }
151    offset_solid_joined_rest(source, distance, corners)
152}
153
154/// [`offset_solid_joined`] after the pipe-first lane.
155fn offset_solid_joined_rest(
156    source: &BrepSolid,
157    distance: f64,
158    corners: OffsetCorners,
159) -> Result<OffsetShellResultRecord, KernelRefusal> {
160    // A concave rounded corner the growth passes: the sharp-cornered body's
161    // growth with the tubes about the corners' arcs (`BREP_OFFSET_CORNER_TUBES`).
162    if corners == OffsetCorners::Rounded && distance > 0.0 {
163        if let Some(grown) = super::corner_tubes::corner_tubes_growth(source, distance) {
164            return Ok(grown);
165        }
166    }
167    if corners == OffsetCorners::Rounded && distance > 0.0 {
168        if let Some(grown) = grown_across_reflex_edges(source, distance) {
169            return Ok(grown);
170        }
171    }
172    // A right prism over a polygon whose shrink drops an edge or splits the
173    // body: the planar erosion extruded, exact and without a boolean
174    // (`BREP_OFFSET_PRISM_EROSION`); a solid of revolution over a polygon
175    // section likewise, its section eroded and revolved
176    // (`BREP_OFFSET_REVOLVED_EROSION`).
177    if corners == OffsetCorners::Rounded && distance < 0.0 {
178        if let Some(eroded) = super::prism_erosion::prism_erosion(source, distance, true) {
179            return Ok(eroded);
180        }
181        if let Some(eroded) = super::revolved_erosion::revolved_erosion(source, distance, true) {
182            return Ok(eroded);
183        }
184    }
185    let widened_before = super::outward_side_widen::widened_count();
186    let sharp = match offset_body(source, &[], -distance, Body::Whole, "offset_solid") {
187        // A rounded growth whose sharp body was assembled only because a
188        // curved face's side was widened (`outward_side_widen`) used to be
189        // refused there and built by the revolved-parallel lane, which is
190        // exact; a solid of revolution keeps that lane, and any other body
191        // (the lane declines it) rounds the sharp body.
192        Ok(_) if corners == OffsetCorners::Rounded
193            && distance > 0.0
194            && super::outward_side_widen::widened_count() != widened_before
195            && super::revolved_parallel::revolved_parallel(source, distance).is_some() =>
196        {
197            return Ok(super::revolved_parallel::revolved_parallel(source, distance).unwrap());
198        }
199        Ok(sharp) => sharp,
200        Err(error) => {
201            if corners == OffsetCorners::Rounded {
202                if let Some(eroded) = super::prism_erosion::prism_erosion(source, distance, false) {
203                    return Ok(eroded);
204                }
205                if distance < 0.0 {
206                    if let Some(eroded) = super::revolved_erosion::revolved_erosion(source, distance, false) {
207                        return Ok(eroded);
208                    }
209                    // Curved sides the polygon eroder does not read
210                    // (`BREP_OFFSET_REVOLVED_CURVED_EROSION`).
211                    if let Some(eroded) = super::revolved_curved_erosion::revolved_curved_erosion(source, distance) {
212                        return Ok(eroded);
213                    }
214                    // A convex body of planes and spheres: its faces' regions
215                    // shrunk and met (`BREP_OFFSET_CONVEX_EROSION`).
216                    if let Some(eroded) = super::convex_erosion::convex_erosion(source, distance) {
217                        return Ok(eroded);
218                    }
219                }
220                if let Some(grown) = grown_by_pieces(source, distance)? {
221                    return Ok(grown);
222                }
223                if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
224                    return Ok(grown);
225                }
226                if let Some(grown) = super::pipe_parallel::pipe_parallel(source, distance) {
227                    return Ok(grown);
228                }
229            }
230            // A right prism shrunk past its profile's curvature: the trimmed
231            // inward offset extruded between the moved caps (sharp and rounded
232            // joins agree on a convex prism's shrink).
233            if distance < 0.0 {
234                if let Some(shrunk) = super::prism_parallel::prism_parallel(source, distance)? {
235                    return Ok(shrunk);
236                }
237            }
238            return Err(error);
239        }
240    };
241    match corners {
242        OffsetCorners::Sharp => Ok(sharp),
243        OffsetCorners::Rounded => match round_offset_joins(sharp, distance, Some(source)) {
244            Ok(rounded) => Ok(rounded),
245            // A shrink whose rounds the blend cannot build: the exact erosion
246            // lanes the pipeline's refusal is offered (`BREP_OFFSET_SHRINK_AFTER_ROUND`).
247            Err(error) if distance < 0.0 && shrink_after_round_on() => super::prism_erosion::prism_erosion(source, distance, false)
248                .or_else(|| super::revolved_erosion::revolved_erosion(source, distance, false))
249                .or_else(|| super::revolved_curved_erosion::revolved_curved_erosion(source, distance))
250                .or_else(|| super::convex_erosion::convex_erosion(source, distance))
251                .ok_or(error),
252            // A mitred body cannot carry the ball over a vertex of degree four
253            // or more; a convex polyhedron's parallel body is built directly.
254            Err(error) => match crate::blend::convex_parallel::convex_polyhedron_parallel(source, distance) {
255                Ok(Some((solid, images))) if solid.validate().is_empty() => {
256                    let face_images = images
257                        .into_iter()
258                        .map(|image| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: image.unwrap_or(0) })
259                        .collect();
260                    Ok(OffsetShellResultRecord { solid, face_images })
261                }
262                _ => super::revolved_parallel::revolved_parallel(source, distance)
263                    .or_else(|| super::pipe_parallel::pipe_parallel(source, distance))
264                    .ok_or(error),
265            },
266        },
267    }
268}
269
270/// `BREP_OFFSET_SHRINK_AFTER_ROUND` (default on; `=0` restores): a rounded
271/// SHRINK whose sharp body assembled but whose concave rounds the blend could
272/// not build is offered the exact erosion lanes a pipeline refusal is.
273///
274/// Cause (brep-bench offset/plus-shaped-plate-shrunk, a plus 4 thick shrunk by
275/// 1): the sharp body is right, but each arm is left exactly 2d wide and the
276/// rounds of its inside corners refuse ("faces are tangent along the edge";
277/// "dihedral angle too degenerate"), while the prism's erosion is its
278/// outline's erosion extruded between the caps moved in.
279fn shrink_after_round_on() -> bool {
280    switch!("BREP_OFFSET_SHRINK_AFTER_ROUND", true)
281}
282
283
284/// `BREP_OFFSET_PIPE_FIRST` (default on; `=0` restores; `check` builds both and
285/// compares their volumes): the pipe-parallel lane answers a rounded growth
286/// before the pipeline, not only after its refusal.
287fn pipe_first_mode() -> crate::env_read::Mode {
288    crate::mode_switch!("BREP_OFFSET_PIPE_FIRST", true)
289}
290
291/// `BREP_OFFSET_REVOLVED_FIRST` (default on; `=0` restores): the revolved-parallel lane
292/// answers a rounded growth before the pipeline, not only after its refusal.
293fn revolved_first_on() -> bool {
294    switch!("BREP_OFFSET_REVOLVED_FIRST", true)
295}
296
297
298/// `BREP_OFFSET_GROW_BY_PIECES` (default on; `=0` restores): [`grown_by_pieces`].
299fn grow_by_pieces_enabled() -> bool {
300    switch!("BREP_OFFSET_GROW_BY_PIECES", true)
301}
302
303
304/// The ROUNDED growth of a body whose own offset body the pipeline could not
305/// assemble, as the union of its pieces' growths: the parallel body of a
306/// union is the union of the parallel bodies, `(A ∪ B) ⊕ D = (A ⊕ D) ∪
307/// (B ⊕ D)`, for any pieces whose union is the body.
308///
309/// Cause (a drum with a groove 1.6 wide grown by 1, brep-bench
310/// offset/grooved-drum-grown): the groove's walls offset across each other,
311/// "a skin partly shadowed that way is not yet assembled", and even assembled
312/// the sharp body would have no groove left to round, while the case's notch
313/// is the two tori about the groove's outer rims. Cut at the planes of its
314/// planar faces the drum is three cylinders; each grows by the pipeline's own
315/// rounded offset, and their union carries the notch where the two rim tori
316/// cross.
317///
318/// The cuts are chosen by [`thin_pair_planes`] (the planes parallel to a pair
319/// of planar faces whose offsets cross), each kept only where it divides a
320/// piece (`split_solid_by_plane`). A SHRINK runs the same construction on the
321/// body's complement in a frame box ([`shrunk_by_pieces`]). Every piece must
322/// grow and the union must validate; anything else declines and the
323/// pipeline's own refusal stands. The faces are all `Offset` images with
324/// `source_face_id` 0, as the rounded caps are: a face of the union may carry
325/// the growth of several source faces' pieces.
326///
327/// A decline is `Ok(None)`; the one refusal that comes through is a shrink
328/// whose grown complement covers the whole body, which is the answer itself.
329fn grown_by_pieces(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
330    if !grow_by_pieces_enabled() {
331        return Ok(None);
332    }
333    match grown_by_pieces_impl(source, distance) {
334        Ok(result) => Ok(result),
335        Err(error) if matches!(&error.class, crate::RefusalClass::IllPosed { what } if what == "offset_solid_shrinks_to_nothing") => Err(error),
336        Err(error) => {
337            os_debug!("grow by pieces declined: {error}");
338            Ok(None)
339        }
340    }
341}
342
343fn grown_by_pieces_impl(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
344    if distance < 0.0 {
345        return shrunk_by_pieces(source, -distance);
346    }
347    let Some(sets) = thin_pair_planes(source, distance, true)? else {
348        return Ok(None);
349    };
350    let mut answer = None;
351    for planes in &sets {
352        match grown_union(source, planes, distance) {
353            Ok(Some(solid)) => {
354                answer = Some(solid);
355                break;
356            }
357            Ok(None) => {}
358            Err(error) => os_debug!("grow by pieces: {} plane(s) declined: {error}", planes.len()),
359        }
360    }
361    let Some(solid) = answer else {
362        return Ok(None);
363    };
364    let face_images = solid
365        .shells
366        .iter()
367        .flat_map(|shell| &shell.faces)
368        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
369        .collect();
370    Ok(Some(OffsetShellResultRecord { solid, face_images }))
371}
372
373/// Roll the sharp body's joins that the ball of radius `|distance|` rounds:
374/// the convex edges of an outward offset, the concave edges of an inward one.
375/// A body with no such edge is already the parallel body and is returned as
376/// it is. Provenance: a face still on a sharp-body surface keeps that face's
377/// image; a cap (a cylinder, torus or corner ball the blend built, which lies
378/// on no offset face) is an `Offset` image with `source_face_id` 0, because it
379/// rounds a JOIN between source faces and has no single source face.
380///
381/// Every join is rounded at `|distance|` exactly, or the body is refused: the
382/// fillet's radius relief (a locally reduced radius where the ball folds) is
383/// held off, since a relieved join is not the parallel body. The rims of
384/// bores wider than the growth (`source` given) are left sharp and their
385/// cusps carved instead ([`super::bore_dimples::carve_wide_rims`]): the
386/// rim's ball there runs round a circle smaller than itself, which the
387/// blend's march reads as a fold.
388fn round_offset_joins(
389    sharp: OffsetShellResultRecord,
390    distance: f64,
391    source: Option<&BrepSolid>,
392) -> Result<OffsetShellResultRecord, KernelRefusal> {
393    let wanted_convex = distance > 0.0;
394    let rims = match source {
395        Some(source) if wanted_convex => super::bore_dimples::wide_bore_rims(source, distance),
396        _ => Vec::new(),
397    };
398    let tolerance = 1e-7 * crate::solid_scale(&sharp.solid).max(1.0);
399    let midpoints: Vec<Vec3> = sharp_join_midpoints(&sharp.solid, wanted_convex)?
400        .into_iter()
401        .filter(|point| !rims.iter().any(|rim| rim.holds(*point, distance, tolerance)))
402        .collect();
403    if midpoints.is_empty() && rims.is_empty() {
404        return Ok(sharp);
405    }
406    let rounded = if midpoints.is_empty() {
407        Ok(sharp.solid.clone())
408    } else {
409        let _no_relief = crate::blend::relief::Relieving::enter();
410        fillet_edges(&sharp.solid, &midpoints, None, distance.abs(), false, None)
411    };
412    let solid = rounded
413        .and_then(|rounded| {
414            if rims.is_empty() {
415                return Ok(rounded);
416            }
417            super::bore_dimples::carve_wide_rims(&rounded, &rims, distance).map_err(|reason| {
418                KernelRefusal::unsupported(KernelStage::Refine, "offset_wide_bore_rim", format!("offset_solid: a bore rim's cusp could not be carved: {reason}"))
419            })
420        })
421        .map_err(|error| {
422            error.with_message(|message| {
423                format!(
424                    "offset_solid: the rounded joins of the offset body could not be built \
425                     ({} edge(s) at radius {:.6}): {message}",
426                    midpoints.len(),
427                    distance.abs()
428                )
429            })
430        })?;
431    let operands = sharp
432        .solid
433        .shells
434        .iter()
435        .flat_map(|shell| &shell.faces)
436        .zip(&sharp.face_images)
437        .map(|(face, image)| (face, image.clone()))
438        .collect::<Vec<_>>();
439    let cap = OffsetShellFaceImageRecord {
440        role: OffsetFaceRole::Offset,
441        source_face_id: 0,
442    };
443    let face_images = provenance_by_surface(&solid, &operands, Some(&cap))?;
444    Ok(OffsetShellResultRecord { solid, face_images })
445}
446
447/// Per-face provenance of a body whose faces lie on its operands' surfaces (a
448/// boolean result, a blend's untouched faces): each result face takes the
449/// image of the FIRST operand face whose surface carries an interior point of
450/// it and whose trim contains that point's foot. Operands are matched in the
451/// order given, so a coincident pair (a held face and the opening it copies)
452/// resolves to whichever is listed first. A face on no operand surface takes
453/// `unmatched`, or refuses by name when there is none.
454pub(super) fn provenance_by_surface(
455    result: &BrepSolid,
456    operands: &[(&FaceRecord, OffsetShellFaceImageRecord)],
457    unmatched: Option<&OffsetShellFaceImageRecord>,
458) -> Result<Vec<OffsetShellFaceImageRecord>, KernelRefusal> {
459    let band = 1e-6 * crate::solid_scale(result).max(1.0);
460    let mut images = Vec::new();
461    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
462        let seeds = super::source_seeds(result, face.id)?;
463        let seed = seeds[0];
464        let point = face.surface.evaluate(seed.x, seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
465        let mut found = None;
466        for (operand, image) in operands {
467            let Ok(foot) = project_point_to_surface(&operand.surface, point) else { continue };
468            if foot.distance > band {
469                continue;
470            }
471            let inside = super::parameter_point_in_face(operand, Vec2 { x: foot.u, y: foot.v }, 1e-8)
472                .is_ok_and(|class| class != PolygonClass::Outside);
473            if inside {
474                found = Some(image.clone());
475                break;
476            }
477        }
478        match found.or_else(|| unmatched.cloned()) {
479            Some(image) => images.push(image),
480            None => {
481                return Err(KernelRefusal::internal(
482                    KernelStage::Sew,
483                    "offset_shell_provenance_lost",
484                    format!(
485                        "offset_shell: result face {} at ({:.4}, {:.4}, {:.4}) lies on no operand face",
486                        face.id, point.x, point.y, point.z
487                    ),
488                ))
489            }
490        }
491    }
492    Ok(images)
493}
494
495/// Midpoints of the SHARP edges of `solid` whose convexity is `convex`: an
496/// edge bordering two different faces whose outward normals differ there, read
497/// at the edge midpoint. Tangent junctions (a blend face meeting its support)
498/// and face-local seams are not joins and are skipped.
499fn sharp_join_midpoints(solid: &BrepSolid, convex: bool) -> Result<Vec<Vec3>, KernelRefusal> {
500    // Cosine of the dihedral angle above which two faces read as tangent.
501    const TANGENT_COSINE: f64 = 1.0 - 1e-6;
502    let faces = solid
503        .shells
504        .iter()
505        .flat_map(|shell| &shell.faces)
506        .collect::<Vec<_>>();
507    let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
508    for face in &faces {
509        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
510            uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
511        }
512    }
513    let mut midpoints = Vec::new();
514    for edge in &solid.edges {
515        if edge.degenerate {
516            continue;
517        }
518        let Some(pair) = uses.get(&edge.id) else { continue };
519        if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
520            continue;
521        }
522        if edge_is_convex_join(edge, pair[0], pair[1].0, TANGENT_COSINE)? == Some(convex) {
523            midpoints.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Classify, "evaluate")?);
524        }
525    }
526    Ok(midpoints)
527}
528
529/// `Some(true)` for a convex join, `Some(false)` for a concave one, `None` for
530/// a tangent junction. With `t` the direction the first face's coedge runs
531/// along the edge and `n_a` that face's outward normal, `n_a × t` points into
532/// the first face; the join is convex when the second face's outward normal
533/// points away from there.
534pub(super) fn edge_is_convex_join(
535    edge: &EdgeRecord,
536    (first, first_forward): (&FaceRecord, bool),
537    second: &FaceRecord,
538    tangent_cosine: f64,
539) -> Result<Option<bool>, KernelRefusal> {
540    let t = 0.5 * (edge.t0 + edge.t1);
541    let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
542    let point = derivatives[0];
543    let mut tangent = derivatives[1].normalized().or_refuse(KernelStage::Classify, "normalized")?;
544    if !first_forward {
545        tangent = tangent.scale(-1.0);
546    }
547    let normal_a = outward_normal_at(first, point)?;
548    let normal_b = outward_normal_at(second, point)?;
549    if normal_a.dot(normal_b) >= tangent_cosine {
550        return Ok(None);
551    }
552    Ok(Some(normal_b.dot(normal_a.cross(tangent)) < 0.0))
553}
554
555fn outward_normal_at(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
556    let foot = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
557    super::face_normal(face, foot.u, foot.v)
558}
559
560// ---------------------------------------------------------------------------
561// Shell as a boolean
562// ---------------------------------------------------------------------------
563
564/// The textbook shell: the offset body with the opening faces HELD (copied at
565/// distance zero, so they cancel in the difference), then `source − body` for
566/// an inward shell and `body − source` for an outward one. The walls at the
567/// openings come out of the boolean. `distance` carries `offset_shell`'s sign
568/// (positive inward).
569///
570/// This is the lane `offset_shell` falls back to when its direct construction
571/// refuses by one of its own names (`direct_refusal_takes_the_boolean_lane`);
572/// it is public so the two can be compared on any fixture. The result's
573/// `face_images` are read back from the operands by surface
574/// (`provenance_by_surface`): `Offset` for a face of the body's skins,
575/// `Wall` for a held opening face, `Source` for a face of the source.
576pub fn offset_shell_by_boolean(
577    source: &BrepSolid,
578    opening_face_ids: &[u64],
579    distance: f64,
580) -> Result<OffsetShellResultRecord, KernelRefusal> {
581    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
582        let mut record = offset_shell_by_boolean(&scaled.source, opening_face_ids, scaled.distance)
583            .map_err(|error| scaled.refusal(error))?;
584        record.solid = scaled.back(&record.solid, "offset_shell")?;
585        return Ok(record);
586    }
587    if opening_face_ids.is_empty() {
588        return Err(KernelRefusal::input(
589            KernelStage::Collect,
590            "offset_shell_no_opening",
591            "offset_shell: at least one opening face is required",
592        ));
593    }
594    let body = offset_body(source, opening_face_ids, distance, Body::Whole, "offset_shell_by_boolean")
595        .or_else(|error| {
596            if !direct_refusal_takes_the_boolean_lane(&error) {
597                return Err(error);
598            }
599            let result = super::joint_offset::build(source, opening_face_ids, distance);
600            if let Err(reason) = &result {
601                os_debug!("joint offset refused: {reason}");
602            }
603            result.map_err(|_| error)
604        })?;
605    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
606    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
607        .map_err(|error| {
608            error.with_message(|message| {
609                format!("offset_shell: the boolean lane's difference could not be built: {message}")
610            })
611        })?;
612    // The body's faces first, so the ring on a held face's plane reads as
613    // that face's `Wall` rather than as the coincident source opening.
614    let mut operands = body
615        .solid
616        .shells
617        .iter()
618        .flat_map(|shell| &shell.faces)
619        .zip(&body.face_images)
620        .map(|(face, image)| (face, image.clone()))
621        .collect::<Vec<_>>();
622    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
623        (
624            face,
625            OffsetShellFaceImageRecord {
626                role: OffsetFaceRole::Source,
627                source_face_id: face.id,
628            },
629        )
630    }));
631    let face_images = provenance_by_surface(&solid, &operands, None)?;
632    Ok(OffsetShellResultRecord { solid, face_images })
633}
634
635/// Lane O row 34: the CLOSED hollow, a shell with no openings. The offset
636/// body, the whole source grown or shrunk with sharp joins, against the
637/// source: `source − body` inward and `body − source` outward, so the result
638/// is the outer shell and the inner void's shell, with the walls of the band
639/// between them. `distance` carries `offset_shell`'s sign (positive inward).
640/// `face_images` are read back from the operands by surface as in
641/// [`offset_shell_by_boolean`]: `Offset` for the body's faces, `Source` for
642/// the source's.
643///
644/// The construction checks itself: the result is exactly two shells and its
645/// volume is the difference of the operands' volumes.
646pub fn offset_shell_closed(source: &BrepSolid, distance: f64) -> Result<OffsetShellResultRecord, KernelRefusal> {
647    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell_closed")? {
648        let mut record = offset_shell_closed(&scaled.source, scaled.distance).map_err(|error| scaled.refusal(error))?;
649        record.solid = scaled.back(&record.solid, "offset_shell_closed")?;
650        return Ok(record);
651    }
652    let body = offset_body(source, &[], distance, Body::Whole, "offset_shell_closed")?;
653    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
654    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
655        .map_err(|error| {
656            error.with_message(|message| format!("offset_shell: the closed hollow's difference could not be built: {message}"))
657        })?;
658    let volume = |solid: &BrepSolid| {
659        crate::solid_mass_properties(solid)
660            .map(|properties| properties.volume)
661            .or_refuse(KernelStage::Validate, "solid_mass_properties")
662    };
663    let expected = volume(kept)? - volume(removed)?;
664    let measured = volume(&solid)?;
665    if solid.shells.len() != 2 || !(expected > 0.0) || !((measured - expected).abs() <= 1e-9 * expected) {
666        return Err(KernelRefusal::internal(
667            KernelStage::Validate,
668            "offset_shell_closed_hollow",
669            format!(
670                "offset_shell: the closed hollow is not the band between its operands ({} shells, volume {measured} against {expected})",
671                solid.shells.len()
672            ),
673        ));
674    }
675    let mut operands = body
676        .solid
677        .shells
678        .iter()
679        .flat_map(|shell| &shell.faces)
680        .zip(&body.face_images)
681        .map(|(face, image)| (face, image.clone()))
682        .collect::<Vec<_>>();
683    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
684        (face, OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
685    }));
686    let face_images = provenance_by_surface(&solid, &operands, None)?;
687    Ok(OffsetShellResultRecord { solid, face_images })
688}
689
690/// Whether a refusal of the direct pipeline is one of its OWN named
691/// inabilities, the ones the boolean recipe can answer differently: an
692/// `offset_shell_*` unsupported-geometry or internal refusal, or the
693/// assembler's typed non-integral-genus and degenerate-arrangement refusals
694/// that `cause_in_front` carries a shell cause through. Input refusals
695/// (distance, foreign opening, no retained face) and soundness refusals are
696/// not: the first name a caller's mistake, the second a body that must not be
697/// shipped by any route.
698pub fn direct_refusal_takes_the_boolean_lane(refusal: &KernelRefusal) -> bool {
699    match &refusal.class {
700        RefusalClass::UnsupportedGeometry { what } | RefusalClass::Internal { what } => {
701            what.starts_with("offset_shell_")
702        }
703        RefusalClass::NonIntegralGenus { .. } => {
704            refusal.message.starts_with("offset_shell")
705                || (bare_genus_takes_the_boolean_lane() && refusal.message.starts_with("boolean assembly:"))
706        }
707        RefusalClass::DegenerateArrangement { .. } => refusal.message.starts_with("offset_shell"),
708        _ => false,
709    }
710}
711
712/// `BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE` (default on; `=0` restores): the
713/// direct pipeline's assembly refusing a non-integral genus takes the boolean
714/// lane even with no shell cause put in front of it. Which sentence a refusal
715/// carries says nothing about whether the lane can answer:
716/// `inbox_20261017_negative_shell` only reached the lane through the note of
717/// an omission, and the omission was a misread fillet's true skin; reading
718/// that skin correctly (`BREP_OFFSET_TANGENT_EDGE_EUCLID`) left the same
719/// failed assembly with no note, and the shell was refused.
720fn bare_genus_takes_the_boolean_lane() -> bool {
721    crate::switch!("BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE", true)
722}
723
724/// The cut planes: every planar face's plane parallel to a THIN PAIR, two
725/// planar faces with opposite outward normals closer than `2·amount` that face
726/// each other across void (`grow`) or across material (shrink) — the pair
727/// whose offsets cross. Deduplicated. Two sets are offered in turn: every
728/// planar face's plane parallel to a thin pair, then the thin pairs' own
729/// planes alone (when fewer), because the boolean that unions the grown
730/// pieces can fail on where one set's pieces meet and not the other's (the
731/// dumbbell's complement cut at all four y planes left sliver edges where the
732/// neck-mouth rounds of adjacent pieces cross). `None` when there is no thin
733/// pair or every set has more than eight planes.
734fn thin_pair_planes(solid: &BrepSolid, amount: f64, grow: bool) -> Result<Option<Vec<Vec<(Vec3, Vec3)>>>, KernelRefusal> {
735    let band = 1e-9 * crate::solid_scale(solid).max(1.0);
736    // Each planar face's plane, its OUTWARD normal.
737    let mut faces: Vec<(Vec3, Vec3)> = Vec::new();
738    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
739        let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
740            continue;
741        };
742        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
743        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
744        let Ok(outward) = super::face_normal(face, 0.5 * (u0 + u1), 0.5 * (v0 + v1)) else {
745            continue;
746        };
747        faces.push((point, if outward.dot(normal) < 0.0 { normal.scale(-1.0) } else { normal }));
748    }
749    let mut directions: Vec<Vec3> = Vec::new();
750    let mut pairs: Vec<(usize, usize)> = Vec::new();
751    for (index, (point, normal)) in faces.iter().enumerate() {
752        for (offset, (other, other_normal)) in faces[index + 1..].iter().enumerate() {
753            if normal.dot(*other_normal) > -1.0 + 1e-12 {
754                continue;
755            }
756            // Signed gap from this face's plane to the other's, along this
757            // face's outward normal: positive across void, negative across
758            // material.
759            let gap = other.sub(*point).dot(*normal);
760            let thin = if grow { gap > band && gap < 2.0 * amount } else { gap < -band && -gap < 2.0 * amount };
761            if thin {
762                pairs.push((index, index + 1 + offset));
763                if !directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
764                    directions.push(*normal);
765                }
766            }
767        }
768    }
769    if directions.is_empty() {
770        return Ok(None);
771    }
772    let push = |planes: &mut Vec<(Vec3, Vec3)>, point: Vec3, normal: Vec3| {
773        let seen = planes
774            .iter()
775            .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
776        if !seen {
777            planes.push((point, normal));
778        }
779    };
780    let mut parallel: Vec<(Vec3, Vec3)> = Vec::new();
781    for (point, normal) in &faces {
782        if directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
783            push(&mut parallel, *point, *normal);
784        }
785    }
786    let mut paired: Vec<(Vec3, Vec3)> = Vec::new();
787    for (first, second) in &pairs {
788        push(&mut paired, faces[*first].0, faces[*first].1);
789        push(&mut paired, faces[*second].0, faces[*second].1);
790    }
791    let mut sets = Vec::new();
792    if parallel.len() <= 8 {
793        sets.push(parallel.clone());
794    }
795    if paired.len() <= 8 && paired.len() < parallel.len() {
796        sets.push(paired);
797    }
798    Ok((!sets.is_empty()).then_some(sets))
799}
800
801/// `solid` cut by every plane that divides a piece of it.
802fn cut_by_planes(solid: &BrepSolid, planes: &[(Vec3, Vec3)]) -> Vec<BrepSolid> {
803    let mut pieces = vec![solid.clone()];
804    for (point, normal) in planes {
805        let mut next = Vec::with_capacity(pieces.len() * 2);
806        for piece in pieces {
807            match crate::split_solid_by_plane(&piece, *point, *normal) {
808                Ok((below, above)) => {
809                    next.push(below);
810                    next.push(above);
811                }
812                Err(_) => next.push(piece),
813            }
814        }
815        pieces = next;
816    }
817    pieces
818}
819
820/// The SHRINK by `amount` through the complement: `S ⊖ D = S − ((F − S) ⊕ D)`
821/// for a frame box `F` reaching past `S` by more than `amount`, where the
822/// complement's growth is the union of its pieces' growths, the pieces cut at
823/// the planes of `S`'s planar faces.
824///
825/// Cause (a drum with a flange 1.6 thick shrunk by 1, brep-bench
826/// offset/flanged-drum-shrunk): the flange's two faces offset across each
827/// other ("a skin partly shadowed that way is not yet assembled"), and the
828/// low ridge the case reads is the two concave tori about the flange's inner
829/// rims, which the complement's pieces carry as the rounds of their own
830/// convex rims.
831fn shrunk_by_pieces(source: &BrepSolid, amount: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
832    let Some(sets) = thin_pair_planes(source, amount, false)? else {
833        return Ok(None);
834    };
835    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
836    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
837    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
838        for control in face.surface.control_points.iter().flatten() {
839            let Ok(point) = control.point() else { return Ok(None) };
840            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
841            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
842        }
843    }
844    let margin = 3.0 * amount;
845    let corner = low.sub(Vec3::new(margin, margin, margin));
846    let size = high.sub(low).add(Vec3::new(2.0 * margin, 2.0 * margin, 2.0 * margin));
847    let frame = crate::make_box_brep(corner, size.x, size.y, size.z).or_refuse(KernelStage::Refine, "make_box_brep")?;
848    let options = BooleanOptions::default();
849    let outside = boolean_operation(&frame, source, BooleanOperation::Subtract, &options)?;
850    let mut answer = None;
851    // Each plane set's grown pieces, kept for the subtraction below: growing
852    // them is most of a set's cost (a cut, a sharp offset and a rounding per
853    // piece), and the subtraction reads exactly the pieces the union did.
854    let mut grown_sets: Vec<Result<Option<Vec<BrepSolid>>, KernelRefusal>> = Vec::with_capacity(sets.len());
855    for planes in &sets {
856        let grown = grown_pieces(&outside, planes, amount);
857        let attempt = match &grown {
858            Ok(Some(grown)) => union_of_grown(grown),
859            Ok(None) => Ok(None),
860            Err(error) => Err(error.clone()),
861        }
862        .and_then(|reach| match reach {
863            Some(reach) => boolean_operation(source, &reach, BooleanOperation::Subtract, &options).map(Some),
864            None => Ok(None),
865        });
866        grown_sets.push(grown);
867        match attempt {
868            Ok(Some(solid)) if solid.validate().is_empty() => {
869                answer = Some(solid);
870                break;
871            }
872            Ok(_) => {}
873            Err(error) => os_debug!("shrink by pieces: {} plane(s) declined: {error}", planes.len()),
874        }
875    }
876    if answer.is_none() && shrink_by_subtraction_enabled() {
877        for (planes, grown) in sets.iter().zip(grown_sets) {
878            match grown.and_then(|grown| subtracted_one_by_one(source, grown)) {
879                Ok(Some(solid)) => {
880                    answer = Some(solid);
881                    break;
882                }
883                Ok(None) => {}
884                Err(error) => os_debug!("shrink by subtraction: {} plane(s) declined: {error}", planes.len()),
885            }
886        }
887    }
888    let Some(solid) = answer else {
889        return Ok(None);
890    };
891    // The grown complement covering the whole body is the shrink's answer
892    // "nothing", and an empty solid validates: it is refused by name, never
893    // returned as a body (the elliptic cylinder shrunk by 6 once read as a
894    // solid of no faces).
895    if solid.shells.iter().all(|shell| shell.faces.is_empty()) {
896        return Err(KernelRefusal::ill_posed(KernelStage::Refine, "offset_solid_shrinks_to_nothing", format!(
897            "offset_solid: the shrink by {amount:.6} leaves nothing: the complement grown by that much covers the whole body"
898        )));
899    }
900    let face_images = solid
901        .shells
902        .iter()
903        .flat_map(|shell| &shell.faces)
904        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
905        .collect();
906    Ok(Some(OffsetShellResultRecord { solid, face_images }))
907}
908
909/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins,
910/// and the growths' union; `None` when the planes leave one piece or the
911/// union does not validate.
912fn grown_union(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
913    let Some(grown) = grown_pieces(solid, planes, amount)? else {
914        return Ok(None);
915    };
916    union_of_grown(&grown)
917}
918
919/// The union of grown pieces; `None` when it does not validate.
920fn union_of_grown(grown: &[BrepSolid]) -> Result<Option<BrepSolid>, KernelRefusal> {
921    let union = crate::boolean_operation_nary(grown, BooleanOperation::Union)?;
922    Ok(union.validate().is_empty().then_some(union))
923}
924
925/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins;
926/// `None` when the planes leave one piece.
927fn grown_pieces(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
928    let pieces = cut_by_planes(solid, planes);
929    if pieces.len() < 2 {
930        return Ok(None);
931    }
932    os_debug!("by pieces: {} plane(s) cut the body into {} piece(s)", planes.len(), pieces.len());
933    let mut grown = Vec::with_capacity(pieces.len());
934    for (index, piece) in pieces.iter().enumerate() {
935        let sharp = offset_body(piece, &[], -amount, Body::Whole, "offset_solid_piece")
936            .map_err(|error| error.with_message(|message| format!("piece {index}: {message}")))?;
937        grown.push(round_offset_joins(sharp, amount, None)?.solid);
938    }
939    Ok(Some(grown))
940}
941
942/// `BREP_OFFSET_SHRINK_BY_SUBTRACTION` (default on; `=0` restores): where the union of a
943/// shrink's grown complement pieces cannot be assembled, the pieces are
944/// subtracted from the body one at a time instead.
945///
946/// Cause (the dumbbell plate shrunk by 1.5, brep-bench
947/// shell/dumbbell-neck-filled): the grown pieces' concave rounds about the
948/// neck mouths cross at y = 5, and their n-ary union failed ("boolean assembly
949/// produced invalid topology (S=3 genus=2)", one-use edges ~3e-5 long near
950/// (8.882, 5, 1.5)) for every plane set. `S − (A ∪ B) = (S − A) − B`.
951fn shrink_by_subtraction_enabled() -> bool {
952    switch!("BREP_OFFSET_SHRINK_BY_SUBTRACTION", true)
953}
954
955
956/// `source` less each of the grown pieces `grown` in turn (`None` when there
957/// are none, as [`grown_pieces`] gives none for a set leaving one piece, or
958/// when the result does not validate).
959fn subtracted_one_by_one(source: &BrepSolid, grown: Option<Vec<BrepSolid>>) -> Result<Option<BrepSolid>, KernelRefusal> {
960    let Some(grown) = grown else {
961        return Ok(None);
962    };
963    let options = BooleanOptions::default();
964    let mut body = source.clone();
965    for (index, piece) in grown.iter().enumerate() {
966        body = boolean_operation(&body, piece, BooleanOperation::Subtract, &options)
967            .map_err(|error| error.with_message(|message| format!("subtracting grown piece {index}: {message}")))?;
968    }
969    Ok(body.validate().is_empty().then_some(body))
970}
971
972/// `BREP_OFFSET_REFLEX_BY_PIECES` (default on; `=0` restores): [`grown_across_reflex_edges`].
973fn reflex_by_pieces_enabled() -> bool {
974    switch!("BREP_OFFSET_REFLEX_BY_PIECES", true)
975}
976
977
978/// The ROUNDED growth of a body with CONCAVE (reflex) edges between planar
979/// faces, as the union of its pieces' growths, the pieces cut at those
980/// faces' planes; `None` (and the ordinary sharp body + rounds) where the body
981/// has none, or a piece or the union fails.
982///
983/// Cause (an L-shaped plate grown by 1, brep-bench offset/l-block-grown, read
984/// volume +0.041 and area −0.061 against the closed form): the sharp body is
985/// right, but where its reflex edge meets the top and bottom, the rounds of
986/// the two convex edges beside it must meet in a sharp concave crease, and
987/// `fillet_edges` blends that corner instead. Cut at x = 5 the plate is two
988/// boxes; each grows to a rounded box exactly, and their union carries the
989/// crease as the two rounds' own intersection.
990fn grown_across_reflex_edges(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
991    if !reflex_by_pieces_enabled() {
992        return None;
993    }
994    match reflex_growth(source, distance, REFLEX_DEPTH) {
995        Ok(Some(solid)) => {
996            let face_images = solid
997                .shells
998                .iter()
999                .flat_map(|shell| &shell.faces)
1000                .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
1001                .collect();
1002            Some(OffsetShellResultRecord { solid, face_images })
1003        }
1004        Ok(None) => None,
1005        Err(error) => {
1006            os_debug!("reflex by pieces declined: {error}");
1007            None
1008        }
1009    }
1010}
1011
1012/// How many times [`reflex_growth`] cuts a piece that still has reflex
1013/// edges again (`BREP_OFFSET_REFLEX_RECURSE`).
1014const REFLEX_DEPTH: usize = 6;
1015
1016/// `BREP_OFFSET_REFLEX_RECURSE` (default on; `=0` restores): a piece of
1017/// [`grown_across_reflex_edges`] that still has a reflex edge between planar
1018/// faces is grown by the lane again, cut at its own reflex planes, instead of
1019/// by `fillet_edges`, which blends the crease where that edge meets two
1020/// rounded rims.
1021///
1022/// Cause (a plate with a square hole grown by 1, brep-bench
1023/// offset/plate-with-a-square-hole-grown, read volume +0.0823 and area
1024/// −0.1215 against the closed form; plus-shaped, U-shaped, star and
1025/// square-pocketed plates likewise): the lane took the first single plane
1026/// that split the body, x = 3, and the U-shaped piece beyond it kept two
1027/// reflex edges, whose four ends the fillet rounded as a rolling ball does
1028/// (it opens the sharp body, and the opening keeps a spindle torus about each
1029/// reflex edge where the parallel body has a crease: (1 − π/4)(5/3 − π/2)d³
1030/// = 0.020574 too much volume at each end).
1031fn reflex_recurse_enabled() -> bool {
1032    switch!("BREP_OFFSET_REFLEX_RECURSE", true)
1033}
1034
1035
1036/// The planes of the planar faces beside each reflex (concave) edge of
1037/// `source`, each plane once.
1038fn reflex_planes(source: &BrepSolid) -> Result<Vec<(Vec3, Vec3)>, KernelRefusal> {
1039    let band = 1e-9 * crate::solid_scale(source).max(1.0);
1040    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
1041    let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
1042    for face in &faces {
1043        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1044            uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
1045        }
1046    }
1047    let mut planes: Vec<(Vec3, Vec3)> = Vec::new();
1048    for edge in &source.edges {
1049        if edge.degenerate {
1050            continue;
1051        }
1052        let Some(pair) = uses.get(&edge.id) else { continue };
1053        if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
1054            continue;
1055        }
1056        if edge_is_convex_join(edge, pair[0], pair[1].0, 1.0 - 1e-6)? != Some(false) {
1057            continue;
1058        }
1059        for (face, _) in pair {
1060            let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
1061                continue;
1062            };
1063            let seen = planes
1064                .iter()
1065                .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
1066            if !seen {
1067                planes.push((point, normal));
1068            }
1069        }
1070    }
1071    Ok(planes)
1072}
1073
1074/// The rounded growth of `source` as the union of its pieces' growths, cut at
1075/// the planes of [`reflex_planes`]; `None` when it has none or no set of them
1076/// builds. With `BREP_OFFSET_REFLEX_RECURSE` a piece that still has reflex
1077/// planes is grown the same way, at most [`REFLEX_DEPTH`] levels deep and
1078/// [`REFLEX_BUDGET`] plane sets in all; where that finds nothing the lane's
1079/// single cuts answer as they do without the switch.
1080fn reflex_growth(source: &BrepSolid, distance: f64, depth: usize) -> Result<Option<BrepSolid>, KernelRefusal> {
1081    let planes = reflex_planes(source)?;
1082    if planes.is_empty() {
1083        return Ok(None);
1084    }
1085    if reflex_recurse_enabled() {
1086        let mut budget = REFLEX_BUDGET;
1087        if let Some(solid) = reflex_growth_whole(source, &planes, distance, depth, &mut budget)? {
1088            return Ok(Some(solid));
1089        }
1090        os_debug!("reflex by pieces: no set leaves every piece free of reflex edges ({} set(s) tried)", REFLEX_BUDGET - budget);
1091    }
1092    if planes.len() > 8 {
1093        return Ok(None);
1094    }
1095    for set in &plane_sets(&planes) {
1096        match grown_union(source, set, distance) {
1097            Ok(Some(solid)) => {
1098                os_debug!("reflex by pieces: {} plane(s)", set.len());
1099                return Ok(Some(solid));
1100            }
1101            Ok(None) => {}
1102            Err(error) => os_debug!("reflex by pieces: {} plane(s) declined: {error}", set.len()),
1103        }
1104    }
1105    Ok(None)
1106}
1107
1108/// How many plane sets one [`reflex_growth`] tries at most, over all its
1109/// levels (`BREP_OFFSET_REFLEX_RECURSE`).
1110const REFLEX_BUDGET: usize = 24;
1111
1112/// Each plane alone, then all of them when there are two to eight: one plane
1113/// per reflex edge is enough, and fewer pieces meet in fewer places.
1114fn plane_sets(planes: &[(Vec3, Vec3)]) -> Vec<Vec<(Vec3, Vec3)>> {
1115    let mut sets = planes.iter().map(|plane| vec![*plane]).collect::<Vec<_>>();
1116    if planes.len() > 1 && planes.len() <= 8 {
1117        sets.push(planes.to_vec());
1118    }
1119    sets
1120}
1121
1122/// [`reflex_growth`] with `BREP_OFFSET_REFLEX_RECURSE`: the first set of
1123/// `planes` whose every piece grows free of reflex planes (a piece with reflex
1124/// planes of its own grown again, `depth` more levels), or `None`; never a
1125/// piece rounded by the fillet across a reflex edge beside a planar face (one
1126/// between curved faces is rounded as before).
1127fn reflex_growth_whole(source: &BrepSolid, planes: &[(Vec3, Vec3)], distance: f64, depth: usize, budget: &mut usize) -> Result<Option<BrepSolid>, KernelRefusal> {
1128    for set in &plane_sets(planes) {
1129        if *budget == 0 {
1130            return Ok(None);
1131        }
1132        *budget -= 1;
1133        match reflex_union(source, set, distance, depth, budget) {
1134            Ok(Some(solid)) => {
1135                os_debug!("reflex by pieces: {} plane(s), depth {depth}", set.len());
1136                return Ok(Some(solid));
1137            }
1138            Ok(None) => {}
1139            Err(error) => os_debug!("reflex by pieces: {} plane(s) declined: {error}", set.len()),
1140        }
1141    }
1142    Ok(None)
1143}
1144
1145/// [`grown_union`] for the recursive reflex lane: `source` cut at `planes`,
1146/// each disjoint lump of each piece grown on its own, a lump with reflex
1147/// planes by [`reflex_growth_whole`]; `None` when one of those finds nothing
1148/// or `depth` is spent.
1149fn reflex_union(source: &BrepSolid, planes: &[(Vec3, Vec3)], distance: f64, depth: usize, budget: &mut usize) -> Result<Option<BrepSolid>, KernelRefusal> {
1150    let pieces = cut_by_planes(source, planes);
1151    if pieces.len() < 2 {
1152        return Ok(None);
1153    }
1154    let lumps = pieces.iter().flat_map(solid_lumps).collect::<Vec<_>>();
1155    os_debug!("reflex by pieces: {} plane(s) cut the body into {} lump(s)", planes.len(), lumps.len());
1156    let inners = lumps.iter().map(reflex_planes).collect::<Result<Vec<_>, _>>()?;
1157    if depth == 0 && inners.iter().any(|inner| !inner.is_empty()) {
1158        return Ok(None);
1159    }
1160    let mut grown = Vec::with_capacity(lumps.len());
1161    for (index, (lump, inner)) in lumps.iter().zip(&inners).enumerate() {
1162        if !inner.is_empty() {
1163            match reflex_growth_whole(lump, inner, distance, depth - 1, budget)? {
1164                Some(solid) => grown.push(solid),
1165                None => return Ok(None),
1166            }
1167            continue;
1168        }
1169        // A lump free of reflex planes with a curved face grows by the whole
1170        // route, so a bore through it keeps its dimples (a recess's ring over
1171        // its floor); a lump of planes is rounded as the lane always did.
1172        let band = 1e-9 * crate::solid_scale(lump).max(1.0);
1173        let mut curved = false;
1174        for face in lump.shells.iter().flat_map(|shell| &shell.faces) {
1175            if super::rim_welds::planar_surface_frame(&face.surface, band)?.is_none() {
1176                curved = true;
1177                break;
1178            }
1179        }
1180        if curved {
1181            let lump_grown = offset_solid_unread(lump, distance, OffsetCorners::Rounded)
1182                .map_err(|error| error.with_message(|message| format!("lump {index}: {message}")))?;
1183            grown.push(lump_grown.solid);
1184            continue;
1185        }
1186        let sharp = offset_body(lump, &[], -distance, Body::Whole, "offset_solid_piece")
1187            .map_err(|error| error.with_message(|message| format!("lump {index}: {message}")))?;
1188        grown.push(round_offset_joins(sharp, distance, None)?.solid);
1189    }
1190    union_of_grown(&grown)
1191}
1192
1193/// `solid` as one solid per shell when every shell bounds material of its
1194/// own (positive volume alone: no void shell), else `solid` whole.
1195fn solid_lumps(solid: &BrepSolid) -> Vec<BrepSolid> {
1196    if solid.shells.len() < 2 {
1197        return vec![solid.clone()];
1198    }
1199    let mut lumps = Vec::with_capacity(solid.shells.len());
1200    for shell in &solid.shells {
1201        let mut edge_ids = rustc_hash::FxHashSet::default();
1202        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|loop_record| &loop_record.coedges) {
1203            edge_ids.insert(coedge.edge_id);
1204        }
1205        let edges = solid.edges.iter().filter(|edge| edge_ids.contains(&edge.id)).cloned().collect::<Vec<_>>();
1206        let vertex_ids = edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect::<rustc_hash::FxHashSet<_>>();
1207        let mut lump = BrepSolid {
1208            mass_properties_cache: Default::default(),
1209            vertices: solid.vertices.iter().filter(|vertex| vertex_ids.contains(&vertex.id)).cloned().collect(),
1210            edges,
1211            shells: vec![shell.clone()],
1212            genus: 0,
1213            cells: Vec::new(),
1214            ..solid.clone()
1215        };
1216        // genus = S − χ/2, χ = V − E + F − H over the non-degenerate cells,
1217        // as `validate` reads it.
1218        let live = lump.edges.iter().filter(|edge| !edge.degenerate).flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect::<rustc_hash::FxHashSet<_>>();
1219        let chi = live.len() as i64 - lump.edges.iter().filter(|edge| !edge.degenerate).count() as i64 + shell.faces.len() as i64
1220            - lump.bounding_hole_count();
1221        lump.genus = 1 - chi / 2;
1222        let positive = crate::solid_mass_properties(&lump).is_ok_and(|m| m.volume > 0.0);
1223        if !positive || !lump.validate().is_empty() {
1224            return vec![solid.clone()];
1225        }
1226        lumps.push(lump);
1227    }
1228    lumps
1229}