Skip to main content

brep_offset/offset/offset_shell/
pipeline.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// Put every face on one normal convention (surface normal on the CCW
5/// parameter-winding side) and then restore outward normals. The offset shell's
6/// source and offset skins are assembled as independent components whose
7/// per-face `same_sense` can follow opposite conventions; `validate()` only
8/// checks coedge-direction coherence (the `forward` flags), so a joined,
9/// watertight, coedge-coherent manifold can still be normal-incoherent and
10/// report the wrong volume. Re-deriving `same_sense` from the loop winding makes
11/// the coedge-coherent manifold normal-coherent; the signed-volume flip then
12/// orients it outward. Only invoked after a non-coplanar rim weld, so the
13/// coplanar cylinder/prism shells keep their exact assembled orientation.
14/// `BREP_OFFSET_ONE_CALL_IMPRINT` (lane P3b row 6, 2026-10-26): one
15/// `build_imprints` over a composite of every carrier instead of one call per
16/// pair. On by default (promoted 2026-10-27 after the 98 + 144 case oracle
17/// census); `0`/`off` retains the per-pair calls. Re-pinned by independent
18/// oracles, not byte-identical (piece and vertex numbering is the single
19/// call's).
20fn one_call_imprint_enabled() -> bool {
21    switch!("BREP_OFFSET_ONE_CALL_IMPRINT", true)
22}
23
24thread_local! {
25    static ONE_CALL_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
26}
27
28
29fn coheres_face_normals(solid: &mut BrepSolid) -> Result<(), KernelRefusal> {
30    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
31        face.same_sense = parameter_space_area(face).or_refuse(KernelStage::Sew, "parameter_space_area")? > 0.0;
32    }
33    // Outward is a PER-SHELL property: a through-hole shelled at both ends
34    // legitimately produces two disjoint closed components (the outer wall
35    // tube and the hole wall tube), and a single global signed-volume flip
36    // cannot orient both.
37    for shell_index in 0..solid.shells.len() {
38        let single = BrepSolid {
39            mass_properties_cache: Default::default(),
40            cells: Default::default(),
41            id: solid.id,
42            vertices: solid.vertices.clone(),
43            edges: solid.edges.clone(),
44            shells: vec![solid.shells[shell_index].clone()],
45            genus: 0,
46            kind: crate::BodyKind::Solid,
47        };
48        // Read for its SIGN only, through the per-face term memo
49        // (`solid_signed_volume_for_sign`: the verdict against the bar is the
50        // exact integral's, and a face read about the same reference before —
51        // the next feature's push, the boolean assembler's own check — is
52        // served its term). The exact read here cost 0.26 s on the shelled-box
53        // report's 34-face shell, 42 of its faces fitted.
54        if crate::signed_volume_against(&single, 0.0).or_refuse(KernelStage::Sew, "solid_signed_volume")? < 0.0 {
55            flip_shell_faces(&mut solid.shells[shell_index])?;
56        }
57    }
58    Ok(())
59}
60
61/// Mint a vertex at every SELF-TOUCH of the source's faces before the shell
62/// reads their trims.
63///
64/// A face whose loops touch at an EDGE INTERIOR is a pinched region: the
65/// reported 2026-09-09 document's r = 6 through-hole kisses both r = 4 fillet
66/// setbacks on the top face, at (16, 20, 10) and (10, 20, 16), with no vertex
67/// there.  The fragment stage's 2D arrangement resolves such a pinch by
68/// carving the touched-off corner into its own region, whose loop walks the
69/// closed hole chain in a PARTIAL run — which `build_loop` can only assemble
70/// when the touch is a vertex of both touching edges, and otherwise refuses
71/// with "chain N fragmented into an incomplete run".
72///
73/// The boolean lane mints that vertex inside `build_imprints`
74/// (`imprint/self_touch.rs`).  Nothing minted it here: the shell fragments
75/// its SOURCE against an EMPTY imprint, and its offset carriers — whose trims
76/// are copied from the source faces — deliberately keep their boundaries
77/// un-split, so both arrived at the arrangement pinched.  Splitting the
78/// source once, before the carriers are built from it, fixes both: every
79/// carrier inherits the split trim by construction.
80///
81/// Returns `None` when no face self-touches, so every part that was never
82/// pinched keeps its exact previous path.  Escape hatch:
83/// `BREP_SELF_TOUCH_SPLIT=0`, the same one the imprint lane honours.
84fn split_self_touching_source(source: &BrepSolid) -> Result<Option<BrepSolid>, KernelRefusal> {
85    if std::env::var("BREP_SELF_TOUCH_SPLIT").as_deref() == Ok("0") {
86        return Ok(None);
87    }
88    // The same derivation `offset_shell_impl` uses for every other band, so
89    // the source scan and the carrier-pair scans agree on what "touching"
90    // means.
91    let scale = crate::solid_scale(source);
92    let tolerance = 1e-7f64.max(scale * 1e-9);
93    let edge_splits = crate::imprint::self_touch_edge_splits(source, SOURCE_OPERAND, tolerance, scale)?;
94    if edge_splits.is_empty() {
95        return Ok(None);
96    }
97    os_debug!(
98        "self-touch: source split on {} edge(s): {:?}",
99        edge_splits.len(),
100        edge_splits
101            .iter()
102            .map(|split| split.edge_id)
103            .collect::<Vec<_>>(),
104    );
105    let imprint = ImprintResultRecord {
106        faces_in_unproved_pairs: None,
107        edge_splits,
108        ..empty_imprint()
109    };
110    Ok(Some(apply_edge_splits(source, SOURCE_OPERAND, &imprint)?))
111}
112
113/// How far past the grown outline a planar opening wall that meets a RULED
114/// opening is padded, in units of the offset-skin band the wall selection reads
115/// (see the wall construction).
116///
117/// Measured on the torus wedge through the pipeline, grown by 0.05, 0.1, 0.5
118/// and 0.999 (band 2e-3): a clearance of 2 or 2.5 bands still shreds the cap
119/// into 22 to 36 faces with the area 5% to 11% high; from 4 bands on every
120/// member builds its 6 faces, and from 4 to 32 bands each member's volume moves
121/// by at most 1.2e-7. 16 sits four times above the first clean reading.
122const RULED_NEIGHBOUR_CLEARANCE_BANDS: f64 = 16.0;
123
124/// How far past its opening plane an inward carrier is grown, as a fraction of
125/// the shell distance (see the fall-short reach in the carrier loop).
126const REACH_CLEARANCE: f64 = 0.25;
127
128/// `BREP_OFFSET_EXACT_PLANAR_PCURVES` (default on since the 2026-11-18
129/// promotion; `=0` restores the imprint's pcurves): every
130/// coedge of a planar face the offset BUILT (an offset or a wall, never a
131/// retained source face) takes the EXACT affine image
132/// of its own 3D edge as its pcurve, where that edge lies on the plane.
133///
134/// A plane's trim may still carry the pcurve of the imprint section it was cut
135/// from, and that section need not be the edge the assembly kept: on a boss
136/// under a rim fillet shelled through its bottom, with the boss's one cylinder
137/// face extended to its full domain, the opening wall's arc sat 6.7e-6 off the
138/// cylinder's offset while the edge itself sat on both, and the shell's volume
139/// read up to 3.8e-5 off its oracle depending only on where the cylinder's
140/// seam sat. The image of an edge on its plane is exact (the inverse affine map
141/// of the edge's control net), so the trim no longer depends on the section.
142fn exact_planar_pcurves_on() -> bool {
143    switch!("BREP_OFFSET_EXACT_PLANAR_PCURVES", true)
144}
145
146/// The pass behind [`exact_planar_pcurves_on`]: the number of coedges whose
147/// pcurve changed. A loop with any edge not on its plane within `tolerance`
148/// (the exact lane declines it) keeps every pcurve it has.
149fn exact_planar_pcurves(solid: &mut BrepSolid, built: &HashSet<u64>, tolerance: f64) -> Result<usize, KernelRefusal> {
150    let edges: HashMap<u64, EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge.clone())).collect();
151    let mut replaced = 0usize;
152    for shell in &mut solid.shells {
153        for face in &mut shell.faces {
154            if !built.contains(&face.id) || !face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
155                continue;
156            }
157            // All or nothing per loop: one declined edge beside replaced ones
158            // would leave a gap in the loop's parameter space.
159            for loop_record in &mut face.loops {
160                let mut exact = Vec::with_capacity(loop_record.coedges.len());
161                for coedge in &loop_record.coedges {
162                    let Some(edge) = edges.get(&coedge.edge_id) else { break };
163                    if edge.degenerate || !(edge.t0 < edge.t1) {
164                        break;
165                    }
166                    let Ok(Some(fit)) = brep_geometry::pcurve::affine_pcurve_on_range(&face.surface, &edge.curve, edge.t0, edge.t1, coedge.forward, tolerance) else {
167                        break;
168                    };
169                    exact.push(fit.curve);
170                }
171                if exact.len() != loop_record.coedges.len() {
172                    continue;
173                }
174                for (coedge, pcurve) in loop_record.coedges.iter_mut().zip(exact) {
175                    coedge.pcurve = pcurve;
176                    replaced += 1;
177                }
178            }
179        }
180    }
181    if replaced > 0 {
182        solid.mass_properties_cache = Default::default();
183    }
184    Ok(replaced)
185}
186
187/// What the pipeline assembles.
188#[derive(Clone, Copy, Debug, Eq, PartialEq)]
189pub(super) enum Body {
190    /// A shell: the retained source faces, their offset skins and the walls
191    /// at the openings, bounding the material between source and offset.
192    Shell,
193    /// The offset body itself: the offset skins alone, closed by their
194    /// mutual sections; `opening_face_ids` are HELD faces, copied at
195    /// distance zero as walls, with no source face assembled and no skin
196    /// flipped. The whole-solid offset and the boolean fallback's offset
197    /// body are built this way.
198    Whole,
199}
200
201
202#[cfg(not(test))]
203fn forced_direct_refusal() -> Option<KernelRefusal> {
204    None
205}
206
207/// `BREP_OFFSET_EVERY_SKIN_PIECE` (default on; `=0` keeps the seed's one
208/// piece): see EVERY SKIN PIECE in the offset selection.
209fn every_skin_piece_enabled() -> bool {
210    crate::switch!("BREP_OFFSET_EVERY_SKIN_PIECE", true)
211}
212
213/// `BREP_OFFSET_STAND_IN_ON_OWN_OFFSET` (default on since the 2026-11-18
214/// promotion; `=0` restores the largest piece): see ON ITS OWN OFFSET in the
215/// offset selection.
216fn stand_in_on_own_offset_on() -> bool {
217    crate::switch!("BREP_OFFSET_STAND_IN_ON_OWN_OFFSET", true)
218}
219
220/// `BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE` (default on; `=0` restores): when an
221/// inward shell's assembly fails, EVERY SKIN PIECE is retried on the seeded
222/// path too. Past 2.0 a reported box and pin model's bore skin comes apart into one piece
223/// per corner channel and the seed answered for one of them. Only as a retry:
224/// a shell the seed's choice closes keeps that answer.
225fn every_seeded_skin_piece_enabled() -> bool {
226    crate::switch!("BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE", true)
227}
228
229/// `BREP_OFFSET_WALL_INSIDE_SOURCE_LANE` (default on; `=0` restores): an
230/// outward shell whose wall selection keeps a fragment inside the source
231/// refuses by name (`offset_shell_wall_inside_source`), which takes the boolean
232/// lane, instead of returning a shell with a fin in it.
233fn wall_inside_source_lane_on() -> bool {
234    crate::switch!("BREP_OFFSET_WALL_INSIDE_SOURCE_LANE", true)
235}
236
237pub fn offset_shell(
238    source: &BrepSolid,
239    opening_face_ids: &[u64],
240    distance: f64,
241) -> Result<OffsetShellResultRecord, KernelRefusal> {
242    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
243        let mut record = offset_shell(&scaled.source, opening_face_ids, scaled.distance).map_err(|error| scaled.refusal(error))?;
244        record.solid = scaled.back(&record.solid, "offset_shell")?;
245        return Ok(record);
246    }
247    let direct = match forced_direct_refusal() {
248        Some(forced) => Err(forced),
249        None => offset_body(source, opening_face_ids, distance, Body::Shell, "offset_shell"),
250    };
251    let mut shelled = offset_shell_lanes(source, opening_face_ids, distance, direct)?;
252    if membrane_shells_on() {
253        // An unchanged body keeps the membrane reading taken on it (one mass
254        // pass instead of two: ~75 ms of shell/rounded-tray's 0.19 s).
255        let membranes = match drop_folded_shells_reading(&mut shelled.solid, distance) {
256            Some(unchanged) => unchanged,
257            None => membrane_shell_indices(&shelled.solid, distance),
258        };
259        let paired = paired_face_ids(&shelled.solid);
260        if !membranes.is_empty() || !paired.is_empty() {
261            for (first, second) in &paired {
262                let shell = shelled.solid.shells.iter().position(|shell| shell.faces.iter().any(|face| face.id == *first));
263                os_debug!(
264                    "membrane pair: faces {first} and {second} in shell {shell:?} of {:?} faces",
265                    shell.map(|index| shelled.solid.shells[index].faces.len())
266                );
267            }
268            return Err(KernelRefusal::unsupported(KernelStage::Validate, "offset_shell_membrane", format!(
269                "offset_shell: at this distance the result has {} shell(s) enclosing no volume and \
270                 {} pair(s) of faces bounded by the same edges{} (zero-thickness membranes \
271                 beside the cavity), which no solid carries",
272                membranes.len(),
273                paired.len(),
274                paired.first().map(|(a, b)| format!(", first faces {a} and {b}")).unwrap_or_default()
275            )));
276        }
277    }
278    Ok(shelled)
279}
280
281/// `BREP_OFFSET_MEMBRANE_SHELLS` (default on; `=0` restores): a shell of the
282/// result that encloses nothing (made only of FOLDED faces, each loop running
283/// along its edges once in each direction, closed by point edges; or of zero
284/// volume over its area; or a bag, its faces pairing up on the same edges) is
285/// removed with the edges and vertices only it used, when the
286/// rest still validates. Otherwise, and for two faces of one real shell bounded
287/// by the same edges (a zero-thickness fin), the shell is refused as a
288/// membrane.
289///
290/// Cause (a reported box and pin model): at 2.38 and 2.40 the result reported
291/// three shells, two of them single folded faces of about 6.5e-6 mm^2 at the
292/// floor/wall corner; at 2.46 (with the corner-debris switch) six more, folded
293/// faces and two-face bags of volume 1e-8 over area 4e-3. None shares an edge
294/// with the cavity's shell. `validate()` accepts them all and the volume is
295/// right, but the shell count is not, nor is anything that walks the shells.
296///
297/// Every test is scaled by the offset distance, since a real piece of the shell
298/// is about |distance| thick: a folded or bag shell is removed only when its
299/// volume is at most 1% of |distance| × its area (a sphere face, whose seam
300/// also runs both ways, encloses the sealed cavity of a sphere-cut shell), and
301/// the zero-volume bar never exceeds 1e-3 × |distance| (a shell 1e-7 thick is
302/// a real sliver, not a membrane).
303fn membrane_shells_on() -> bool {
304    switch!("BREP_OFFSET_MEMBRANE_SHELLS", true)
305}
306
307/// Whether every non-degenerate edge of `face`'s loops is used once forward
308/// and once reversed by the face itself.
309fn face_is_folded(face: &FaceRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
310    let mut balance: HashMap<u64, (usize, usize)> = HashMap::default();
311    for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
312        if edges.get(&coedge.edge_id).is_some_and(|edge| edge.degenerate) {
313            continue;
314        }
315        let entry = balance.entry(coedge.edge_id).or_default();
316        if coedge.forward {
317            entry.0 += 1;
318        } else {
319            entry.1 += 1;
320        }
321    }
322    !balance.is_empty() && balance.values().all(|&(forward, reversed)| forward == 1 && reversed == 1)
323}
324
325/// Whether every face of `shell` shares its whole set of non-degenerate edges
326/// with exactly one other face of it: two-sided sheets with nothing between.
327fn shell_is_bag(shell: &ShellRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
328    let mut sets: HashMap<Vec<u64>, usize> = HashMap::default();
329    for face in &shell.faces {
330        let mut set: Vec<u64> = face
331            .loops
332            .iter()
333            .flat_map(|l| &l.coedges)
334            .map(|coedge| coedge.edge_id)
335            .filter(|id| !edges.get(id).is_some_and(|edge| edge.degenerate))
336            .collect();
337        set.sort_unstable();
338        set.dedup();
339        if set.is_empty() {
340            return false;
341        }
342        *sets.entry(set).or_default() += 1;
343    }
344    !sets.is_empty() && sets.values().all(|&count| count == 2)
345}
346
347/// Removes the shells made only of folded faces, then the edges and vertices
348/// no remaining face uses. Keeps `solid` unchanged when that would leave no
349/// shell or a result that does not validate. A folded or bag shell qualifies
350/// only when its volume is at most 1% of |distance| × its area.
351pub fn drop_folded_shells(solid: &mut BrepSolid, distance: f64) {
352    drop_folded_shells_reading(solid, distance);
353}
354
355
356/// [`drop_folded_shells`], returning [`membrane_shell_indices`] of `solid`
357/// when it is left unchanged (the reading taken here), `None` when shells
358/// were dropped.
359pub(crate) fn drop_folded_shells_reading(solid: &mut BrepSolid, distance: f64) -> Option<Vec<usize>> {
360    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
361    let empty = membrane_shell_indices(solid, distance);
362    let folded: Vec<usize> = (0..solid.shells.len())
363        .filter(|&index| {
364            let shell = &solid.shells[index];
365            empty.contains(&index)
366                || ((shell.faces.iter().all(|face| face_is_folded(face, &edges)) || shell_is_bag(shell, &edges))
367                    && shell_volume_and_area(solid, index)
368                        .is_some_and(|(volume, area)| volume.abs() <= 1e-2 * distance.abs() * area))
369        })
370        .collect();
371    if folded.is_empty() || folded.len() == solid.shells.len() {
372        return Some(empty);
373    }
374    let mut trimmed = solid.clone();
375    let mut index = 0;
376    trimmed.shells.retain(|_| {
377        let keep = !folded.contains(&index);
378        index += 1;
379        keep
380    });
381    let used_edges: HashSet<u64> = trimmed
382        .shells
383        .iter()
384        .flat_map(|shell| &shell.faces)
385        .flat_map(|face| &face.loops)
386        .flat_map(|l| &l.coedges)
387        .map(|coedge| coedge.edge_id)
388        .collect();
389    trimmed.edges.retain(|edge| used_edges.contains(&edge.id));
390    let used_vertices: HashSet<u64> = trimmed
391        .edges
392        .iter()
393        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
394        .collect();
395    trimmed.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
396    crate::boolean::refresh_derived_genus(&mut trimmed);
397    let issues = trimmed.validate();
398    if !issues.is_empty() {
399        os_debug!("folded shells {folded:?} kept: without them the result does not validate: {issues:?}");
400        return Some(empty);
401    }
402    os_debug!("dropped folded shells {folded:?}");
403    *solid = trimmed;
404    None
405}
406
407/// Pairs of faces of one shell bounded by exactly the same non-degenerate
408/// edges: two sides of a zero-thickness fin. By face id.
409pub fn paired_face_ids(solid: &BrepSolid) -> Vec<(u64, u64)> {
410    let mut pairs = Vec::new();
411    let degenerate: HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
412    for shell in &solid.shells {
413        let mut seen: HashMap<Vec<u64>, u64> = HashMap::default();
414        for face in &shell.faces {
415            let mut edges: Vec<u64> = face
416                .loops
417                .iter()
418                .flat_map(|l| &l.coedges)
419                .map(|c| c.edge_id)
420                .filter(|id| !degenerate.contains(id))
421                .collect();
422            edges.sort_unstable();
423            if edges.len() < 2 {
424                continue;
425            }
426            match seen.get(&edges) {
427                Some(&other) => pairs.push((other, face.id)),
428                None => {
429                    seen.insert(edges, face.id);
430                }
431            }
432        }
433    }
434    pairs
435}
436
437/// The volume and area of shell `index` of `solid` on its own.
438fn shell_volume_and_area(solid: &BrepSolid, index: usize) -> Option<(f64, f64)> {
439    let mut alone = solid.clone();
440    alone.shells = vec![solid.shells[index].clone()];
441    crate::solid_mass_properties(&alone).ok().map(|mass| (mass.volume, mass.surface_area))
442}
443
444/// The shells of `solid` that enclose no volume, by index: |V| at most
445/// min(1e-6 × the bounding-box diagonal, 1e-3 × |distance|) × the shell's
446/// area. A shell whose mass properties cannot be measured is never reported.
447pub fn membrane_shell_indices(solid: &BrepSolid, distance: f64) -> Vec<usize> {
448    if solid.vertices.is_empty() {
449        return Vec::new();
450    }
451    let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
452    let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
453    for vertex in &solid.vertices {
454        lo = Vec3::new(lo.x.min(vertex.point.x), lo.y.min(vertex.point.y), lo.z.min(vertex.point.z));
455        hi = Vec3::new(hi.x.max(vertex.point.x), hi.y.max(vertex.point.y), hi.z.max(vertex.point.z));
456    }
457    let thickness = (1e-6 * hi.sub(lo).length()).min(1e-3 * distance.abs());
458    (0..solid.shells.len())
459        .filter(|&index| {
460            shell_volume_and_area(solid, index).is_some_and(|(volume, area)| volume.abs() <= thickness * area)
461        })
462        .collect()
463}
464
465fn offset_shell_lanes(
466    source: &BrepSolid,
467    opening_face_ids: &[u64],
468    distance: f64,
469    direct: Result<OffsetShellResultRecord, KernelRefusal>,
470) -> Result<OffsetShellResultRecord, KernelRefusal> {
471    match direct {
472        Ok(result) => Ok(result),
473        // The boolean lane answers the direct construction's own named
474        // refusals; when it refuses too, the direct refusal is the one
475        // reported, because it names the cause.
476        Err(direct) if super::solid::direct_refusal_takes_the_boolean_lane(&direct) => {
477            os_debug!("direct pipeline refused ({direct}); taking the boolean lane");
478            match super::solid::offset_shell_by_boolean(source, opening_face_ids, distance) {
479                Ok(result) => Ok(result),
480                Err(boolean) => {
481                    os_debug!("boolean lane refused too ({boolean})");
482                    // An outward wall through a curved opening on a sphere or
483                    // a cylinder: the grown body cut by the opening's own
484                    // surface (`opening_surface_cut`).
485                    if distance < 0.0
486                        && super::opening_surface_cut::answers(&direct)
487                        && super::opening_surface_cut::opening_surface_cut_on()
488                    {
489                        match super::opening_surface_cut::build(source, opening_face_ids, distance) {
490                            Ok(result) => return Ok(result),
491                            Err(cut) => os_debug!("opening-surface cut refused too ({cut})"),
492                        }
493                    }
494                    Err(direct)
495                }
496            }
497        }
498        Err(direct) => Err(direct),
499    }
500}
501
502/// The pipeline's one timed entry: `offset_shell` and `offset_solid` both run
503/// through it, so the `timing.*` split and the acceptance step are the same.
504/// Lane O row 38's switch, default on since batch 17 (`0`/`off` restores the fit): it asks the offset pipeline's
505/// imprints for the planar-iso lane's exact pcurves (`ImprintOptions::
506/// exact_iso_pcurves`, parity slice 1): a section the lane answers is an
507/// iso-curve of the ruled carrier and an affine image on the plane, so its
508/// pcurves are written down instead of fitted. Booleans keep their own
509/// default; `BREP_EXACT_ISO_PCURVES` still overrides every imprint.
510fn offset_exact_iso_pcurves_on() -> bool {
511    switch!("BREP_OFFSET_EXACT_ISO_PCURVES", true)
512}
513
514
515pub(super) fn offset_body(
516    source: &BrepSolid,
517    opening_face_ids: &[u64],
518    distance: f64,
519    body: Body,
520    entry: &str,
521) -> Result<OffsetShellResultRecord, KernelRefusal> {
522    profile::reset();
523    let full_turn = if super::full_turn::full_turn_revolutions_on() { super::full_turn::full_turn_revolution_source(source)? } else { None };
524    let source = full_turn.as_ref().unwrap_or(source);
525    // Lane P3b row 3: one stderr write per operation for every profile line
526    // emitted below (`crate::imprint::ProfileSink`).
527    let _profile_sink = crate::imprint::ProfileSink::open();
528    let started = web_time::Instant::now();
529    let result = match offset_shell_any_lane(source, opening_face_ids, distance, body) {
530        // A cylinder split along its own seam: refused with the seam where it
531        // is, retried with the two pieces joined on the full turn seamed in
532        // their gap (`full_turn.rs`). Only a refusal is retried.
533        Err(error) if super::full_turn::full_turn_revolutions_on() => match super::full_turn::seam_pieces_joined(source, opening_face_ids)? {
534            Some(joined) => offset_shell_any_lane(&joined, opening_face_ids, distance, body).map_err(|_| error),
535            None => Err(error),
536        },
537        other => other,
538    }
539    .and_then(|result| {
540        let mut clock = web_time::Instant::now();
541        let connected = outward_shell_is_connected(source, distance, &result);
542        profile::lap(&mut clock, profile::ACCEPTANCE);
543        connected.map(|()| result)
544    });
545    profile::add(profile::TOTAL, started.elapsed());
546    profile::report(entry);
547    result
548}
549
550/// Every shell of an OUTWARD result must bound volume. The shell is the grown
551/// body less the source with the openings held, so it can be disconnected
552/// (opening a cylinder's lateral face leaves its two grown caps as two
553/// slabs), but each of its shells encloses material. A shell that encloses
554/// none, a lone face that happened to close, is a fragment of an assembly that
555/// went wrong and still validated. Measured on 2026-09-26: a free-form D whose
556/// fitted opening wall sat within the fit tolerance of its carriers' sections
557/// returned its body plus 62 single-face shells of volume under 3e-24, each
558/// valid, with the right total volume. So this refuses by name for EVERY
559/// outward shell, not only for the lane that produced those.
560pub fn outward_shell_is_connected(
561    source: &BrepSolid,
562    distance: f64,
563    result: &OffsetShellResultRecord,
564) -> Result<(), KernelRefusal> {
565    if distance >= 0.0 || result.solid.shells.len() <= 1 {
566        return Ok(());
567    }
568    let scale = crate::solid_scale(source).max(1.0);
569    let volumes = result
570        .solid
571        .shells
572        .iter()
573        .map(|shell| {
574            let mut one = result.solid.clone();
575            one.shells = vec![shell.clone()];
576            crate::solid_mass_properties(&one)
577                .map(|properties| properties.volume)
578                .or_refuse(KernelStage::Validate, "solid_mass_properties")
579        })
580        .collect::<Result<Vec<f64>, KernelRefusal>>()?;
581    let total = volumes.iter().map(|volume| volume.abs()).sum::<f64>();
582    let floor = (1e-9 * total).max(1e-12 * scale * scale * scale);
583    let empty = volumes.iter().filter(|volume| volume.abs() <= floor).count();
584    if empty == 0 {
585        return Ok(());
586    }
587    Err(refusals::empty_shell(result.solid.shells.len(), empty, floor).into())
588}
589
590fn offset_shell_any_lane(
591    source: &BrepSolid,
592    opening_face_ids: &[u64],
593    distance: f64,
594    body: Body,
595) -> Result<OffsetShellResultRecord, KernelRefusal> {
596    // Pinched source faces are un-modellable by the arrangement until the
597    // touch is a vertex; do it once here so BOTH `offset_shell_impl` attempts
598    // and every carrier built from the source see the same topology.
599    let prepared = split_self_touching_source(source)?;
600    let source = prepared.as_ref().unwrap_or(source);
601    // The revolved-wedge lane answers a SHELL question (the material between
602    // a revolve and its grown image); the offset body takes the pipeline.
603    if body == Body::Whole {
604        // Row 36 (`BREP_OFFSET_SPHERE_BODY`, default off): the offset body of a
605        // ball is the ball scaled about its centre (`sphere_body.rs`); it
606        // declines to the pipeline on anything else.
607        if opening_face_ids.is_empty() {
608            if let Some(result) = sphere_body::sphere_body(source, distance) {
609                return Ok(result);
610            }
611            // `BREP_OFFSET_TORUS_APPLE` (default on; `=0` restores): a whole torus grown
612            // past its hole is the revolved apple (`torus_body.rs`).
613            if let Some(result) = super::torus_body::torus_apple(source, distance) {
614                return Ok(result);
615            }
616        }
617        return imprint_attempts(source, opening_face_ids, distance, body);
618    }
619    // `BREP_OFFSET_BOX_EMPTY_CAVITY` (default on; `=0` restores): an inward shell of a box
620    // whose walls' reach meets across an axis is the box itself, read exactly
621    // (`box_cavity.rs`) in place of the cavity search and its proof.
622    if let Some(unchanged) = super::box_cavity::box_empty_cavity_shell(source, opening_face_ids, distance)? {
623        return Ok(unchanged);
624    }
625    // `BREP_OFFSET_REVOLVED_SHELL` (default on; `=0` restores): an inward shell of a convex
626    // solid of revolution is its section less the cavity, revolved
627    // (`revolved_shell.rs`).
628    if let Some(shell) = super::revolved_shell::revolved_shell(source, opening_face_ids, distance) {
629        return Ok(shell);
630    }
631    // An outward shell of the one circular face of a partial revolve is planar
632    // in the meridian half-plane, fold band and all: build it there and revolve
633    // it once (`revolved_wedge.rs`). Anything else declines and takes the
634    // imprint pipeline, unchanged.
635    if let Some(result) = revolved_wedge::retained_cap_shell(source, opening_face_ids, distance) {
636        return Ok(result);
637    }
638    match revolved_wedge::recognize(source, opening_face_ids, distance) {
639        Ok(revolved_wedge::Recognition::Wedge(wedge)) => {
640            os_debug!("revolved wedge lane: {}", wedge.report());
641            return revolved_wedge::build(&wedge, source);
642        }
643        Ok(revolved_wedge::Recognition::Declined(reason)) => {
644            os_debug!("revolved wedge lane declined: {reason}");
645        }
646        // A source the lane cannot even read is not one it takes; the pipeline
647        // owns every refusal.
648        Err(error) => {
649            os_debug!("revolved wedge lane declined: could not read the source ({error})");
650        }
651    }
652    // `BREP_OFFSET_SPHERE_CUT_SHELL` (default on; `=0` restores): an inward shell of a ball cut by
653    // planes is the source less the moved ball cut by the moved planes
654    // (`sphere_cut_shell.rs`); it declines to the pipeline on anything else.
655    if let Some(result) = sphere_cut_shell::sphere_cut_shell(source, opening_face_ids, distance) {
656        return Ok(result);
657    }
658    // Row 32 (`BREP_OFFSET_PLANAR_SHELL`, default on; `=0` restores): an outward shell of a
659    // convex polyhedron in closed form (`planar_shell.rs`); it declines to the
660    // pipeline on anything else.
661    if let Some(result) = planar_shell::planar_shell(source, opening_face_ids, distance) {
662        return Ok(result);
663    }
664    imprint_attempts(source, opening_face_ids, distance, body)
665}
666
667
668fn imprint_attempts(
669    source: &BrepSolid,
670    opening_face_ids: &[u64],
671    distance: f64,
672    body: Body,
673) -> Result<OffsetShellResultRecord, KernelRefusal> {
674    // An OUTWARD pass that refused after holding back a concave side runs once
675    // more with it continued round its arc (`concave_arc_retry_on`); the
676    // first refusal stands if that fails too.
677    let held = super::outward_side_widen::concave_held();
678    let first = imprint_attempts_once(source, opening_face_ids, distance, body);
679    match first {
680        Err(error) if distance < 0.0 || body == Body::Whole => {
681            if !super::outward_side_widen::concave_arc_retry_on() || super::outward_side_widen::concave_held() == held {
682                return Err(error);
683            }
684            os_debug!("outward pass refused with concave sides held back ({error}); retrying with them continued round their arc");
685            match super::outward_side_widen::with_concave_arc(|| imprint_attempts_once(source, opening_face_ids, distance, body)) {
686                Ok(result) => Ok(result),
687                Err(_) => Err(error),
688            }
689        }
690        other => other,
691    }
692}
693
694fn imprint_attempts_once(
695    source: &BrepSolid,
696    opening_face_ids: &[u64],
697    distance: f64,
698    body: Body,
699) -> Result<OffsetShellResultRecord, KernelRefusal> {
700    // First try with oblique hole-wall carriers extended past their opening
701    // planes (the lane that closes tilted/conical through-holes). If that
702    // extension fired but the arrangement could not assemble the harder
703    // configuration it produced (e.g. the extended bore genuinely intersects
704    // other offset walls), fall back to the un-extended pipeline so every
705    // previously-supported shape keeps its exact path and every refusal keeps
706    // the canonical honesty-gate message.
707    let mut extension_fired = false;
708    let mut reflex_rebuilds = 0usize;
709    let mut shadowed_points = Vec::new();
710    let mut omitted = HashSet::default();
711    let mut vacated_notes = Vec::new();
712    let result = match offset_shell_impl(
713        source,
714        opening_face_ids,
715        distance,
716        body,
717        true,
718        &mut extension_fired,
719        &mut reflex_rebuilds,
720        &HashSet::default(),
721        &HashSet::default(),
722        false,
723        &mut shadowed_points,
724        &mut omitted,
725        &mut vacated_notes,
726    ) {
727        Ok(result) => {
728            // Attribution marker: which pipeline produced this result. A
729            // retry-produced Ok can silently mask a broken extension lane —
730            // always say which attempt won. The reflex-rebuild count rides
731            // along because that lane fires on BOTH attempts: "extension
732            // idle" alone would misread as "the plain pipeline did this".
733            os_debug!(
734                "offset_shell result: FIRST attempt (extension {}, reflex-rebuilt {})",
735                if extension_fired { "fired" } else { "idle" },
736                reflex_rebuilds,
737            );
738            Ok(result)
739        }
740        Err(error) if extension_fired => {
741            os_debug!("extended pipeline failed ({error}); retrying without carrier extension");
742            let mut unused = false;
743            let mut retry_reflex = 0usize;
744            shadowed_points.clear();
745            omitted.clear();
746            let retried = offset_shell_impl(
747                source,
748                opening_face_ids,
749                distance,
750                body,
751                false,
752                &mut unused,
753                &mut retry_reflex,
754                &HashSet::default(),
755                &HashSet::default(),
756                false,
757                &mut shadowed_points,
758                &mut omitted,
759                &mut vacated_notes,
760            );
761            os_debug!(
762                "offset_shell result: RETRY without extension ({}, reflex-rebuilt {retry_reflex})",
763                if retried.is_ok() { "ok" } else { "err" },
764            );
765            retried
766        }
767        Err(error) => Err(error),
768    };
769    // A refusal from a shell whose selection saw two offsets CROSS inside
770    // material thinner than twice the distance says so first: a rib thinner
771    // than 2d shelled inward is that configuration, and the assembly's own
772    // message names only the symptom. A refusal that already names its cause
773    // keeps it. The crossing is looked for here, on the failure path only.
774    match result {
775        // A refusal that already names its CAUSE keeps its own sentence; one
776        // that names a symptom ("connector edge left its plane", an assembly
777        // message) is worth a cause in front of it. Reading the whole prefix as
778        // "anything this module wrote" was too wide: the twin bosses came out
779        // led by a notch sentence when their cause was the shadow cascade, and
780        // the partial cone lost its junction cause behind a connector's.
781        // Each cause is put IN FRONT of the symptom with `with_message`, so the
782        // symptom's class (an assembly's `NonIntegralGenus`, …) survives.
783        Err(error) if !refusal_names_its_cause(&error.message) => {
784            let crossing = name_offset_crossing(source, opening_face_ids, distance, &shadowed_points);
785            let junction = crossing
786                .is_none()
787                .then(|| name_retained_opening_junction(source, opening_face_ids, distance))
788                .flatten();
789            Err(cause_in_front(error, crossing, junction, vacated_notes.first()))
790        }
791        result => result,
792    }
793}
794
795/// The symptom `error` with the first named cause IN FRONT of it: an offset
796/// crossing, else a retained/opening junction, else a vacated rim's note.
797/// Each prefix is a `with_message`, so the symptom's CLASS (an assembly's
798/// `NonIntegralGenus`, …) survives the sentence put before it.
799pub fn cause_in_front(
800    error: KernelRefusal,
801    crossing: Option<String>,
802    junction: Option<String>,
803    note: Option<&String>,
804) -> KernelRefusal {
805    if let Some(crossing) = crossing {
806        return error.with_message(|error| {
807            format!(
808                "offset_shell: {crossing}; a skin partly shadowed that way is not yet \
809                 assembled ({error})"
810            )
811        });
812    }
813    if let Some(junction) = junction {
814        return error.with_message(|error| format!("offset_shell: {junction} ({error})"));
815    }
816    // A rim the closure could not bridge, with what it measured, in front of
817    // whatever the assembly then said about the hole it left.
818    match note {
819        Some(note) => error.with_message(|error| {
820            format!(
821                "offset_shell: a rim vacated by an omitted support was left open — {note} \
822                 ({error})"
823            )
824        }),
825        None => error,
826    }
827}
828
829/// The refusals this module's own cause-naming lanes produce. Anything else is
830/// a symptom another stage reported, and takes a cause in front of it.
831fn refusal_names_its_cause(error: &str) -> bool {
832    [
833        " coincide near ",
834        " touch tangentially near ",
835        "is sealed off from the opening",
836        "cannot tell whether",
837        "omitting the shadowed offsets of source faces",
838        "reads shadowed over its whole extent, so omitting it again",
839        "nested passes without settling",
840        "no retained face keeps any offset skin",
841        "is shadowed at every one of its",
842        "a rim vacated by an omitted support was left open",
843        "junction, so its offset ends inside the cavity",
844        "cross near",
845        "which meet tangentially along source edge",
846        // The opening-wall lane's own named refusals, so a cause of mine never
847        // arrives in front of one of theirs.
848        "folds where the carve",
849        "is curved and not a ruled surface",
850        "cannot be built",
851    ]
852    .iter()
853    .any(|name| error.contains(name))
854}
855
856/// The deepest nesting of `offset_shell_impl` passes one shell may take.
857/// Every re-run changes an input that only grows (the omitted supports, the
858/// cavity bounds, the every-seed flag), so the depth is bounded by the face
859/// count already; this bound makes a re-run that fails to grow its input a
860/// named refusal instead of a stack overflow, whatever the cause.
861pub(super) const MAXIMUM_PASS_DEPTH: usize = 24;
862
863std::thread_local! {
864    static PASS_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
865}
866
867/// One nested pass, counted while it lives.
868struct PassDepth;
869
870impl PassDepth {
871    fn enter() -> Result<Self, KernelRefusal> {
872        let depth = PASS_DEPTH.with(|cell| {
873            let depth = cell.get() + 1;
874            cell.set(depth);
875            depth
876        });
877        let pass = PassDepth;
878        if depth > MAXIMUM_PASS_DEPTH {
879            return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::PASS_BUDGET, format!(
880                "offset_shell: the construction re-ran {MAXIMUM_PASS_DEPTH} nested passes without settling \
881                 which offset supports to omit"
882            )));
883        }
884        Ok(pass)
885    }
886}
887
888impl Drop for PassDepth {
889    fn drop(&mut self) {
890        PASS_DEPTH.with(|cell| cell.set(cell.get().saturating_sub(1)));
891    }
892}
893
894
895
896fn offset_shell_impl(
897    source: &BrepSolid,
898    opening_face_ids: &[u64],
899    distance: f64,
900    body: Body,
901    extend_oblique_carriers: bool,
902    extension_fired: &mut bool,
903    reflex_rebuilds: &mut usize,
904    shadowed_supports: &HashSet<u64>,
905    cavity_bounds: &HashSet<u64>,
906    every_seeded_piece: bool,
907    shadowed_points: &mut Vec<(Vec3, u64)>,
908    omitted_supports: &mut HashSet<u64>,
909    vacated_notes: &mut Vec<String>,
910) -> Result<OffsetShellResultRecord, KernelRefusal> {
911    let _pass = PassDepth::enter()?;
912    profile::attempt();
913    let _sharp_rims = super::carriers::SharpOpeningRims::set(if super::carriers::ruled_miter_on() {
914        super::carriers::sharp_opening_rims(source, opening_face_ids)
915    } else {
916        HashSet::default()
917    });
918    let mut clock = web_time::Instant::now();
919    omitted_supports.clone_from(shadowed_supports);
920    vacated_notes.clear();
921    if !distance.is_finite() || distance.abs() <= MINIMUM_DISTANCE {
922        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_distance", "offset_shell: distance must be finite and non-zero"));
923    }
924    if opening_face_ids.is_empty() && body == Body::Shell {
925        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_no_opening", "offset_shell: at least one opening face is required"));
926    }
927    let source_faces = source
928        .shells
929        .iter()
930        .flat_map(|shell| &shell.faces)
931        .collect::<Vec<_>>();
932    let opening_set = opening_face_ids.iter().copied().collect::<HashSet<_>>();
933    if opening_set
934        .iter()
935        .any(|id| !source_faces.iter().any(|face| face.id == *id))
936    {
937        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_foreign_opening", "offset_shell: opening face does not belong to source"));
938    }
939    let retained = source_faces
940        .iter()
941        .filter(|face| !opening_set.contains(&face.id))
942        .map(|face| face.id)
943        .collect::<Vec<_>>();
944    if retained.is_empty() {
945        return Err(refusals::no_retained_face().into());
946    }
947    let mut carriers = Vec::new();
948    let mut open_section_reach = false;
949    if distance < 0.0 && std::env::var("BREP_OFFSET_OPEN_SECTION_REACH").as_deref() != Ok("0") {
950        for face in &source_faces {
951            if retained.contains(&face.id) && open_profile_has_construction_headroom(face)? {
952                open_section_reach = true;
953                break;
954            }
955        }
956    }
957    // Faces whose folded part was carved away, by source face id. Later stages
958    // that read a retained face's TRIM — the apex-cap scan below is the one —
959    // must read the carved trim, not the one the source still carries.
960    let mut carved_supports = HashMap::<u64, FaceRecord>::default();
961    // Lane O item 705: (neighbour face, opening face, rim edge) of every
962    // tangent junction with a curved opening the neighbour cannot reach.
963    let mut tangent_rim_rounds: Vec<(u64, u64, u64)> = Vec::new();
964    // Supports omitted because their offset collapsed (`planar_rim_tube`).
965    let mut collapsed_supports: Vec<u64> = Vec::new();
966    // The carriers that are such tubes, by index, with the opening each
967    // tube's mouth lies on.
968    let mut rim_tubes: HashMap<usize, u64> = HashMap::default();
969    // The tubes of SURVIVING rounds, by carrier index: such a tube rides its
970    // round's id, so reading it shadowed must drop only the tube, never the
971    // round's own offset.
972    let mut surviving_tubes = HashSet::<usize>::default();
973    // The carriers of a BAND carve's kept pieces (whole body only), by index:
974    // one wholly shadowed piece drops alone, never its source face's others.
975    let mut band_pieces = HashSet::<usize>::default();
976    let mut shielded_cusps = HashSet::<u64>::default();
977
978    for face_id in &retained {
979        let face = source_faces.iter().find(|face| face.id == *face_id).unwrap();
980        profile::lap(&mut clock, profile::CARRIER_TRIM);
981        let collapsed = profile::detail("offset_support_collapsed", || offset_support_collapsed(face, distance))?;
982        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
983        if collapsed {
984            os_debug!("omitting collapsed offset support for source face {face_id}");
985            collapsed_supports.push(*face_id);
986            continue;
987        }
988        // A support a previous pass found SHADOWED contributes no skin, and its
989        // carrier must not imprint its neighbours either — see the selection.
990        if shadowed_supports.contains(face_id) {
991            os_debug!("omitting shadowed offset support for source face {face_id}");
992            continue;
993        }
994        // A planar carrier whose source face meets a neighbour at a REFLEX
995        // (concave) edge extends its trim by |distance|: at such a junction
996        // the offset skin must GROW past the source footprint to meet the
997        // neighbour's offset (a pocket wall's source [5,15] → skin
998        // [3.5,16.5]); a source-sized trim leaves a gap no miter can bridge.
999        // The surplus at the face's convex ends is clipped by the imprints +
1000        // on-skin filter. Convex-only faces keep their exact source-sized
1001        // trim — extending them perturbs delicately-selected fragment
1002        // landscapes for no benefit.
1003        let miter = source_faces
1004            .iter()
1005            .find(|face| face.id == *face_id)
1006            .map(|face| face_reflex_miter_tan(source, face))
1007            .transpose()?
1008            .flatten();
1009        // The offsets of two faces joined at a reflex edge meet d·tan(θn/2)
1010        // past the source rim — d only for a perpendicular join. Scale the
1011        // extension to the worst sampled miter (×1.5 headroom so the true
1012        // intersection lands strictly INSIDE the extended trim, never on its
1013        // boundary where the arrangement drops boundary-coincident cuts) and
1014        // cap it: a near-tangential join would ask for an unbounded trim.
1015        let reflex_extension = miter.map(|worst_tan| {
1016            (distance.abs() * worst_tan * 1.5)
1017                .max(distance.abs())
1018                .min(distance.abs() * 12.0)
1019        });
1020        if let Some(extension) = reflex_extension {
1021            os_debug!("carrier for src face {face_id}: reflex-extended by {extension:.4}");
1022        }
1023        // OUTWARD: every retained carrier grows by |distance| across its
1024        // sharp and opening-facing sides (the offsets of a convex junction
1025        // meet past both source rims; a wall plane cuts the surplus), and
1026        // by nothing across a smooth junction into a retained neighbour —
1027        // see `outward_carrier_extension`. A reflex junction needs no
1028        // outward growth at all (those offsets cross inside the trims).
1029        let mut curved_reach = None;
1030        let planar_reach = planar_opening_reach(face, &source_faces, &opening_set, distance)?;
1031        let mut thin_padded = false;
1032        let extension = if distance < 0.0 {
1033            outward_carrier_extension(source, face, &source_faces, &opening_set, distance.abs())?
1034        } else {
1035            let mut inward = crate::CarrierExtension::uniform(reflex_extension.unwrap_or(0.0));
1036            // Only a carrier that becomes its trim box's full rectangle (an
1037            // affine plane with a curved outline element, below) has the box's
1038            // room past a reflex rim INSIDE the box; a slid trim (a straight
1039            // L-shaped outline) needs every side's pad for its inner corners.
1040            if reflex_extension.is_some()
1041                && super::carrier_rebuild::reflex_pad_convex_sides_on()
1042                && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1043                && outline_has_curved_element(source, face)?
1044            {
1045                let [u_min, u_max, v_min, v_max] = super::carrier_rebuild::convex_box_sides(source, face, reflex_extension.unwrap_or(0.0))?;
1046                // Never every side: an all-zero extension is not a carrier
1047                // the size of its trim but NO slide at all, which leaves an
1048                // affine plane at its whole source net (a boss's floor, a
1049                // third of its plane's domain, ran far past its convex rims
1050                // and the shell crossed itself). A face
1051                // whose sides are all convex keeps the uniform pad.
1052                if !(u_min && u_max && v_min && v_max) {
1053                    if u_min { inward.u_min = 0.0; }
1054                    if u_max { inward.u_max = 0.0; }
1055                    if v_min { inward.v_min = 0.0; }
1056                    if v_max { inward.v_max = 0.0; }
1057                }
1058                os_debug!("carrier for src face {face_id}: reflex pad u=({:.4},{:.4}) v=({:.4},{:.4})", inward.u_min, inward.u_max, inward.v_min, inward.v_max);
1059            }
1060            // `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): a skin thinner than
1061            // the fragmenter's graze band is padded past its source rims
1062            // (`thin_skin_pad`), so its sections end far from its corners.
1063            if let Some(pad) = thin_skin_pad(source, face, distance)? {
1064                inward = crate::CarrierExtension { u_min: inward.u_min.max(pad), u_max: inward.u_max.max(pad), v_min: inward.v_min.max(pad), v_max: inward.v_max.max(pad) };
1065                os_debug!("carrier for src face {face_id}: thin skin padded by {pad:.6}");
1066                thin_padded = true;
1067            }
1068            if let Some(reach) = planar_reach {
1069                let grown = reach + REACH_CLEARANCE * distance;
1070                inward = crate::CarrierExtension { u_min: inward.u_min.max(grown), u_max: inward.u_max.max(grown), v_min: inward.v_min.max(grown), v_max: inward.v_max.max(grown) };
1071                os_debug!("carrier for src face {face_id}: planar reach to its opening {reach:.6}");
1072            }
1073            if reflex_extension.is_some() {
1074                let [u_min, u_max, v_min, v_max] =
1075                    apex_corner_reach(source, face, &source_faces, &opening_set, distance)?;
1076                if u_min.max(u_max).max(v_min).max(v_max) > 0.0 {
1077                    inward.u_min = inward.u_min.max(u_min);
1078                    inward.u_max = inward.u_max.max(u_max);
1079                    inward.v_min = inward.v_min.max(v_min);
1080                    inward.v_max = inward.v_max.max(v_max);
1081                    os_debug!(
1082                        "carrier for src face {face_id}: apex corner reach u=({:.4},{:.4}) v=({:.4},{:.4})",
1083                        inward.u_min, inward.u_max, inward.v_min, inward.v_max,
1084                    );
1085                }
1086            }
1087            // An INWARD carrier that falls short of the planar opening it meets
1088            // is grown until it crosses that plane, so the imprint cuts the
1089            // skin there instead of leaving a rim for the ruled weld to cork
1090            // below the opening (`fallshort_opening_reach`).
1091            if let Some((at_v_max, reach)) =
1092                fallshort_opening_reach(source, face, &source_faces, &opening_set, distance)?
1093            {
1094                // Past the plane by a quarter of the shell's own thickness, so
1095                // the section is strictly inside the carrier's trim rather than
1096                // on its boundary. Measured 2026-09-17 over the offset-shell
1097                // suite: every fraction from 0.01 to 2.0 of |d| gives the same
1098                // 73 passing members, while a margin sized in COINCIDENCE BANDS
1099                // (1 to 32 of them, 2e-5 each here) breaks the sphere-under-
1100                // frustum member by 9.4e-2 — the fragile margins are the ones
1101                // far below the construction's own length.
1102                let grown = reach + REACH_CLEARANCE * distance.abs();
1103                if at_v_max {
1104                    inward.v_max = inward.v_max.max(grown);
1105                } else {
1106                    inward.v_min = inward.v_min.max(grown);
1107                }
1108                os_debug!(
1109                    "carrier for src face {face_id}: inward reach to its opening plane {reach:.6}                      at v_{} ",
1110                    if at_v_max { "max" } else { "min" },
1111                );
1112            }
1113            // A CURVED opening has no such construction, and the pipeline
1114            // closes the cavity with whatever completion reaches for: measured
1115            // 7.6% short on the hemisphere cup shelled through its dome.
1116            if let Some((opening, gap)) =
1117                offset_falls_short_of_curved_opening(source, face, &source_faces, &opening_set, distance)?
1118            {
1119                if std::env::var("BREP_OFFSET_CURVED_REACH").as_deref() != Ok("0") {
1120                    curved_reach = curved_opening_reach_source(source, face, distance)?;
1121                }
1122                // `BREP_OFFSET_CURVED_RULED_REACH` (default on; `=0` restores): where the
1123                // rectangle continuation declines (a u-closed band, a tangent
1124                // junction), a v-ruled carrier is grown along its rulings
1125                // until it crosses the curved opening, as the planar reach
1126                // does for a plane (`curved_fallshort_reach`).
1127                let mut ruled_reach = false;
1128                if curved_reach.is_none() {
1129                    if let Some((at_v_max, reach)) =
1130                        curved_fallshort_reach(source, face, &source_faces, &opening_set, distance)?
1131                    {
1132                        let grown = reach + REACH_CLEARANCE * distance.abs();
1133                        if at_v_max {
1134                            inward.v_max = inward.v_max.max(grown);
1135                        } else {
1136                            inward.v_min = inward.v_min.max(grown);
1137                        }
1138                        ruled_reach = true;
1139                        os_debug!(
1140                            "carrier for src face {face_id}: ruled reach to its curved opening {opening} {reach:.6} at v_{}",
1141                            if at_v_max { "max" } else { "min" },
1142                        );
1143                    }
1144                }
1145                // Lane O item 705 (`BREP_OFFSET_TANGENT_RIM_ROUND`, default off):
1146                // a face that meets its curved opening TANGENTIALLY never
1147                // reaches it — its skin runs parallel to the opening at
1148                // exactly d — and the wall there is a round of radius d about
1149                // the rim (`rim_round.rs`). Record the rim; the round carrier
1150                // is emitted beside the apex caps, and this face's carrier is
1151                // built as it is.
1152                if curved_reach.is_none() && !ruled_reach && super::rim_round::tangent_rim_round_enabled() {
1153                    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1154                        let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else {
1155                            continue;
1156                        };
1157                        if mate.id != opening || !uses_are_tangent(face, coedge, mate, mate_use)? {
1158                            continue;
1159                        }
1160                        os_debug!("tangent rim round: source face {face_id} meets opening {opening} tangentially along edge {}", coedge.edge_id);
1161                        tangent_rim_rounds.push((*face_id, opening, coedge.edge_id));
1162                    }
1163                }
1164                if curved_reach.is_none() && !ruled_reach && !tangent_rim_rounds.iter().any(|(id, _, _)| id == face_id) {
1165                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening_short", format!(
1166                        "offset_shell: the offset skin of source face {face_id} stops {gap:.3e} short of \
1167                         curved opening face {opening}; only a planar opening's skin is grown to meet it"
1168                    )));
1169                }
1170            }
1171            inward
1172        };
1173        if distance < 0.0 {
1174            os_debug!(
1175                "carrier for src face {face_id}: outward extension u=({:.3},{:.3}) v=({:.3},{:.3})",
1176                extension.u_min,
1177                extension.u_max,
1178                extension.v_min,
1179                extension.v_max,
1180            );
1181        }
1182        // CARVE: a support whose offset folds over PART of its trim keeps the
1183        // regular part and drops the rest, instead of being built whole with
1184        // the fold in it. The carrier is built over the CARVED source, so the
1185        // trim it clones stops at the fold locus — and, because that trim no
1186        // longer reaches past the offset's pinch, `offset_surface`'s apex-cone
1187        // pinch retrim does not fire and the cloned pcurves still name the
1188        // pointwise offset.
1189        //
1190        // A carve that cannot be made is not a licence to build the folded
1191        // support anyway: the refusal is the answer, because a carrier with an
1192        // inverted patch in it welds into a shell that validates and bounds the
1193        // wrong solid.
1194        profile::lap(&mut clock, profile::CARRIER_TRIM);
1195        let carved = profile::detail("carve_folded_support", || carve_shell_support(source, face, distance, opening_face_ids, body == Body::Whole))?;
1196        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1197        // A CUT RIM — the face's rim with a planar opening running across
1198        // its surface rather than along a v end — has the trim rebuilt over
1199        // the surface's full rectangle so the opening plane truncates the
1200        // offset skin (`cut_rim_full_rectangle_source`); like the carve, a
1201        // substitute source the carrier is built over.
1202        let cut_rim = if carved.is_none() && curved_reach.is_none() {
1203            cut_rim_full_rectangle_source(source, face, &source_faces, &opening_set, distance)?
1204        } else {
1205            None
1206        };
1207        // A curved face's SHARP outward u-side: the carrier is built over the
1208        // surface continued past it, so it reaches the mitre with its sharp
1209        // neighbour's offset (`sharp_side_continued_source`). Its INWARD
1210        // reflex u-side widens the trim inside the surface's own domain
1211        // instead (`reflex_side_widened_source`).
1212        let sharp_side = if carved.is_none() && cut_rim.is_none() && curved_reach.is_none() {
1213            match sharp_side_continued_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1214                Some(continued) => Some(continued),
1215                None => match band_reach_continued_source(source, face, distance, &extension)? {
1216                    Some(widened) => Some(widened),
1217                    None => match reflex_side_widened_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1218                        Some(widened) => Some(widened),
1219                        None => super::outward_side_widen::outward_sharp_side_widened_source(
1220                            source,
1221                            face,
1222                            &source_faces,
1223                            &opening_set,
1224                            distance,
1225                            &extension,
1226                        )?,
1227                    },
1228                },
1229            }
1230        } else {
1231            None
1232        };
1233        let carrier_source = match (&carved, &cut_rim) {
1234            (None, None) if curved_reach.is_some() => curved_reach.as_ref().unwrap(),
1235            (None, None) if sharp_side.is_some() => sharp_side.as_ref().unwrap(),
1236            (None, Some(rebuilt)) => rebuilt,
1237            (Some(carved), _) => {
1238                os_debug!(
1239                    "carving the fold off source face {face_id}: {:.1}% of its trim kept, \
1240                     {} new boundary pcurve(s)",
1241                    carved.kept_fraction * 100.0,
1242                    carved.fold_boundary
1243                );
1244                carved_supports.insert(*face_id, carved.face.clone());
1245                if carved.shielded_cusp {
1246                    shielded_cusps.insert(*face_id);
1247                }
1248                &carved.solid
1249            }
1250            (None, None) => source,
1251        };
1252        profile::lap(&mut clock, profile::CARRIER_TRIM);
1253        let (mut carrier, lane) = carrier_solid_sided_lane(carrier_source, *face_id, distance, &extension)?;
1254        os_debug!(
1255            "carrier for src face {face_id}: lane {lane:?} carved {} surface u {:?} v {:?} source face u {:?} v {:?}",
1256            carved.is_some(),
1257            carrier.shells[0].faces[0].surface.domain_u().ok(),
1258            carrier.shells[0].faces[0].surface.domain_v().ok(),
1259            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_u().ok()),
1260            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_v().ok()),
1261        );
1262        profile::carrier_built(lane, clock.elapsed());
1263        clock = web_time::Instant::now();
1264        if (distance < 0.0 || reflex_extension.is_some()) && face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1265            // PADDED planes: the pad slides the plane's net while the trim's
1266            // loops are cloned in uv, so an INTERIOR loop (a bore or boss rim
1267            // in the face) is carried outward with the grown outline instead
1268            // of following the neighbour's offset.
1269            //   OUTWARD: a bore's rim grew (r=4.68 → 5.15) while the shrunk
1270            //   offset bore (r=3.68) that must hole this plane fell inside the
1271            //   enlarged void, so neither the imprint nor the orphan-rim weld
1272            //   could cut it.
1273            //   INWARD, reflex-extended: the same slide moves a REFLEX hole
1274            //   rim the wrong way — a sphere sitting under a frustum's base
1275            //   annulus (the user's 2026-09-07 document) had its r=8.3 rim
1276            //   scaled to 9.22 while the shrunk offset sphere (r=7.3) crosses
1277            //   the offset plane at r=7.23, inside the enlarged hole: the
1278            //   pair imprint found nothing and the rim stayed one-use.
1279            // Drop the interior loops (as the wall carriers do): the
1280            // neighbour's carrier imprints — or its rim, welded in as a
1281            // hole — cut the true opening, and the seeded selection drops
1282            // the disk over it. A CONVEX interior rim on the same face (a
1283            // through-bore in a pocket floor) is safe to drop too: its
1284            // offset bore imprints at r+d and the ring inside is rejected by
1285            // class (Out) or by the on-skin filter, no seed involved.
1286            drop_wall_interior_loops(&mut carrier)?;
1287            // A free-form outline grown uniformly outward is trimmed by its
1288            // outline OFFSET, not the slid net's scaled trim
1289            // (`outline_offset_carrier`).
1290            let pads = [extension.u_min, extension.u_max, extension.v_min, extension.v_max];
1291            let widest = pads.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1292            let narrowest = pads.iter().copied().fold(f64::INFINITY, f64::min);
1293            // `BREP_OFFSET_CONVEX_POLYGON_OUTLINE`: pads equal but for their last
1294            // bits (a tetrahedron's turned sides read 2.121 four ways, not
1295            // bit-equal) are the uniform pad too.
1296            let uniform = (extension.u_min == extension.u_max
1297                && extension.u_min == extension.v_min
1298                && extension.u_min == extension.v_max)
1299                || (convex_polygon_outline_enabled() && widest - narrowest <= 1e-9 * widest.abs());
1300            if distance < 0.0 && uniform {
1301                // Past the walls' sections by the same clearance a planar
1302                // neighbour of a ruled wall gets, so each section lies
1303                // strictly INSIDE the fitted trim rather than on it.
1304                let clearance =
1305                    RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance);
1306                if let Some(rebuilt) = outline_offset_carrier(source, face, widest, clearance, &carrier)? {
1307                    os_debug!(
1308                        "carrier for src face {face_id}: outline trimmed by its offset by {:.4}",
1309                        widest + clearance
1310                    );
1311                    carrier = rebuilt;
1312                } else if super::outward_side_widen::slid_trim_falls_short(
1313                    source,
1314                    face,
1315                    &source_faces,
1316                    &carrier,
1317                    distance,
1318                    narrowest,
1319                )? {
1320                    // `BREP_OFFSET_OUTWARD_SIDE_WIDEN`: a slid trim short of
1321                    // its pad takes the plane's rectangle, and the
1322                    // neighbours' offsets cut the skin from it.
1323                    os_debug!("carrier for src face {face_id}: slid trim falls short, full rectangle");
1324                    carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1325                    // Only the rectangle's own edges: a section along the
1326                    // replaced trim's records would be dropped as lying on
1327                    // this carrier's boundary.
1328                    super::outward_side_widen::keep_used_edges(&mut carrier);
1329                }
1330            } else if distance < 0.0 && nonuniform_slid_trim_on() && super::outward_side_widen::slid_trim_falls_short(
1331                source,
1332                face,
1333                &source_faces,
1334                &carrier,
1335                distance,
1336                narrowest,
1337            )? {
1338                // The same fallback for a NON-uniform extension (a drafted
1339                // neighbour pads one side more): the rectangle does not depend
1340                // on the pads being equal. Measured on a block leaning out 1
1341                // over its height 6, opened through an end face, with a slot
1342                // through its top running out of the far end: the top's slid
1343                // trim kept its notch at the slot wall while the wall's offset
1344                // stood 1 past it, and the shell refused with open edges along
1345                // that line; with the side vertical the extension is uniform
1346                // and this fallback already built it.
1347                os_debug!("carrier for src face {face_id}: slid trim falls short (non-uniform extension), full rectangle");
1348                carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1349                super::outward_side_widen::keep_used_edges(&mut carrier);
1350            }
1351        }
1352        // An inward reflex junction needs a construction plane extending PAST
1353        // the source rim. Sliding the net under a free-form trim scales that
1354        // trim instead: a notched revolve cap's notch grows, and clips away the
1355        // sections with the box's offsets. Even its curved convex boundary can
1356        // fall inside the neighbouring offset section after that scaling.
1357        // Use the extended plane's full rectangle and let the neighbouring
1358        // carriers cut the skin. The source face and the offset surface stay
1359        // unchanged. Circular outlines need the same construction: scaling a
1360        // reflex arc can also clip away its offset cylinder's section. Unlike
1361        // an outline offset, this needs no approximation of
1362        // the planar rim's parallel curve (which may collapse at a tight turn).
1363        //
1364        // A THIN-SKIN pad (`thin_skin_pad`) slides the net the same way, by
1365        // much more than the distance, and a trim that is not star-shaped
1366        // about the slide's centre moves some of its sides INWARD: an end
1367        // wall joined to a disc had its straight side carried 0.084 into the
1368        // face at d = 0.06, short of the neighbouring wall's offset, and the
1369        // skin never reached it. Such a carrier takes the rectangle too.
1370        if distance > 0.0
1371            && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1372            && ((reflex_extension.is_some() && outline_has_curved_element(source, face)?)
1373                || (thin_padded && thin_pad_rectangle_enabled() && outline_has_curved_element(source, face)?))
1374        {
1375            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1376        }
1377        if planar_reach.is_some() {
1378            // A chamfer's trimmed polygon can cut diagonally across its
1379            // patch. Scaling that polygon with the net can still clip the
1380            // opening section. Let the opening and neighbouring offsets
1381            // trim the grown construction rectangle instead.
1382            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1383        }
1384        if open_section_reach {
1385            if let Some(continued) = open_section_construction(source, face, &carrier, &extension, distance)? {
1386                carrier = continued;
1387                os_debug!("carrier for src face {face_id}: open section uses its natural construction rectangle");
1388            }
1389        }
1390        // The rim a shadowed support's removal VACATED in this carrier's trim:
1391        // a slot narrower than 2|d| that runs out through this face leaves a
1392        // notch its own skin has to close, because the dilation fills the slot.
1393        // The source face keeps its notch; only the carrier is bridged.
1394        if distance < 0.0 && !shadowed_supports.is_empty() {
1395            let report = close_vacated_rims(
1396                &mut carrier,
1397                source_faces
1398                    .iter()
1399                    .find(|face| face.id == *face_id)
1400                    .copied()
1401                    .unwrap_or(face),
1402                &source_faces,
1403                shadowed_supports,
1404            )?;
1405            if report.closed > 0 {
1406                os_debug!(
1407                    "carrier for src face {face_id}: {} vacated rim run(s) bridged",
1408                    report.closed
1409                );
1410            }
1411            for declined in &report.declined {
1412                os_debug!("carrier for src face {face_id}: vacated rim left alone — {declined}");
1413                vacated_notes.push(format!("source face {face_id}: {declined}"));
1414            }
1415        }
1416        if carved.as_ref().is_some_and(|carved| !carved.other_pieces.is_empty()) {
1417            band_pieces.insert(carriers.len());
1418        }
1419        carriers.push(Carrier {
1420            solid: carrier,
1421            source_face_id: *face_id,
1422            kind: OffsetFaceRole::Offset,
1423        });
1424        // A BAND carve's other kept pieces (whole body only): a carrier each,
1425        // over its own carved source, the selection reading every one against
1426        // the whole source.
1427        for piece in carved.iter().flat_map(|carved| &carved.other_pieces) {
1428            let (piece_carrier, piece_lane) = carrier_solid_sided_lane(&piece.solid, *face_id, distance, &extension)?;
1429            os_debug!("carrier for src face {face_id}: band piece lane {piece_lane:?} ({:.1}% kept)", piece.kept_fraction * 100.0);
1430            band_pieces.insert(carriers.len());
1431            carriers.push(Carrier {
1432                solid: piece_carrier,
1433                source_face_id: *face_id,
1434                kind: OffsetFaceRole::Offset,
1435            });
1436        }
1437    }
1438    profile::lap(&mut clock, profile::CARRIER_TRIM);
1439    // APEX-CAP carriers: a retained face whose DEGENERATE edge (an apex
1440    // point, e.g. a conic crater's tip) offsets into a RING is an EXTERIOR
1441    // cone offset — the parallel surface truncates at the ring and the exact
1442    // rolling-ball offset closes it with a SPHERE of radius |distance| about
1443    // the apex. Emit that sphere as an extra carrier: the ring imprint
1444    // (sphere × offset frustum) splits it, the on-skin filter keeps exactly
1445    // the cap sector (its points are |d| from the apex and ≥|d| from the
1446    // rest of the face), and the ring becomes two-use.
1447    let mut apex_cap_sources = HashSet::default();
1448    let mut apex_cap_pairs: Vec<(usize, usize)> = Vec::new();
1449    {
1450        let retained_count = carriers.len();
1451        for index in 0..retained_count {
1452            // A CARVED support's trim is the carved one. Its coedges name edges
1453            // that live only in the carved clone, so the `source.edges` lookup
1454            // below finds nothing and the apex-cap lane skips the face — which
1455            // is right: the carve already ended that carrier at the offset's own
1456            // pinch, and there is no apex ring left to cap.
1457            let carved_face = carved_supports.get(&carriers[index].source_face_id);
1458            let source_face = carved_face
1459                .or_else(|| source_by_id_lookup(&source_faces, carriers[index].source_face_id));
1460            let Some(source_face) = source_face else {
1461                continue;
1462            };
1463            let carrier_surface = carriers[index].solid.shells[0].faces[0].surface.clone();
1464            for coedge in source_face
1465                .loops
1466                .iter()
1467                .flat_map(|loop_record| &loop_record.coedges)
1468            {
1469                let Some(edge) = source
1470                    .edges
1471                    .iter()
1472                    .find(|edge| edge.id == coedge.edge_id)
1473                else {
1474                    continue;
1475                };
1476                if !edge.degenerate {
1477                    continue;
1478                }
1479                // Image of the degenerate edge on the offset surface.
1480                let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
1481                let mut ring = Vec::new();
1482                for sample in 0..=8 {
1483                    let uv = coedge
1484                        .pcurve
1485                        .evaluate(p0 + (p1 - p0) * sample as f64 / 8.0).or_refuse(KernelStage::Sew, "evaluate")?;
1486                    ring.push(carrier_surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Sew, "evaluate")?);
1487                }
1488                let spread = ring
1489                    .iter()
1490                    .map(|point| point.sub(ring[0]).length())
1491                    .fold(0.0f64, f64::max);
1492                if spread <= distance.abs() * 1e-2 {
1493                    continue;
1494                }
1495                let apex = source
1496                    .vertices
1497                    .iter()
1498                    .find(|vertex| vertex.id == edge.start_vertex_id)
1499                    .map(|vertex| vertex.point)
1500                    .ok_or_else(|| "offset_shell: apex vertex missing".to_string()).or_refuse(KernelStage::Sew, "offset_shell_apex_vertex_missing")?;
1501                let centroid = ring
1502                    .iter()
1503                    .fold(Vec3::default(), |sum, point| sum.add(*point))
1504                    .scale(1.0 / ring.len() as f64);
1505                let axis = apex.sub(centroid);
1506                let axis = if axis.length() > 1e-9 {
1507                    axis.normalized().or_refuse(KernelStage::Sew, "normalized")?
1508                } else {
1509                    Vec3::new(0.0, 0.0, 1.0)
1510                };
1511                os_debug!(
1512                    "apex-cap carrier for src face {} at ({:.3},{:.3},{:.3}) r={:.3}",
1513                    carriers[index].source_face_id,
1514                    apex.x,
1515                    apex.y,
1516                    apex.z,
1517                    distance.abs(),
1518                );
1519                apex_cap_sources.insert(index);
1520                apex_cap_sources.insert(carriers.len());
1521                apex_cap_pairs.push((index, carriers.len()));
1522                carriers.push(Carrier {
1523                    solid: crate::make_sphere_brep(apex, distance.abs(), axis).or_refuse(KernelStage::Sew, "make_sphere_brep")?,
1524                    source_face_id: carriers[index].source_face_id,
1525                    kind: OffsetFaceRole::Offset,
1526                });
1527            }
1528        }
1529    }
1530    // Lane O item 705: the ROUND carriers about tangent opening rims, emitted
1531    // as the apex caps are (an extra Offset carrier of the neighbour face) and
1532    // handled by the same exemptions and coincident-edge splits for now.
1533    if !tangent_rim_rounds.is_empty() {
1534        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1535        for (neighbour_id, opening_id, edge_id) in &tangent_rim_rounds {
1536            let Some(neighbour_index) = carriers.iter().position(|carrier| carrier.source_face_id == *neighbour_id && matches!(carrier.kind, OffsetFaceRole::Offset)) else {
1537                continue;
1538            };
1539            let Some(edge) = source.edges.iter().find(|edge| edge.id == *edge_id) else { continue };
1540            let Some(opening_face) = source_by_id_lookup(&source_faces, *opening_id) else { continue };
1541            match super::rim_round::circular_rim_round(edge, opening_face, distance, tolerance)? {
1542                Some(round) => {
1543                    os_debug!("tangent rim round: torus about edge {edge_id} (neighbour {neighbour_id}, opening {opening_id}) as carrier {}", carriers.len());
1544                    apex_cap_sources.insert(neighbour_index);
1545                    apex_cap_sources.insert(carriers.len());
1546                    apex_cap_pairs.push((neighbour_index, carriers.len()));
1547                    carriers.push(Carrier { solid: round, source_face_id: *neighbour_id, kind: OffsetFaceRole::Offset });
1548                }
1549                None => {
1550                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_tangent_rim_round", format!(
1551                        "offset_shell: the round about the tangent rim (edge {edge_id}) between source face {neighbour_id} and \
1552                         curved opening face {opening_id} is built only for a circular rim inside its own circle"
1553                    )));
1554                }
1555            }
1556        }
1557    }
1558    // A collapsed round's END on a planar opening: the tube about it
1559    // (`rim_round::planar_rim_tube`), riding the round's id as a synthetic
1560    // carrier the way an apex cap rides its cone's.
1561    if distance > 0.0 && super::rim_round::collapsed_rim_tube_enabled() {
1562        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1563        // A tube a previous pass read SHADOWED is omitted with its round, as
1564        // every shadowed support is: building it again would read shadowed
1565        // again and ask for the same re-run.
1566        // A SURVIVING round (`BREP_OFFSET_SURVIVING_RIM_TUBE`) takes its tube
1567        // too: its offset ends `distance` under the rim, and the quarter tube
1568        // runs from there to the mouth.
1569        let surviving = retained
1570            .iter()
1571            .filter(|id| super::rim_round::surviving_rim_tube_enabled() && !collapsed_supports.contains(id))
1572            .map(|id| (*id, true));
1573        let rounds = collapsed_supports.iter().map(|id| (*id, false)).chain(surviving).collect::<Vec<_>>();
1574        for (collapsed_id, survives) in rounds.iter().filter(|(id, _)| !shadowed_supports.contains(id)) {
1575            let Some(face) = source_by_id_lookup(&source_faces, *collapsed_id) else { continue };
1576            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1577                let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else { continue };
1578                // Planarity is read from the geometry in `planar_rim_tube`
1579                // (a plane may arrive degree-elevated or revolved).
1580                if !opening_set.contains(&mate.id)
1581                    || !uses_are_tangent(face, coedge, mate, mate_use)?
1582                {
1583                    continue;
1584                }
1585                let Some(edge) = source.edges.iter().find(|edge| edge.id == coedge.edge_id) else { continue };
1586                // A circle's tube ends ON the plane (its mouth an orphan rim);
1587                // a line's runs past it (cut by the wall like any skin).
1588                let (tube, on_plane) = match super::rim_round::planar_rim_tube(edge, mate, distance, tolerance, *survives)? {
1589                    Some(tube) => (Some(tube), true),
1590                    None if super::rim_round::surviving_rim_tube_enabled() => {
1591                        (super::rim_round::planar_line_rim_tube(edge, mate, distance, tolerance, *survives)?, false)
1592                    }
1593                    None => (None, false),
1594                };
1595                if let Some(tube) = tube {
1596                    os_debug!(
1597                        "rim tube: about edge {} (face {collapsed_id}, {}, opening {}) as carrier {}",
1598                        edge.id,
1599                        if *survives { "surviving" } else { "collapsed" },
1600                        mate.id,
1601                        carriers.len()
1602                    );
1603                    if on_plane {
1604                        rim_tubes.insert(carriers.len(), mate.id);
1605                    }
1606                    if *survives {
1607                        surviving_tubes.insert(carriers.len());
1608                    }
1609                    carriers.push(Carrier { solid: tube, source_face_id: *collapsed_id, kind: OffsetFaceRole::Offset });
1610                }
1611            }
1612        }
1613    }
1614    profile::lap(&mut clock, profile::APEX_CAPS);
1615    // A fold the carve's probe did not see (`outward_fold_the_carve_missed`):
1616    // a band too thin for its grid is built whole, and the torus wedge grown by
1617    // 1.001 then held the reflected lemon beyond its axis. Asked of every
1618    // retained face the carve neither carved nor omitted, on every outward
1619    // shell: a ruled wall is what first let the pipeline CLOSE such a shape,
1620    // but the geometry is the trigger. Refused by name, the tangent onset
1621    // included; a partial revolve of that kind is the revolved-wedge lane's
1622    // question, and that lane runs in front of this pipeline.
1623    if distance < 0.0 {
1624        for face_id in &retained {
1625            if carved_supports.contains_key(face_id)
1626                || !carriers.iter().any(|carrier| carrier.source_face_id == *face_id)
1627            {
1628                continue;
1629            }
1630            let face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1631            if let Some(fold) = profile::detail("outward_fold_the_carve_missed", || outward_fold_the_carve_missed(face, distance))? {
1632                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_outward_fold_band", format!(
1633                    "offset_shell: the outward offset of source face {face_id} folds where the carve \
1634                     saw no fold (area factor {:.3e} at u={:.6}, v={:.6}); a fold band that thin is \
1635                     not built",
1636                    fold.factor, fold.u, fold.v
1637                )));
1638            }
1639        }
1640    }
1641    profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1642    // Wall carriers built as a RULED opening face extended along itself, by
1643    // carrier index: the in-front guard reads their sides off the surface
1644    // normal where it would read a plane's.
1645    let mut ruled_walls = HashSet::default();
1646    // Inward walls at reflex rims need construction area beyond the source
1647    // opening too. Track them for source imprints and material-side selection.
1648    let mut inward_extended_walls = HashSet::default();
1649    let mut reflex_wall_neighbors = HashMap::default();
1650    // OUTWARD through a CURVED opening. A ruled one — the cone a revolved
1651    // straight profile edge sweeps, a cylinder — has its wall built as the
1652    // opening face held in place and EXTENDED along itself, exactly as a plane
1653    // is padded (`extended_ruled_wall`); the pad is the plane's, read off the
1654    // same convex junctions. Built first, so the planar walls know which
1655    // neighbours are ruled walls.
1656    //
1657    // Any other curved opening is refused by name. Its wall used to be the
1658    // unpadded source face, which never reaches the grown offset: on a torus
1659    // wedge whose chord revolves to a cone, the pair offset x cone cut 0
1660    // pieces, the cone's one fragment was dropped as a void cross-section, and
1661    // the result read "completion produced non-integral genus" with 12 open
1662    // edges. No outward shell in the kernel suites or the case corpus closed
1663    // through that wall (census, 2026-09-17).
1664    let mut ruled_built = HashMap::<u64, BrepSolid>::default();
1665    if distance < 0.0 {
1666        for face_id in opening_face_ids {
1667            let source_face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1668            if source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1669                continue;
1670            }
1671            if !ruled_opening(source_face)? {
1672                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening", format!(
1673                    "offset_shell: opening face {face_id} is curved and not a ruled surface; an \
1674                     outward wall is built only on a planar or ruled opening"
1675                )));
1676            }
1677            let pad = outward_wall_pad(
1678                source,
1679                source_face,
1680                &source_faces,
1681                &opening_set,
1682                distance.abs(),
1683            )?;
1684            let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1685            match extended_ruled_wall(source, source_face, pad, tolerance)? {
1686                Ok(wall) => {
1687                    os_debug!(
1688                        "wall for opening face {face_id}: ruled, pad {pad:.4}, sides reach {:.4?}",
1689                        wall.reached
1690                    );
1691                    ruled_built.insert(*face_id, wall.solid);
1692                }
1693                Err(reason) => {
1694                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_ruled_wall", format!(
1695                        "offset_shell: the outward wall of ruled opening face {face_id} cannot be \
1696                         built: {reason}"
1697                    )));
1698                }
1699            }
1700        }
1701    }
1702    let ruled_openings = ruled_built
1703        .keys()
1704        .filter_map(|id| source_by_id_lookup(&source_faces, *id))
1705        .collect::<Vec<_>>();
1706    for face_id in opening_face_ids {
1707        let source_face = source_faces
1708            .iter()
1709            .find(|face| face.id == *face_id)
1710            .unwrap();
1711        if let Some(wall) = ruled_built.remove(face_id) {
1712            ruled_walls.insert(carriers.len());
1713            carriers.push(Carrier {
1714                solid: wall,
1715                source_face_id: *face_id,
1716                kind: OffsetFaceRole::Wall,
1717            });
1718            continue;
1719        }
1720        if distance > 0.0
1721            && source_face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1722        {
1723            if let Some((pad, neighbors)) =
1724                inward_wall_pad(source, source_face, &source_faces, &opening_set, distance)?
1725            {
1726                // Scaling a notched/free-form outline can still clip the new
1727                // rim. Use the whole plane rectangle; source and offset
1728                // imprints below recover both exact boundaries of the wall.
1729                let padded = carrier_solid(source, *face_id, 0.0, pad)?;
1730                let wall = full_rectangle_face(&padded, &padded.shells[0].faces[0])?;
1731                inward_extended_walls.insert(carriers.len());
1732                reflex_wall_neighbors.insert(carriers.len(), neighbors);
1733                carriers.push(Carrier {
1734                    solid: wall,
1735                    source_face_id: *face_id,
1736                    kind: OffsetFaceRole::Wall,
1737                });
1738                continue;
1739            }
1740        }
1741        carriers.push(Carrier {
1742            solid: if distance < 0.0 && source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1743                let pad = outward_wall_pad(
1744                    source,
1745                    source_face,
1746                    &source_faces,
1747                    &opening_set,
1748                    distance.abs(),
1749                )?;
1750                // A plane meeting a RULED opening is padded past the grown
1751                // outline, not onto it. Padded by exactly the pad, its trim's
1752                // arc lands ON the grown offset's section wherever the join is
1753                // perpendicular, and the ruled wall's section then ENDS on that
1754                // coincident pair: on the torus wedge the cap shredded into 60
1755                // slivers along the grown circle. The clearance is counted in
1756                // the band that decides whether the strip beyond the grown
1757                // outline is wall or void, so the strip always resolves as its
1758                // own fragment and is dropped as void.
1759                let uniform_pad = pad;
1760                let pad = if ruled_openings
1761                    .iter()
1762                    .any(|ruled| source_faces_adjacent(source_face, ruled))
1763                {
1764                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS
1765                        * offset_skin_band(crate::solid_scale(source), distance)
1766                } else if outline_has_free_element(source, source_face)? {
1767                    // A free-form outline's wall is a FIT: without the same
1768                    // clearance its outline sits within the fit tolerance of
1769                    // the carriers' own sections on the plane, and the
1770                    // near-coincident curves shred the wall's imprint (26 to
1771                    // 121 fragments on the free-form D band, 2026-09-26). With
1772                    // it, the surplus ring is cut away cleanly.
1773                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance)
1774                } else {
1775                    pad
1776                };
1777                os_debug!("wall for opening face {face_id}: outward pad {pad:.4}");
1778                // The wall is the opening's outline OFFSET by the pad in its
1779                // own plane (`outline_offset.rs`). The pad used to SCALE that
1780                // outline about the patch centre, which is the offset only for
1781                // a rectangle filling its patch or a circle centred on it: an
1782                // L-shaped opening's notch edges pass through the centre and
1783                // did not move at all, so the notch faces' grown offsets
1784                // crossed the plane outside the wall ("non-integral genus",
1785                // `l-step-open-bottom` at d = −1.5 in the membrane census).
1786                //
1787                // An outline this module does not offset keeps the scaled wall,
1788                // but only when that wall still COVERS the offset outline along
1789                // every edge a retained face meets — which is what the sections
1790                // have to land inside. Otherwise the shell refuses by name
1791                // rather than assembling an open rim.
1792                let mut scaled = carrier_solid(source, *face_id, 0.0, pad)?;
1793                drop_wall_interior_loops(&mut scaled)?;
1794                // Each outline edge padded for its own neighbour, plus the same
1795                // clearance the uniform pad carries (`outward_wall_pads_per_edge`).
1796                let per_edge = if per_edge_opening_pads_on() {
1797                    Some(outward_wall_pads_per_edge(source, source_face, &source_faces, &opening_set, distance.abs())?)
1798                } else {
1799                    None
1800                };
1801                // Where the pads differ, every edge also takes the clearance a
1802                // ruled or free-form neighbour's wall takes: an edge padded by
1803                // exactly d beside one padded more lands its wall boundary ON
1804                // the neighbour's offset section, and the imprint drops it as
1805                // boundary (non-integral genus at the corner they share).
1806                let clearance = match &per_edge {
1807                    Some(pads) if pads.values().any(|value| (value - uniform_pad).abs() > 1e-12 * uniform_pad.max(1.0)) => {
1808                        (pad - uniform_pad).max(
1809                            RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance),
1810                        )
1811                    }
1812                    _ => pad - uniform_pad,
1813                };
1814                // An outline the per-edge offset declines (a tangent junction
1815                // between edges padded differently) takes the uniform pad.
1816                let outline_wall = || match &per_edge {
1817                    Some(pads) => match offset_outline_wall_per_edge(source, source_face, &|edge_id| {
1818                        pads.get(&edge_id).copied().unwrap_or(uniform_pad) + clearance
1819                    })? {
1820                        Ok(wall) => Ok(Ok(wall)),
1821                        Err(reason) => {
1822                            os_debug!("per-edge outline of opening face {face_id} declined ({reason}); uniform pad");
1823                            offset_outline_wall(source, source_face, pad)
1824                        }
1825                    },
1826                    None => offset_outline_wall(source, source_face, pad),
1827                };
1828                let mut wall = match profile::detail("offset_outline_wall", outline_wall)? {
1829                    Ok(outline) => {
1830                        // Where the scaled wall already trims the offset
1831                        // outline's own region — a rectangle filling its patch,
1832                        // a circle centred on it — it is kept, so no shell that
1833                        // was right before is rebuilt on a different patch.
1834                        let same = profile::detail("walls_trim_the_same_region", || walls_trim_the_same_region(
1835                            &outline,
1836                            &scaled,
1837                            1e-9f64.max(crate::solid_scale(source) * 1e-11),
1838                        ))?;
1839                        if same {
1840                            os_debug!("wall for opening face {face_id}: scaled, which IS its outline offset");
1841                            scaled
1842                        } else {
1843                            os_debug!("wall for opening face {face_id}: outline offset by {pad:.4}");
1844                            outline
1845                        }
1846                    }
1847                    Err(reason) => {
1848                        let carrier_surfaces = carriers
1849                            .iter()
1850                            .filter(|carrier| matches!(carrier.kind, OffsetFaceRole::Offset))
1851                            .map(|carrier| (carrier.source_face_id, &carrier.solid.shells[0].faces[0].surface))
1852                            .collect::<Vec<_>>();
1853                        if let Err(uncovered) = scaled_wall_covers_offset(
1854                            source,
1855                            source_face,
1856                            &scaled,
1857                            pad,
1858                            &source_faces,
1859                            &opening_set,
1860                            &carrier_surfaces,
1861                        )? {
1862                            return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_opening_wall_coverage", format!(
1863                                "offset_shell: opening face {face_id}'s outline is not offset \
1864                                 ({reason}), and its scaled outward wall does not contain every \
1865                                 retained neighbour's grown offset section (a point of one lies \
1866                                 {uncovered:.3e} outside)"
1867                            )));
1868                        }
1869                        os_debug!(
1870                            "wall for opening face {face_id}: scaled, which covers its offset ({reason})"
1871                        );
1872                        scaled
1873                    }
1874                };
1875                // The pad extends the wall by STRETCHING the plane's 2x2 net
1876                // while the trim pcurves are cloned in UV, so every loop
1877                // scales about the patch centre by (w+2|d|)/w. For the OUTER
1878                // loop of a full-domain rectangle that lands exactly on the
1879                // grown outline — the intended wall extent. But an INTERIOR
1880                // loop (a carve outline: a bore, gouge or crater rim in the
1881                // opening face) is scaled OUTWARD too, and the enlarged hole
1882                // then swallows both circles the wall must be cut by (the
1883                // source carve rim from the wall x source imprint and the
1884                // shrunk rim from the wall x offset-carrier imprint) — the
1885                // imprints clip to nothing and the rims dangle one-use. Drop
1886                // interior loops instead: the wall covers the carve mouth,
1887                // the imprints cut the true rims, and selection (void-wall
1888                // guard + on-skin filter) drops the fragments over the void.
1889                drop_wall_interior_loops(&mut wall)?;
1890                wall
1891            } else {
1892                standalone_face(source, *face_id)?
1893            },
1894            source_face_id: *face_id,
1895            kind: OffsetFaceRole::Wall,
1896        });
1897    }
1898    if carriers.len() >= SOURCE_OPERAND as usize {
1899        return Err(KernelRefusal::unsupported(KernelStage::Collect, "offset_shell_carrier_count", "offset_shell: too many carrier faces for current ABI"));
1900    }
1901    profile::lap(&mut clock, profile::WALLS);
1902    // The characteristic length every tolerance below is derived from.  This
1903    // was `max ‖vertex‖` — the distance from the WORLD ORIGIN — until audit
1904    // slice 0: that form made every band widen as the part was moved away from
1905    // the origin while ignoring the part's actual size, so the same shell
1906    // solved to different tolerances depending only on where it was modelled.
1907    // `solid_scale` is the bbox diagonal, floored at 1.0 exactly as the old
1908    // fold was, so this changes ONE thing: placement-dependence.
1909    let scale = crate::solid_scale(source);
1910    crate::report_scale_migration("offset_shell", scale, || {
1911        source
1912            .vertices
1913            .iter()
1914            .map(|vertex| vertex.point.length())
1915            .fold(1.0, f64::max)
1916    });
1917    let smooth = synchronize_smooth_offset_boundaries(&mut carriers, &source_faces, scale)?;
1918    // Reflex-rim rebuilds run on BOTH attempts: the fallback for a broken
1919    // extension is an honest refusal, but the fallback for a skipped reflex
1920    // rebuild is a silently WRONG (membrane-capped) shell.
1921    let reflex_rebuilt = rebuild_reflex_rim_carriers(
1922        &mut carriers,
1923        source,
1924        &source_faces,
1925        &smooth.pairs,
1926        scale,
1927        distance,
1928    )?;
1929    *reflex_rebuilds = reflex_rebuilt.len();
1930    if extend_oblique_carriers {
1931        let oblique_extended = extend_offset_carriers_past_open_hole_rims(
1932            &mut carriers,
1933            source,
1934            &source_faces,
1935            &opening_set,
1936            &smooth.pairs,
1937            scale,
1938        )?;
1939        let mut already_extended = oblique_extended.clone();
1940        already_extended.extend(reflex_rebuilt.iter().copied());
1941        let fallshort_extended = extend_fallshort_curved_carriers(
1942            &mut carriers,
1943            source,
1944            &source_faces,
1945            &opening_set,
1946            &smooth.pairs,
1947            &already_extended,
1948            scale,
1949            distance,
1950        )?;
1951        *extension_fired = !oblique_extended.is_empty() || fallshort_extended > 0;
1952        os_debug!(
1953            "extended {} oblique + {fallshort_extended} fall-short carriers past their opening planes",
1954            oblique_extended.len(),
1955        );
1956    }
1957    profile::lap(&mut clock, profile::EXTENSION);
1958    let tolerance = 1e-7f64.max(scale * 1e-9);
1959    let pair_tolerance = (scale * 1e-8).max(2e-6);
1960    let reach = distance.abs() * 4.0 + pair_tolerance;
1961    // Only after the cascade has omitted a shadowed carrier: until then that
1962    // carrier still cuts both coplanar copies at the same points. A shell only:
1963    // under `offset_solid` (the dumbbell's run-on body shrunk with rounded
1964    // joins) it turned a refusal into a two-shell body 2.16 off its form.
1965    if abut_coplanar_carriers_on() && body == Body::Shell && !shadowed_supports.is_empty() {
1966        let abutted = abut_coplanar_offset_carriers(&mut carriers, tolerance.max(scale * 1e-9))?;
1967        if abutted > 0 {
1968            os_debug!("abutted {abutted} pair(s) of overlapping coplanar offset carriers");
1969        }
1970    }
1971    let carrier_samples = carriers
1972        .iter()
1973        .map(|carrier| carrier_extent_points(&carrier.solid))
1974        .collect::<Result<Vec<_>, _>>()?;
1975    let carrier_bounds = carrier_samples
1976        .iter()
1977        .map(|samples| Bounds::from_nonempty_points(samples))
1978        .collect::<Option<Vec<_>>>()
1979        .ok_or_else(|| "offset_shell: carrier has no boundary samples".to_string()).or_refuse(KernelStage::Sew, "offset_shell_carrier_has_no_boundary_samples")?;
1980    let source_by_id = source_faces
1981        .iter()
1982        .map(|face| (face.id, *face))
1983        .collect::<HashMap<_, _>>();
1984    let source_samples = source_faces
1985        .iter()
1986        .map(|face| {
1987            let standalone = standalone_face(source, face.id)?;
1988            Ok((face.id, edge_sample_points(&standalone)?))
1989        })
1990        .collect::<Result<HashMap<_, _>, KernelRefusal>>()?;
1991    if debug_enabled() {
1992        for (index, carrier) in carriers.iter().enumerate() {
1993            let face = &carrier.solid.shells[0].faces[0];
1994            let samples = &carrier_samples[index];
1995            let bounds =
1996                samples
1997                    .iter()
1998                    .fold((Vec3::default(), Vec3::default()), |(low, high), point| {
1999                        (
2000                            Vec3 {
2001                                x: low.x.min(point.x),
2002                                y: low.y.min(point.y),
2003                                z: low.z.min(point.z),
2004                            },
2005                            Vec3 {
2006                                x: high.x.max(point.x),
2007                                y: high.y.max(point.y),
2008                                z: high.z.max(point.z),
2009                            },
2010                        )
2011                    });
2012            let surface = &face.surface;
2013            let rational = surface
2014                .control_points
2015                .iter()
2016                .flatten()
2017                .any(|point| (point.w - 1.0).abs() > 1e-12);
2018            os_debug!(
2019                "carrier[{index}] kind={:?} source_face={} loops={} deg=({},{}) net={}x{} rational={rational} bounds=({:.3},{:.3},{:.3})..({:.3},{:.3},{:.3})",
2020                carrier.kind, carrier.source_face_id, face.loops.len(),
2021                surface.degree_u, surface.degree_v,
2022                surface.control_points.len(),
2023                surface.control_points.first().map(|row| row.len()).unwrap_or(0),
2024                bounds.0.x, bounds.0.y, bounds.0.z, bounds.1.x, bounds.1.y, bounds.1.z,
2025            );
2026        }
2027        for (index, carrier) in carriers.iter().enumerate() {
2028            if !matches!(carrier.kind, OffsetFaceRole::Offset) {
2029                continue;
2030            }
2031            let source_face = source_by_id[&carrier.source_face_id];
2032            let carrier_surface = &carrier.solid.shells[0].faces[0].surface;
2033            let (ku, kv) = (
2034                crate::KnotVector::new(
2035                    source_face.surface.knots_u.clone(),
2036                    source_face.surface.degree_u,
2037                ),
2038                crate::KnotVector::new(
2039                    source_face.surface.knots_v.clone(),
2040                    source_face.surface.degree_v,
2041                ),
2042            );
2043            if let (Ok(ku), Ok(kv)) = (ku, kv) {
2044                let [u0, u1] = ku.domain();
2045                let [v0, v1] = kv.domain();
2046                let mut worst = 0.0f64;
2047                let mut worst_at = (0.0f64, 0.0f64);
2048                for iu in 0..=24 {
2049                    for iv in 0..=24 {
2050                        let u = u0 + (u1 - u0) * iu as f64 / 24.0;
2051                        let v = v0 + (v1 - v0) * iv as f64 / 24.0;
2052                        let expected = face_offsets(source_face)
2053                            .at(u, v, -distance)
2054                            .map(|sample| sample.point);
2055                        let actual = carrier_surface.evaluate(u, v);
2056                        if let (Ok(expected), Ok(actual)) = (expected, actual) {
2057                            let error = expected.sub(actual).length();
2058                            if error > worst {
2059                                worst = error;
2060                                worst_at = (u, v);
2061                            }
2062                        }
2063                    }
2064                }
2065                let mut normal_swing = 0.0f64;
2066                let mut previous: Option<Vec3> = None;
2067                for iu in 0..=48 {
2068                    let u = u0 + (u1 - u0) * iu as f64 / 48.0;
2069                    let v = (v0 + v1) / 2.0;
2070                    if let Ok(normal) = face_normal(source_face, u, v) {
2071                        if let Some(previous) = previous {
2072                            normal_swing = normal_swing.max(previous.sub(normal).length());
2073                        }
2074                        previous = Some(normal);
2075                    }
2076                }
2077                let weights = source_face
2078                    .surface
2079                    .control_points
2080                    .iter()
2081                    .flatten()
2082                    .map(|point| point.w)
2083                    .fold((f64::MAX, f64::MIN), |(low, high), w| {
2084                        (low.min(w), high.max(w))
2085                    });
2086                os_debug!(
2087                    "carrier[{index}] offset fit error max={worst:.6} at=({:.4},{:.4}) domain_u=({u0:.4},{u1:.4}) normal_step_max={normal_swing:.4} src_net={}x{} src_deg=({},{}) src_w=({:.4},{:.4}) knots_u={:?}",
2088                    worst_at.0, worst_at.1,
2089                    source_face.surface.control_points.len(),
2090                    source_face.surface.control_points.first().map(|row| row.len()).unwrap_or(0),
2091                    source_face.surface.degree_u, source_face.surface.degree_v,
2092                    weights.0, weights.1,
2093                    &source_face.surface.knots_u,
2094                );
2095            }
2096        }
2097        os_debug!("smooth pairs: {:?}", smooth.pairs);
2098    }
2099    let mut imprint = empty_imprint();
2100    let mut next_piece_id = 1;
2101    let mut next_vertex_id = 1;
2102    // Lane P3b row 2 (2026-10-26): where the IMPRINT phase spends its time
2103    // outside `build_imprints`, one `offset_shell.imprint_split` line under
2104    // BREP_PROFILE: the carrier-pair builds and merges, the wall x source
2105    // builds, their standalone face copies and merges, the apex ring splits,
2106    // the smooth-split sync and the boundary-coincidence filter.
2107    let split_profile = crate::imprint::profile_enabled();
2108    let mut split_ms = [0.0f64; 9];
2109    let mut split_clock = split_profile.then(web_time::Instant::now);
2110    let mut split_lap = |slot: usize, clock: &mut Option<web_time::Instant>| {
2111        if let Some(started) = clock {
2112            let now = web_time::Instant::now();
2113            split_ms[slot] += (now - *started).as_secs_f64() * 1e3;
2114            *started = now;
2115        }
2116    };
2117    // The pair skip rules, one closure for both imprint paths below (the
2118    // per-pair calls and row 6's one-call composite).
2119    // TANGENT RIM CUTS, planned before the imprint (`tangent_rim_cuts.rs`).
2120    let tangent_rim_cuts = if super::tangent_rim_cuts::tangent_rim_cuts_enabled() {
2121        super::tangent_rim_cuts::plan_tangent_rim_cuts(&carriers, &source_faces, &smooth.pairs, tolerance, scale)?
2122    } else {
2123        Vec::new()
2124    };
2125    let pair_admitted = |first: usize, second: usize| -> bool {
2126            let first_source = source_by_id[&carriers[first].source_face_id];
2127            let second_source = source_by_id[&carriers[second].source_face_id];
2128            if matches!(carriers[first].kind, OffsetFaceRole::Wall)
2129                && matches!(carriers[second].kind, OffsetFaceRole::Wall)
2130            {
2131                // Unextended inward walls are the opening faces themselves:
2132                // they never overlap; adjacent ones only touch along their
2133                // shared edge, so there is nothing to imprint. OUTWARD walls
2134                // are the opening planes EXTENDED by |distance|: the walls of
2135                // two ADJACENT openings cross along the line of their shared
2136                // source edge, and each wall ring must stop there (the sheet
2137                // past that line lies in front of the other opening). Without
2138                // the cut the wall × source chain below stays open on the
2139                // shared-edge side (its neighbour there is an opening, not a
2140                // retained face), the wall never fragments into its ring, and
2141                // every source rim along both openings dangles one-use.
2142                // Extended inward walls need those mutual cuts as well.
2143                if (distance > 0.0
2144                    && !inward_extended_walls.contains(&first)
2145                    && !inward_extended_walls.contains(&second))
2146                    || !source_faces_adjacent(first_source, second_source)
2147                {
2148                    return false;
2149                }
2150            }
2151            if smooth.pairs.contains(&(first, second)) {
2152                os_debug!("pair ({first},{second}) skipped: smooth");
2153                return false;
2154            }
2155            if !carrier_bounds[first].intersects_upper(carrier_bounds[second], pair_tolerance) {
2156                os_debug!("pair ({first},{second}) skipped: bounds");
2157                return false;
2158            }
2159            if !source_faces_adjacent(first_source, second_source)
2160                && sample_separation(
2161                    &source_samples[&first_source.id],
2162                    &source_samples[&second_source.id],
2163                ) > reach
2164            {
2165                os_debug!("pair ({first},{second}) skipped: separation");
2166                return false;
2167            }
2168            true
2169    };
2170    // The wall x source pairs: an extended opening wall (outward, or inward
2171    // at a reflex rim) against each retained source face adjacent to its
2172    // opening (see the note at the per-pair loop below).
2173    let mut wall_source_pairs: Vec<(usize, u64)> = Vec::new();
2174    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
2175        for index in 0..carriers.len() {
2176            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
2177                continue;
2178            }
2179            if distance > 0.0 && !inward_extended_walls.contains(&index) {
2180                continue;
2181            }
2182            let opening = source_by_id[&carriers[index].source_face_id];
2183            for retained_id in &retained {
2184                if source_faces_adjacent(opening, source_by_id[retained_id]) {
2185                    wall_source_pairs.push((index, *retained_id));
2186                }
2187            }
2188        }
2189    }
2190    let one_call = one_call_imprint_enabled();
2191    let mut one_call_done = false;
2192    if one_call {
2193        // ONE-CALL IMPRINT (`BREP_OFFSET_ONE_CALL_IMPRINT`, lane P3b row 6):
2194        // every carrier and every retained source face a wall is cut against
2195        // go into one open sheet solid (ids renumbered per member), one
2196        // `build_imprints` processes exactly the admitted pairs, and its
2197        // post-passes run once over the whole piece set. The record comes
2198        // back in the shell's operand space. A failure of the single call
2199        // falls back to the per-pair path below, which tolerates a failed
2200        // pair on its own.
2201        let mut members: Vec<(u8, &BrepSolid)> = carriers.iter().enumerate().map(|(index, carrier)| (index as u8, &carrier.solid)).collect();
2202        let mut source_members: Vec<(u64, BrepSolid)> = Vec::new();
2203        for (_, retained_id) in &wall_source_pairs {
2204            if !source_members.iter().any(|(id, _)| id == retained_id) {
2205                source_members.push((*retained_id, standalone_face(source, *retained_id)?));
2206            }
2207        }
2208        for (_, solid) in &source_members {
2209            members.push((SOURCE_OPERAND, solid));
2210        }
2211        let composite = compose_imprint_operands(&members);
2212        let mut admitted: HashSet<(usize, usize)> = HashSet::default();
2213        for first in 0..carriers.len() {
2214            for second in first + 1..carriers.len() {
2215                if pair_admitted(first, second) {
2216                    admitted.insert((composite.face_index[first], composite.face_index[second]));
2217                }
2218            }
2219        }
2220        for (index, retained_id) in &wall_source_pairs {
2221            let member = carriers.len() + source_members.iter().position(|(id, _)| id == retained_id).unwrap();
2222            let (a, b) = (composite.face_index[*index], composite.face_index[member]);
2223            admitted.insert((a.min(b), a.max(b)));
2224        }
2225        split_lap(0, &mut split_clock);
2226        match crate::imprint::build_carrier_imprints_within(
2227            &composite.solid,
2228            &|first, second| admitted.contains(&(first, second)),
2229            &ImprintOptions {
2230                tolerance,
2231                maximum_fit_points: 96,
2232                local_fit: false,
2233                fit_chunk_points: None,
2234                maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2235                span_budget: None,
2236                hermite_sections: false,
2237                tangent_curve_lane: false,
2238                exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2239                march_starts: false,
2240                two_radius_junctions: false,
2241                tangent_curve_imprint: false,
2242            },
2243            !shielded_cusps.is_empty(),
2244        ) {
2245            Ok(record) => {
2246                split_lap(1, &mut split_clock);
2247                imprint = translate_composite_imprint(record, &composite, tolerance, scale)?;
2248                next_piece_id = imprint.pieces.iter().map(|piece| piece.id).max().unwrap_or(0) + 1;
2249                next_vertex_id = imprint.vertices.iter().map(|vertex| vertex.id).max().unwrap_or(0) + 1;
2250                one_call_done = true;
2251                ONE_CALL_RUNS.with(|count| count.set(count.get() + 1));
2252                split_lap(2, &mut split_clock);
2253                os_debug!(
2254                    "one-call imprint: {} members, {} admitted pairs, {} pieces",
2255                    members.len(),
2256                    admitted.len(),
2257                    imprint.pieces.len(),
2258                );
2259            }
2260            Err(error) => {
2261                os_debug!("one-call imprint failed, per-pair path: {error}");
2262            }
2263        }
2264    }
2265    for first in 0..carriers.len() {
2266        for second in first + 1..carriers.len() {
2267            if one_call_done {
2268                break;
2269            }
2270            if !pair_admitted(first, second) {
2271                continue;
2272            }
2273            split_lap(0, &mut split_clock);
2274            let pair = match crate::imprint::build_carrier_imprints(
2275                &carriers[first].solid,
2276                &carriers[second].solid,
2277                &ImprintOptions {
2278                    tolerance,
2279                    maximum_fit_points: 96,
2280                    // The GLOBAL interpolation lane. `local_fit: true` until
2281                    // 2026-09-13, which cost three orders on every smooth
2282                    // section: measured on the apex cone's base circle, the
2283                    // local lane needs 3,070 control points to reach 2.0e-5
2284                    // where the global one reaches 1.4e-8 with 384. What the
2285                    // local lane is for — a rim through a corner, where its
2286                    // monotonicity limiter holds a kink the global cubic rings
2287                    // across, 4.9x measured — is now the fit's own fallback:
2288                    // `fit_polyline` re-runs the other lane whenever the asked
2289                    // one cannot meet the tolerance and returns the better
2290                    // MEASURED curve, so this flag chooses which ladder is
2291                    // paid for first, never which curve is delivered.
2292                    local_fit: false,
2293                    fit_chunk_points: None,
2294                    // Offset carriers can meet in short, tightly curved
2295                    // branches. The general SSI default (diagonal / 15) is
2296                    // too coarse here and lets independently fitted branches
2297                    // miss a shared junction when thickness crosses one of
2298                    // those branches.
2299                    maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2300                    span_budget: None,
2301                    hermite_sections: false,
2302                    tangent_curve_lane: false,
2303                    exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2304                    march_starts: false,
2305                    two_radius_junctions: false,
2306                    tangent_curve_imprint: false,
2307                },
2308                !shielded_cusps.is_empty(),
2309            ) {
2310                Ok(pair) => pair,
2311                // A failed pair imprint (e.g. the marching SSI exhausting its
2312                // step budget on a long closed sphere/plane intersection) is
2313                // not fatal to the shell: the affected rim simply stays
2314                // unsplit and the rim-weld passes below get to close it. The
2315                // final watertightness gate still refuses anything the welds
2316                // cannot reach, so tolerating the miss only enlarges the
2317                // honest success set.
2318                Err(error) => {
2319                    os_debug!("pair ({first},{second}) imprint failed: {error}");
2320                    continue;
2321                }
2322            };
2323            split_lap(1, &mut split_clock);
2324            let pieces_before = imprint.pieces.len();
2325            merge_pair_imprint(
2326                &mut imprint,
2327                pair,
2328                first as u8,
2329                second as u8,
2330                &mut next_piece_id,
2331                &mut next_vertex_id,
2332                tolerance,
2333                scale,
2334            );
2335            split_lap(2, &mut split_clock);
2336            os_debug!(
2337                "pair ({first},{second}) src=({},{}) pieces+={}",
2338                carriers[first].source_face_id,
2339                carriers[second].source_face_id,
2340                imprint.pieces.len() - pieces_before,
2341            );
2342        }
2343    }
2344    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
2345        // An extended opening-wall carrier (outward, or inward at a reflex
2346        // rim) no longer carries the source outline. OUTWARD it has the GROWN
2347        // outline. Its inner boundary — where the wall ring stops at the
2348        // source solid — is the source outline, and the retained SOURCE faces
2349        // are not carriers, so no carrier×carrier pair ever imprints it.
2350        // Un-cut, the wall stays one whole-plane fragment covering the
2351        // opening void, and the source faces' rim edges dangle one-use.
2352        // Imprint each wall carrier against the retained source faces that
2353        // share an edge with its opening: the wall then fragments into the
2354        // ring (kept) and the opening hole (dropped by the void guard).
2355        for index in 0..carriers.len() {
2356            if one_call_done {
2357                break;
2358            }
2359            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
2360                continue;
2361            }
2362            if distance > 0.0 && !inward_extended_walls.contains(&index) {
2363                continue;
2364            }
2365            let opening = source_by_id[&carriers[index].source_face_id];
2366            for retained_id in &retained {
2367                let retained_face = source_by_id[retained_id];
2368                if !source_faces_adjacent(opening, retained_face) {
2369                    continue;
2370                }
2371                split_lap(0, &mut split_clock);
2372                let neighbor = standalone_face(source, *retained_id)?;
2373                split_lap(3, &mut split_clock);
2374                let pair = match build_imprints(
2375                    &carriers[index].solid,
2376                    &neighbor,
2377                    &ImprintOptions {
2378                        tolerance,
2379                        maximum_fit_points: 96,
2380                        // The global lane, as above.
2381                        local_fit: false,
2382                        fit_chunk_points: None,
2383                        maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2384                        span_budget: None,
2385                        hermite_sections: false,
2386                        tangent_curve_lane: false,
2387                        exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2388                        march_starts: false,
2389                        two_radius_junctions: false,
2390                        tangent_curve_imprint: false,
2391                    },
2392                ) {
2393                    Ok(pair) => pair,
2394                    Err(error) => {
2395                        os_debug!(
2396                            "wall×source pair ({index},{retained_id}) imprint failed: {error}"
2397                        );
2398                        continue;
2399                    }
2400                };
2401                split_lap(4, &mut split_clock);
2402                let pieces_before = imprint.pieces.len();
2403                merge_pair_imprint(
2404                    &mut imprint,
2405                    pair,
2406                    index as u8,
2407                    SOURCE_OPERAND,
2408                    &mut next_piece_id,
2409                    &mut next_vertex_id,
2410                    tolerance,
2411                    scale,
2412                );
2413                split_lap(5, &mut split_clock);
2414                os_debug!(
2415                    "wall×source pair ({index},{retained_id}) pieces+={}",
2416                    imprint.pieces.len() - pieces_before,
2417                );
2418            }
2419        }
2420    }
2421    // APEX-CAP ring splits: the cap × cone section lies ON the cone
2422    // carrier's promoted ring edge (an overlap, not a crossing), so
2423    // `build_imprints` mints no edge splits for the cone side. Without them
2424    // the cone keeps ONE closed ring edge while the cap carries the section
2425    // as arcs — mismatched segmentation, both sides one-use. Record the arc
2426    // junctions as splits on the cone's coincident edge.
2427    for (cone_index, cap_index) in &apex_cap_pairs {
2428        let cap_face_id = carriers[*cap_index].solid.shells[0].faces[0].id;
2429        let piece_ids = imprint
2430            .by_face
2431            .iter()
2432            .find(|entry| entry.operand == *cap_index as u8 && entry.face_id == cap_face_id)
2433            .map(|entry| entry.piece_ids.clone())
2434            .unwrap_or_default();
2435        let coincidence_band = 2e-5f64.max(scale * 1e-7);
2436        for piece_id in piece_ids {
2437            let Some((curve, t0, t1)) = imprint
2438                .pieces
2439                .iter()
2440                .find(|piece| piece.id == piece_id)
2441                .map(|piece| (piece.curve.clone(), piece.t0, piece.t1))
2442            else {
2443                continue;
2444            };
2445            for endpoint in [curve.evaluate(t0).or_refuse(KernelStage::Sew, "evaluate")?, curve.evaluate(t1).or_refuse(KernelStage::Sew, "evaluate")?] {
2446                for edge in &carriers[*cone_index].solid.edges {
2447                    if edge.degenerate {
2448                        continue;
2449                    }
2450                    let projection = crate::project_point_to_curve(&edge.curve, endpoint).or_refuse(KernelStage::Sew, "project_point_to_curve")?;
2451                    if projection.distance > coincidence_band
2452                        || projection.u < edge.t0 + 1e-9
2453                        || projection.u > edge.t1 - 1e-9
2454                    {
2455                        continue;
2456                    }
2457                    let parameter = projection.u;
2458                    if let Some(existing) = imprint.edge_splits.iter_mut().find(|split| {
2459                        split.operand == *cone_index as u8 && split.edge_id == edge.id
2460                    }) {
2461                        if !existing
2462                            .parameters
2463                            .iter()
2464                            .any(|value| (*value - parameter).abs() <= 1e-8)
2465                        {
2466                            existing.parameters.push(parameter);
2467                        }
2468                    } else {
2469                        imprint.edge_splits.push(EdgeSplitRecord {
2470                            operand: *cone_index as u8,
2471                            edge_id: edge.id,
2472                            parameters: vec![parameter],
2473                        });
2474                    }
2475                    os_debug!(
2476                        "apex-cap ring split: cone carrier {cone_index} edge {} at t={parameter:.6}",
2477                        edge.id,
2478                    );
2479                }
2480            }
2481        }
2482    }
2483    if debug_enabled() {
2484        for piece in &imprint.pieces {
2485            let start = piece.curve.evaluate(piece.t0);
2486            let mid = piece.curve.evaluate((piece.t0 + piece.t1) * 0.5);
2487            let end = piece.curve.evaluate(piece.t1);
2488            if let (Ok(start), Ok(mid), Ok(end)) = (start, mid, end) {
2489                os_debug!(
2490                    "piece[{}] ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4}) on {:?}",
2491                    piece.id,
2492                    start.x,
2493                    start.y,
2494                    start.z,
2495                    mid.x,
2496                    mid.y,
2497                    mid.z,
2498                    end.x,
2499                    end.y,
2500                    end.z,
2501                    piece.support_faces,
2502                );
2503                for pcurve in &piece.pcurves {
2504                    let uv = |t: f64| pcurve.pcurve.evaluate(t).map(|p| (p.x, p.y)).unwrap_or((f64::NAN, f64::NAN));
2505                    let [a, b] = pcurve.pcurve.domain().unwrap_or([0.0, 1.0]);
2506                    os_debug!(
2507                        "  pcurve operand={} face={} uv {:?}..{:?}..{:?}",
2508                        pcurve.operand, pcurve.face_id, uv(a), uv(0.5 * (a + b)), uv(b),
2509                    );
2510                }
2511            }
2512        }
2513    }
2514    os_debug!("tangent rim cuts imprinted: {}", tangent_rim_cuts.len());
2515    super::tangent_rim_cuts::drop_marched_rim_noise(&mut imprint, &tangent_rim_cuts, distance)?;
2516    let rim_cut_pieces = super::tangent_rim_cuts::imprint_tangent_rim_cuts(
2517        &mut imprint,
2518        &carriers,
2519        tangent_rim_cuts,
2520        &mut next_piece_id,
2521        &mut next_vertex_id,
2522        distance,
2523        tolerance,
2524        scale,
2525    )?;
2526    split_lap(6, &mut split_clock);
2527    synchronize_smooth_edge_splits(&mut imprint, &smooth.edge_pairs);
2528    split_lap(7, &mut split_clock);
2529    // This decides whether an imprint is genuinely the carrier's existing
2530    // trim, not whether independently fitted curves can later be sewn. The
2531    // looser assembly tolerance can erase a short separating branch while it
2532    // is still departing a boundary.
2533    let boundary_coincidence_tolerance = 2e-5f64.max(scale * 1e-7);
2534    let piece_geometry = imprint
2535        .pieces
2536        .iter()
2537        .map(|piece| {
2538            (
2539                piece.id,
2540                FragmentEdgeGeometry {
2541                    curve: piece.curve.clone(),
2542                    t0: piece.t0,
2543                    t1: piece.t1,
2544                },
2545            )
2546        })
2547        .collect::<HashMap<_, _>>();
2548    // A rim tube ends ON its opening's plane: its mouth reaches that
2549    // opening's wall as an orphan rim, welded into the cap like any skin's.
2550    // That wall's own copy of the section would cut the mouth a second time;
2551    // a section with any OTHER wall (a second opening the tube crosses) is a
2552    // true trim and stays.
2553    if !rim_tubes.is_empty() {
2554        for entry in imprint.by_face.iter_mut() {
2555            let Some(wall) = carriers.get(entry.operand as usize) else { continue };
2556            if !matches!(wall.kind, OffsetFaceRole::Wall) {
2557                continue;
2558            }
2559            let wall_opening = wall.source_face_id;
2560            entry.piece_ids.retain(|piece_id| {
2561                !imprint.pieces.iter().any(|piece| {
2562                    piece.id == *piece_id
2563                        && piece
2564                            .support_faces
2565                            .iter()
2566                            .any(|face| rim_tubes.get(&(face.operand as usize)) == Some(&wall_opening))
2567                })
2568            });
2569        }
2570    }
2571    for (index, carrier) in carriers.iter().enumerate() {
2572        if !matches!(carrier.kind, OffsetFaceRole::Offset) {
2573            continue;
2574        }
2575        // A rebuilt carrier keeps the edge records of the trim it replaced
2576        // (`full_rectangle_face` appends its rectangle to a copy). A tangent
2577        // rim cut restores exactly such a rim, so it is read against the
2578        // edges the trim USES; every other piece keeps the reading it had.
2579        let used_edges = carrier.solid.shells[0].faces[0]
2580            .loops
2581            .iter()
2582            .flat_map(|loop_record| &loop_record.coedges)
2583            .map(|coedge| coedge.edge_id)
2584            .collect::<HashSet<_>>();
2585        let boundaries = carrier
2586            .solid
2587            .edges
2588            .iter()
2589            .map(|edge| (used_edges.contains(&edge.id), FragmentEdgeGeometry {
2590                curve: edge.curve.clone(),
2591                t0: edge.t0,
2592                t1: edge.t1,
2593            }))
2594            .collect::<Vec<_>>();
2595        if let Some(by_face) = imprint
2596            .by_face
2597            .iter_mut()
2598            .find(|entry| entry.operand == index as u8)
2599        {
2600            let before = by_face.piece_ids.clone();
2601            by_face.piece_ids.retain(|piece_id| {
2602                let piece = &piece_geometry[piece_id];
2603                let rim_cut = rim_cut_pieces.contains(piece_id);
2604                !boundaries.iter().any(|(used, boundary)| {
2605                    (*used || !rim_cut)
2606                        && fragment_edge_lies_on(piece, boundary, boundary_coincidence_tolerance)
2607                            .unwrap_or(false)
2608                })
2609            });
2610            // Separate retained planes can imprint overlapping portions of the
2611            // same line on this carrier. Arrange that cut once: duplicate
2612            // segments otherwise erase the region between a blend section
2613            // and the line. Preserve each piece on its other carrier.
2614            let candidates = by_face.piece_ids.clone();
2615            by_face.piece_ids.retain(|id| {
2616                let edge = &piece_geometry[id];
2617                if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
2618                    return true;
2619                }
2620                !candidates.iter().any(|other_id| {
2621                    if id == other_id { return false; }
2622                    let other = &piece_geometry[other_id];
2623                    if other.curve.degree != 1 || other.curve.control_points.len() != 2 {
2624                        return false;
2625                    }
2626                    fragment_edge_lies_on(edge, other, tolerance).unwrap_or(false)
2627                        && (other_id < id
2628                            || !fragment_edge_lies_on(other, edge, tolerance).unwrap_or(false))
2629                })
2630            });
2631            if debug_enabled() && before.len() != by_face.piece_ids.len() {
2632                os_debug!(
2633                    "carrier[{index}] dropped boundary-coincident pieces: {:?} -> {:?}",
2634                    before,
2635                    by_face.piece_ids,
2636                );
2637            }
2638        }
2639    }
2640
2641    if debug_enabled() {
2642        for entry in &imprint.by_face {
2643            os_debug!(
2644                "by_face operand={} face={} pieces={:?}",
2645                entry.operand,
2646                entry.face_id,
2647                entry.piece_ids,
2648            );
2649        }
2650    }
2651    split_lap(8, &mut split_clock);
2652    if split_profile {
2653        profile_line!(
2654            "offset_shell.imprint_split skips={:.3} pair_build={:.3} pair_merge={:.3} standalone={:.3} wall_build={:.3} wall_merge={:.3} ring={:.3} smooth={:.3} filter={:.3}",
2655            split_ms[0], split_ms[1], split_ms[2], split_ms[3], split_ms[4], split_ms[5], split_ms[6], split_ms[7], split_ms[8],
2656        );
2657    }
2658    profile::lap(&mut clock, profile::IMPRINT);
2659    let mut split_carriers = Vec::new();
2660    let mut fragments_by_carrier = Vec::new();
2661    for (index, carrier) in carriers.iter().enumerate() {
2662        // Offset carriers keep their boundary un-split (their trims never
2663        // coincide with imprints — the boundary-coincidence filter drops such
2664        // pieces instead). An apex-cap ring breaks that assumption: the
2665        // frustum's ring is its TRIM boundary while the cap crosses it as TWO
2666        // imprint arcs — without splitting, the two sides segment differently
2667        // and both stay one-use. Split exactly the cap-affected carriers.
2668        let split = if matches!(carrier.kind, OffsetFaceRole::Offset)
2669            && !apex_cap_sources.contains(&index)
2670        {
2671            carrier.solid.clone()
2672        } else {
2673            apply_edge_splits(&carrier.solid, index as u8, &imprint)?
2674        };
2675        let fragment_clock = web_time::Instant::now();
2676        let fragments = fragment_solid(&split, index as u8, &imprint)?;
2677        os_debug!(
2678            "carrier[{index}] kind={:?} src={} fragments={} ({:.3} ms)",
2679            carrier.kind,
2680            carrier.source_face_id,
2681            fragments.len(),
2682            fragment_clock.elapsed().as_secs_f64() * 1e3,
2683        );
2684        if debug_enabled() {
2685            for (fragment_index, fragment) in fragments.iter().enumerate() {
2686                let mut boundary_count = 0usize;
2687                let mut imprint_pieces = Vec::new();
2688                let mut derived_count = 0usize;
2689                for coedge in fragment
2690                    .loops
2691                    .iter()
2692                    .flat_map(|loop_record| &loop_record.coedges)
2693                {
2694                    match &coedge.source {
2695                        FragmentEdgeSource::Boundary { .. }
2696                        | FragmentEdgeSource::SharedBoundary { .. } => boundary_count += 1,
2697                        FragmentEdgeSource::Imprint { piece_id } => imprint_pieces.push(*piece_id),
2698                        FragmentEdgeSource::Derived { .. } => derived_count += 1,
2699                    }
2700                }
2701                os_debug!(
2702                    "  frag[{index}.{fragment_index}] test=({:.3},{:.3},{:.3}) uv=({:.3},{:.3}) boundary={boundary_count} derived={derived_count} pieces={imprint_pieces:?}",
2703                    fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
2704                    fragment.test_uv.x, fragment.test_uv.y,
2705                );
2706            }
2707        }
2708        split_carriers.push(split);
2709        fragments_by_carrier.push(fragments);
2710    }
2711    profile::lap(&mut clock, profile::FRAGMENT);
2712    let mut assembly_sources = [(SOURCE_OPERAND, source)]
2713        .into_iter()
2714        .collect::<HashMap<_, _>>();
2715    for (index, carrier) in split_carriers.iter().enumerate() {
2716        assembly_sources.insert(index as u8, carrier);
2717    }
2718
2719    let source_edge_by_id = source
2720        .edges
2721        .iter()
2722        .map(|edge| (edge.id, edge))
2723        .collect::<HashMap<_, _>>();
2724    let retained_faces_with_edges = retained
2725        .iter()
2726        .map(|face_id| {
2727            let face = source_by_id[face_id];
2728            let edges = face
2729                .loops
2730                .iter()
2731                .flat_map(|loop_record| &loop_record.coedges)
2732                .filter_map(|coedge| source_edge_by_id.get(&coedge.edge_id).copied())
2733                .collect::<Vec<_>>();
2734            (face, edges)
2735        })
2736        .collect::<Vec<_>>();
2737    let mut offset_skin_tolerance = offset_skin_band(scale, distance);
2738    // `BREP_OFFSET_THIN_SKIN_PAD`: the band's 2e-3 floor is a fixed length;
2739    // on a shell thinner than it (box-paper-thin, d = 1e-3) no point was ever
2740    // shadowed (`separation < d - 2e-3` cannot hold), so the opening's 1e-3
2741    // corner squares, holding no wall seed, read as the void and were left
2742    // out of the rim. A thin shell's band is held to a quarter of it.
2743    if thin_skin_pad_enabled() && distance > 0.0 {
2744        offset_skin_tolerance = offset_skin_tolerance.min(0.25 * distance.abs());
2745    }
2746    // OUTWARD shells: a wall fragment lying IN FRONT of another opening —
2747    // past that opening's plane on its void side, within the extent of its
2748    // (extended) wall carrier — is not material: an opening removes
2749    // everything in front of it. Such a fragment is the sheet of this wall
2750    // between the source outline and the grown outline on the far side of an
2751    // ADJACENT opening's shared edge (the x∈[−1,0] strip of an opened −Z
2752    // face's wall, in front of the opened −X face). It sits within |distance|
2753    // of a retained face's corner edge, so the void-cross-section guard reads
2754    // it as wall thickness; only the other opening's plane tells it apart.
2755    //
2756    // A RULED opening's wall is curved, so it has no one plane: its front is
2757    // read at the point's foot on the wall carrier, along the carrier's normal
2758    // turned to the opening face's outward side. On the torus wedge that is
2759    // what drops the start and end caps' strips beyond the extended chord,
2760    // which lie within |distance| of the torus and in front of the cone.
2761    let mut opening_planes: Vec<(usize, Vec3, Vec3)> = Vec::new();
2762    let mut opening_ruled: Vec<(usize, f64)> = Vec::new();
2763    if distance < 0.0 {
2764        for (index, carrier) in carriers.iter().enumerate() {
2765            if !matches!(carrier.kind, OffsetFaceRole::Wall) {
2766                continue;
2767            }
2768            let opening = source_by_id[&carrier.source_face_id];
2769            let [u0, u1] = opening.surface.domain_u().or_refuse(KernelStage::Sew, "domain_u")?;
2770            let [v0, v1] = opening.surface.domain_v().or_refuse(KernelStage::Sew, "domain_v")?;
2771            let (u, v) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
2772            if ruled_walls.contains(&index) {
2773                let wall = &split_carriers[index].shells[0].faces[0];
2774                let probe = project_point_to_surface(&wall.surface, opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2775                let side = face_normal(wall, probe.u, probe.v)?.dot(face_normal(opening, u, v)?);
2776                opening_ruled.push((index, if side < 0.0 { -1.0 } else { 1.0 }));
2777                continue;
2778            }
2779            if !opening.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
2780                continue;
2781            }
2782            opening_planes.push((
2783                index,
2784                opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?,
2785                face_normal(opening, u, v)?,
2786            ));
2787        }
2788    }
2789    let in_front_of_other_opening = |wall_index: usize, point: Vec3| -> Result<bool, KernelRefusal> {
2790        let band = 2e-3f64.max(scale * 5e-5);
2791        for (index, plane_point, outward) in &opening_planes {
2792            if *index == wall_index || point.sub(*plane_point).dot(*outward) <= band {
2793                continue;
2794            }
2795            let face = &split_carriers[*index].shells[0].faces[0];
2796            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2797            let uv = Vec2 {
2798                x: projection.u,
2799                y: projection.v,
2800            };
2801            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2802                return Ok(true);
2803            }
2804        }
2805        for (index, side) in &opening_ruled {
2806            if *index == wall_index {
2807                continue;
2808            }
2809            let face = &split_carriers[*index].shells[0].faces[0];
2810            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2811            let outward = face_normal(face, projection.u, projection.v)?.scale(*side);
2812            if point.sub(projection.point).dot(outward) <= band {
2813                continue;
2814            }
2815            let uv = Vec2 {
2816                x: projection.u,
2817                y: projection.v,
2818            };
2819            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2820                return Ok(true);
2821            }
2822        }
2823        Ok(false)
2824    };
2825
2826    let mut chosen_offsets = Vec::new();
2827    let mut chosen_walls = Vec::new();
2828    let mut newly_shadowed = HashSet::<u64>::default();
2829    for (index, carrier) in carriers.iter().enumerate() {
2830        let raw_seeds = source_seeds(source, carrier.source_face_id)?;
2831        let mut seeds = Vec::with_capacity(raw_seeds.len());
2832        for raw_seed in raw_seeds {
2833            let seed = if matches!(carrier.kind, OffsetFaceRole::Offset) {
2834                offset_seed(
2835                    source_by_id[&carrier.source_face_id],
2836                    raw_seed,
2837                    &split_carriers[index].shells[0].faces[0].surface,
2838                    distance,
2839                    2e-3f64.max(scale * 5e-5),
2840                )?
2841                .unwrap_or(raw_seed)
2842            } else if inward_extended_walls.contains(&index) {
2843                offset_seed(
2844                    source_by_id[&carrier.source_face_id],
2845                    raw_seed,
2846                    &split_carriers[index].shells[0].faces[0].surface,
2847                    0.0,
2848                    2e-3f64.max(scale * 5e-5),
2849                )?
2850                .unwrap_or(raw_seed)
2851            } else {
2852                raw_seed
2853            };
2854            if seed.sub(raw_seed).length() > 1e-9 {
2855                os_debug!(
2856                    "  seed[{index}] moved from ({:.4},{:.4}) to the offset image ({:.4},{:.4})",
2857                    raw_seed.x,
2858                    raw_seed.y,
2859                    seed.x,
2860                    seed.y
2861                );
2862            }
2863            seeds.push(seed);
2864        }
2865        let seed = seeds[0];
2866        if matches!(carrier.kind, OffsetFaceRole::Offset) {
2867            // Fragments whose test point sits at the full offset distance
2868            // from every retained source face are the true offset-skin
2869            // regions. Fragments closer to some other face are shadowed
2870            // pockets/strips that another carrier owns.
2871            // A fragment whose offset lies ON another retained face's offset
2872            // (material exactly twice the shell distance thick: a slot, fin or
2873            // floor at t = 2d) reads as SHADOWED by that face. One hair
2874            // thinner, the same fragment reads shadowed on its own and is
2875            // dropped by the on-skin filter, or omits its carrier by the
2876            // skinless rule below, so the answer is the limit of that
2877            // construction: the census's L∞ forms are continuous across the
2878            // onset. Without this the fragment read On, was selected, and the
2879            // shell refused as "a cavity pinched to zero thickness". The
2880            // coincidence test is `coincident_offset_face`'s (the other face's
2881            // distance within `offset_skin_tolerance` of |d|, its foot on the
2882            // opposite side of the point from this face's own), taken only on
2883            // the THIN side of the onset.
2884            let mut readings = Vec::with_capacity(fragments_by_carrier[index].len());
2885            // The construction band allows a carrier's own fit residual. It
2886            // must not also preserve pockets buried by neighboring offsets:
2887            // that coverage is what justified admitting a finite cusp. Keep
2888            // the own-face reading unchanged, and measure other faces at the
2889            // fit tolerance for this construction.
2890            let cusp_neighbors = if shielded_cusps.is_empty() {
2891                Vec::new()
2892            } else {
2893                retained_faces_with_edges.iter()
2894                    .filter(|(face, _)| face.id != carrier.source_face_id)
2895                    .cloned().collect::<Vec<_>>()
2896            };
2897            for fragment in &fragments_by_carrier[index] {
2898                let reading = offset_skin_reading(
2899                    fragment.test_point,
2900                    &retained_faces_with_edges,
2901                    distance,
2902                    offset_skin_tolerance,
2903                );
2904                let reading = if matches!(&reading, SkinReading::On) && !cusp_neighbors.is_empty() {
2905                    offset_skin_reading(
2906                        fragment.test_point,
2907                        &cusp_neighbors,
2908                        distance,
2909                        4.0 * KernelTolerances::for_solid(source, 1e-7).intersection_fit,
2910                    )
2911                } else {
2912                    reading
2913                };
2914                let reading = match reading {
2915                    SkinReading::On => match coincident_offset_face(
2916                        fragment.test_point,
2917                        carrier.source_face_id,
2918                        &retained_faces_with_edges,
2919                        distance,
2920                        offset_skin_tolerance,
2921                    )? {
2922                        // ONE-SIDED and tight: only material no thicker than
2923                        // 2|d| (to 10× the model tolerance) takes the thin
2924                        // construction, which is exact there. A wall inside
2925                        // the skin band but genuinely thicker than 2|d| keeps
2926                        // its sliver cavity's named refusal below; taking the
2927                        // thin construction there would fill a real cavity.
2928                        Some((face, separation)) if separation <= distance.abs() + tolerance * 10.0 => {
2929                            // A coincidence the fragment's other interior
2930                            // points do not share is a tangent TOUCH: the
2931                            // cavity pinches to a line there, and dropping the
2932                            // fragment as a sheet would discard real skin.
2933                            if tangent_touch_on() {
2934                                if let Some((farther, far)) = tangent_touch(
2935                                    fragment,
2936                                    face,
2937                                    &retained_faces_with_edges,
2938                                    distance,
2939                                    offset_skin_tolerance,
2940                                )? {
2941                                    return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::TANGENT_OFFSETS, format!(
2942                                        "offset_shell: the offsets of source faces {} and {face} touch tangentially near \
2943                                         ({:.4}, {:.4}, {:.4}) — the material between those faces is exactly twice the \
2944                                         shell distance thick along that touch (separation {separation:.6} against {:.6}) \
2945                                         and thicker beside it (the offset reads {far:.4} from face {face} at ({:.4}, {:.4}, {:.4})), so the cavity would \
2946                                         pinch to a line there; a cavity pinched to a line is not supported — use a \
2947                                         shell distance a little below {:.4}",
2948                                        carrier.source_face_id,
2949                                        fragment.test_point.x,
2950                                        fragment.test_point.y,
2951                                        fragment.test_point.z,
2952                                        distance.abs(),
2953                                        farther.x,
2954                                        farther.y,
2955                                        farther.z,
2956                                        distance.abs(),
2957                                    )));
2958                                }
2959                            }
2960                            SkinReading::Shadowed { face, separation }
2961                        }
2962                        _ => SkinReading::On,
2963                    },
2964                    other => other,
2965                };
2966                // One test point cannot speak for a skin that bounds a cavity
2967                // the solid demonstrably has: see `cavity_witness`.
2968                let reading = match reading {
2969                    SkinReading::Shadowed { .. } if cavity_bounds.contains(&carrier.source_face_id) => SkinReading::On,
2970                    other => other,
2971                };
2972                readings.push(reading);
2973            }
2974            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
2975                if let SkinReading::Unmeasured { face, reason } = reading {
2976                    return Err(unmeasured_skin_refusal(fragment.test_point, *face, reason));
2977                }
2978            }
2979            if mixed_fragment_report_on() {
2980                let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
2981                omitted.sort_unstable();
2982                for (fragment_index, (fragment, reading)) in fragments_by_carrier[index].iter().zip(&readings).enumerate() {
2983                    let Some(mixed) = mixed_fragment_reading(fragment, source, &retained_faces_with_edges, distance, offset_skin_tolerance)? else { continue };
2984                    if mixed.mixed() {
2985                        eprintln!(
2986                            "MIXED-FRAGMENT d={distance} omitted={omitted:?} src={} fragment={fragment_index} skin={} shadowed={} of {} shadowing={:?} test_reading={} test=({:.4},{:.4},{:.4})",
2987                            carrier.source_face_id, mixed.skin, mixed.shadowed, mixed.inside, mixed.shadowing,
2988                            match reading { SkinReading::On => "On", SkinReading::Shadowed { .. } => "Shadowed", SkinReading::Unmeasured { .. } => "Unmeasured" },
2989                            fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
2990                        );
2991                    }
2992                }
2993            }
2994            // EVERY fragment measured nearer than the distance to some other
2995            // retained face: this support's offset is SHADOWED over its whole
2996            // extended carrier — the side walls of a slot narrower than 2|d|
2997            // grown outward, a pocket floor within 2d of the face under it.
2998            // It owns no skin. It used to switch the filter off and keep its
2999            // seeded fragment anyway, which built a closed, validating shell
3000            // with an inverted box inside it (+90 on a width-2 slot grown by
3001            // 1.5, with the 90 of material at its centre missing). Dropping
3002            // only its fragments is not enough: its carrier has already cut
3003            // its neighbours, and the top skin over that slot keeps a hole
3004            // nothing fills. So the pass is re-run with the support omitted
3005            // before the imprint, like a collapsed one. An apex-cap sphere
3006            // shares its cone's source id and is not judged here.
3007            //
3008            // Only the FIRST pass omits. A test point speaks for its fragment
3009            // because every other carrier's imprint bounds it; omitting a
3010            // carrier removes cuts, merges fragments and moves test points,
3011            // but changes no distance, so a support that reads shadowed only
3012            // AFTER an omission is reading a test point that no longer stands
3013            // for its fragment. Measured on two bosses 1 apart grown outward
3014            // by 1.5: once the facing boss walls were omitted, the plate's
3015            // grown top — one uncut fragment, mostly skin — read shadowed at
3016            // its single test point.
3017            //
3018            // "Every fragment" counts a fragment the selection would drop by
3019            // CLASS as not skin, as the selection does: the extended carrier's
3020            // surplus past a slot's end reads at least the distance from every
3021            // face, lies inside the source, and on a slot 1 wide grown outward
3022            // left the slot floor unjudged until the side walls were gone.
3023            // ADRIFT: a fragment whose test point is farther from its OWN face
3024            // than the distance, in the mitered metric, is not that face's skin
3025            // — it is inside the cavity, past where its neighbours' offsets cut
3026            // it. A rib, a pin or a divider thinner than 2d shelled inward
3027            // keeps such fragments, and the assembly then fails on them.
3028            let adrift = fragments_by_carrier[index]
3029                .iter()
3030                .map(|fragment| {
3031                    point_adrift_of_its_own_offset(
3032                        fragment.test_point,
3033                        carrier.source_face_id,
3034                        &retained_faces_with_edges,
3035                        distance,
3036                        offset_skin_tolerance,
3037                    )
3038                })
3039                .collect::<Vec<_>>();
3040            let mut skinless = readings
3041                .iter()
3042                .any(|reading| matches!(reading, SkinReading::Shadowed { .. }))
3043                || adrift.iter().any(|flag| *flag);
3044            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
3045                if !skinless {
3046                    break;
3047                }
3048                if matches!(reading, SkinReading::On)
3049                    && !adrift[fragments_by_carrier[index]
3050                        .iter()
3051                        .position(|other| std::ptr::eq(other, fragment))
3052                        .unwrap_or(0)]
3053                {
3054                    let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
3055                    skinless = (distance > 0.0 && class == PointClass::Out)
3056                        || (distance < 0.0 && class == PointClass::In);
3057                }
3058            }
3059            #[cfg(not(test))]
3060            let forced_shadow = false;
3061            let skinless = skinless || forced_shadow;
3062            if skinless && !apex_cap_sources.contains(&index) {
3063                if body == Body::Shell && distance > 0.0 && cascade_omission_enabled() && !forced_shadow {
3064                    let held = fragments_holding_true_skin(
3065                        source_by_id[&carrier.source_face_id],
3066                        source,
3067                        &fragments_by_carrier[index],
3068                        &retained_faces_with_edges,
3069                        distance,
3070                        offset_skin_tolerance,
3071                    )?;
3072                    if !held.is_empty() {
3073                        os_debug!("  select[{index}] src={}: {} fragment(s) hold true skin", carrier.source_face_id, held.len());
3074                        chosen_offsets.extend(held);
3075                        continue;
3076                    }
3077                }
3078                if !shadowed_supports.is_empty() && !(body == Body::Shell && distance > 0.0 && cascade_omission_enabled()) {
3079                    let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3080                    omitted.sort_unstable();
3081                    return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
3082                        "offset_shell: omitting the shadowed offsets of source faces {omitted:?} \
3083                         leaves the offset of source face {} shadowed at every one of its {} \
3084                         fragment test points, which no longer stand for their fragments once \
3085                         those carriers stop cutting it",
3086                        carrier.source_face_id,
3087                        readings.len()
3088                    )));
3089                }
3090                if surviving_tubes.contains(&index) {
3091                    os_debug!("  select[{index}] src={}: a surviving round's rim tube reads shadowed; only the tube is dropped", carrier.source_face_id);
3092                    continue;
3093                }
3094                // A band piece buried whole is that piece's answer, not its
3095                // face's: its siblings may still bound material. Its carrier
3096                // stays in the imprint, so the cuts it makes are unchanged.
3097                if band_pieces.contains(&index)
3098                    && carriers.iter().enumerate().any(|(other, sibling)| {
3099                        other != index && sibling.source_face_id == carrier.source_face_id && band_pieces.contains(&other)
3100                    })
3101                {
3102                    os_debug!("  select[{index}] src={}: a band piece reads shadowed; only the piece is dropped", carrier.source_face_id);
3103                    continue;
3104                }
3105                os_debug!(
3106                    "  select[{index}] src={} SHADOWED over all {} fragment(s): {:?}",
3107                    carrier.source_face_id,
3108                    readings.len(),
3109                    readings
3110                );
3111                newly_shadowed.insert(carrier.source_face_id);
3112                continue;
3113            }
3114            // Partly shadowed: keep a bounded sample of the shadowed test
3115            // points, so a refusal can say where two offsets cross.
3116            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
3117                if shadowed_points.len() >= MAXIMUM_CROSSING_READS {
3118                    break;
3119                }
3120                if matches!(reading, SkinReading::Shadowed { .. }) {
3121                    shadowed_points.push((fragment.test_point, carrier.source_face_id));
3122                }
3123            }
3124            let mut on_skin = readings
3125                .iter()
3126                .zip(&adrift)
3127                .map(|(reading, adrift)| matches!(reading, SkinReading::On) && !adrift)
3128                .collect::<Vec<_>>();
3129            if open_section_reach {
3130                if let Some(ends) = open_profile_end_neighbours(index, &carriers, &source_faces)? {
3131                    // A continued variable profile can approach its original
3132                    // end cap inside the distance band. Its sharp boundary is
3133                    // the section with the OFFSET end plane, not that old cap.
3134                    for (keep, fragment) in on_skin.iter_mut().zip(&fragments_by_carrier[index]) {
3135                        *keep = !outside_continued_neighbours(fragment.test_point, &ends, &carriers, tolerance)?;
3136                    }
3137                    os_debug!("  select[{index}] open profile kept {} central regions", on_skin.iter().filter(|keep| **keep).count());
3138                }
3139            }
3140            // A synthetic apex sphere has no source-face seed of its own to
3141            // fall back to. When its whole cap is hidden by retained offsets,
3142            // keep its cuts but contribute no skin. Otherwise the fallback
3143            // selects the uncut sphere as a stray patch inside the material.
3144            // The parent cone remains subject to the ordinary selection.
3145            let skin_filter_active = on_skin.iter().any(|flag| *flag)
3146                || apex_cap_pairs.iter().any(|(_, cap)| *cap == index);
3147            let opening_limits = if inward_extended_walls.is_empty() {
3148                Vec::new()
3149            } else {
3150                let openings = inward_extended_walls
3151                    .iter()
3152                    .map(|index| source_by_id[&carriers[*index].source_face_id])
3153                    .collect::<Vec<_>>();
3154                opening_trim_halfspaces(source_by_id[&carrier.source_face_id], &openings, tolerance)?
3155            };
3156            let mut classified = Vec::new();
3157            let mut viable = Vec::new();
3158            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3159                let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
3160                let excluded_by_class = (distance > 0.0 && class == PointClass::Out)
3161                    || (distance < 0.0 && class == PointClass::In);
3162                let contact = if excluded_by_class {
3163                    false
3164                } else {
3165                    distance > 0.0
3166                        && fragment_has_sustained_source_contact(
3167                            fragment,
3168                            &source_faces,
3169                            &assembly_sources,
3170                            &imprint,
3171                            2e-3f64.max(scale * 5e-5),
3172                        )?
3173                };
3174                os_debug!(
3175                    "  select[{index}.{fragment_index}] class={class:?} contact={contact} on_skin={} reading={:?} adrift={} seed_in={:?} uv=({:.3},{:.3}) at ({:.4},{:.4},{:.4})",
3176                    on_skin[fragment_index],
3177                    readings[fragment_index],
3178                    adrift[fragment_index],
3179                    parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8),
3180                    fragment.test_uv.x, fragment.test_uv.y,
3181                    fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3182                );
3183                let past_opening = opening_limits.iter().any(|(origin, normal)| {
3184                    fragment.test_point.sub(*origin).dot(*normal) < -tolerance * 10.0
3185                });
3186                if excluded_by_class
3187                    || past_opening
3188                    || (skin_filter_active && !on_skin[fragment_index])
3189                {
3190                    continue;
3191                }
3192                classified.push(fragment.clone());
3193                if contact {
3194                    continue;
3195                }
3196                viable.push(fragment.clone());
3197            }
3198            // One skin per REGION of the source face (see `source_seeds`):
3199            // every region of a pinched face is offset like a face of its
3200            // own, and the selection below answers each region's seed. An
3201            // ordinary face has the one seed and the one answer it always had.
3202            let mut region_skins = Vec::new();
3203            let continued_neighbours = if distance > 0.0 {
3204                continued_sphere_neighbours(index, &carriers, &source_faces, scale)?
3205            } else { None };
3206            if let Some(neighbours) = &continued_neighbours {
3207                for fragment in &classified {
3208                    if outside_continued_neighbours(fragment.test_point, neighbours, &carriers, tolerance)? {
3209                        region_skins.push(fragment.clone());
3210                    }
3211                }
3212                os_debug!("  select[{index}] continued sphere kept {} regions", region_skins.len());
3213            }
3214            for &seed in seeds.iter().filter(|_| continued_neighbours.is_none()) {
3215                os_debug!("  select[{index}] seed=({:.4},{:.4})", seed.x, seed.y);
3216                let seeded = viable
3217                    .iter()
3218                    .filter(|fragment| {
3219                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3220                            .is_ok_and(|class| class != PolygonClass::Outside)
3221                    })
3222                    .cloned()
3223                    .collect::<Vec<_>>();
3224                let seeded_classified = classified
3225                    .iter()
3226                    .filter(|fragment| {
3227                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3228                            .is_ok_and(|class| class != PolygonClass::Outside)
3229                    })
3230                    .cloned()
3231                    .collect::<Vec<_>>();
3232                let selected = if viable.is_empty() {
3233                    if !skin_filter_active {
3234                        // NOTHING on this carrier reads on-skin: every classified
3235                        // fragment's test point is measurably CLOSER than the
3236                        // offset distance to some retained face — a buried strip
3237                        // another carrier owns. Forcing the largest one in anyway
3238                        // plants a wrong skin patch that collides with the
3239                        // completion phase's reconstruction (3-use edges).
3240                        // Contribute nothing: `complete_opening_boundary_cycles`
3241                        // rebuilds the true skin from the carrier surface, and the
3242                        // watertight gate still refuses if it cannot.
3243                        None
3244                    } else {
3245                        // ON ITS OWN OFFSET (`BREP_OFFSET_STAND_IN_ON_OWN_OFFSET`):
3246                        // the stand-in is drawn only from the pieces whose test
3247                        // point lies the distance from the carrier's OWN trimmed
3248                        // face, the one holding the seed first. A cylinder kept
3249                        // as one face is offset on its full turn, and the part
3250                        // of that turn buried in the neighbouring wall comes
3251                        // out as a larger piece than the face's own image (a
3252                        // boss whose axis sits inside the wall: 2.4 from the
3253                        // cylinder against 0.1); chosen by area it closed the
3254                        // shell around a skin inside the material.
3255                        let mut pool = classified.clone();
3256                        let mut seeded_own = None;
3257                        if stand_in_on_own_offset_on() {
3258                            let own = classified
3259                                .iter()
3260                                .filter(|fragment| {
3261                                    own_offset_departure(fragment.test_point, carrier.source_face_id, &retained_faces_with_edges, distance)
3262                                        .is_some_and(|departure| departure.abs() <= offset_skin_tolerance)
3263                                })
3264                                .cloned()
3265                                .collect::<Vec<_>>();
3266                            if !own.is_empty() {
3267                                let mut seeded = own
3268                                    .iter()
3269                                    .filter(|fragment| {
3270                                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3271                                            .is_ok_and(|class| class != PolygonClass::Outside)
3272                                    })
3273                                    .cloned()
3274                                    .collect::<Vec<_>>();
3275                                seeded.sort_by(|a, b| a.test_uv.sub(seed).length().total_cmp(&b.test_uv.sub(seed).length()));
3276                                seeded_own = seeded.into_iter().next();
3277                                pool = own;
3278                            }
3279                        }
3280                        let mut by_area = pool
3281                            .iter()
3282                            .cloned()
3283                            .map(|fragment| {
3284                                let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3285                                Ok((fragment, area))
3286                            })
3287                            .collect::<Result<Vec<_>, KernelRefusal>>()?;
3288                        by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3289                        seeded_own.or_else(|| by_area.into_iter().next().map(|entry| entry.0))
3290                    }
3291                } else if !seeded_classified.is_empty() {
3292                    let mut candidates = seeded_classified;
3293                    candidates.sort_by(|a, b| {
3294                        a.test_uv
3295                            .sub(seed)
3296                            .length()
3297                            .total_cmp(&b.test_uv.sub(seed).length())
3298                    });
3299                    candidates.into_iter().next()
3300                } else if viable.len() > 2 {
3301                    let mut by_area = viable
3302                        .iter()
3303                        .cloned()
3304                        .map(|fragment| {
3305                            let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3306                            Ok((fragment, area))
3307                        })
3308                        .collect::<Result<Vec<_>, KernelRefusal>>()?;
3309                    by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3310                    by_area.into_iter().next().map(|entry| entry.0)
3311                } else {
3312                    let mut candidates = if seeded.is_empty() { viable.clone() } else { seeded };
3313                    candidates.sort_by(|a, b| {
3314                        a.test_uv
3315                            .sub(seed)
3316                            .length()
3317                            .total_cmp(&b.test_uv.sub(seed).length())
3318                    });
3319                    candidates.into_iter().next()
3320                };
3321                let mut drop_debris = false;
3322                if let Some(fragment) = &selected {
3323                    os_debug!(
3324                        "  select[{index}] src={} chosen test point departs its own face's offset \
3325                         distance by {:?}",
3326                        carrier.source_face_id,
3327                        own_offset_departure(
3328                            fragment.test_point,
3329                            carrier.source_face_id,
3330                            &retained_faces_with_edges,
3331                            distance
3332                        )
3333                    );
3334                    os_debug!(
3335                        "  select[{index}] src={} chosen test point departs in the MITER metric by {:?}",
3336                        carrier.source_face_id,
3337                        own_miter_departure(
3338                            fragment.test_point,
3339                            carrier.source_face_id,
3340                            &retained_faces_with_edges,
3341                            distance
3342                        )
3343                    );
3344                    let coincidence = coincident_offset_face(
3345                        fragment.test_point,
3346                        carrier.source_face_id,
3347                        &retained_faces_with_edges,
3348                        distance,
3349                        offset_skin_tolerance,
3350                    )?;
3351                    let coincidence = match coincidence {
3352                        Some((other, separation))
3353                            if coincide_debris_on()
3354                                && fragment_is_band_debris(fragment, offset_skin_tolerance)? =>
3355                        {
3356                            os_debug!(
3357                                "  select[{index}] src={} drops corner debris coincident with {other} \
3358                                 (separation {separation}) at {:?}",
3359                                carrier.source_face_id,
3360                                fragment.test_point
3361                            );
3362                            drop_debris = true;
3363                            None
3364                        }
3365                        reading => reading,
3366                    };
3367                    if let Some((other, separation)) = coincidence {
3368                        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_coincident_offsets", format!(
3369                            "offset_shell: the offsets of source faces {} and {other} coincide near \
3370                             ({:.4}, {:.4}, {:.4}) — the material between those faces is twice the \
3371                             shell distance thick (separation {separation:.6} against {:.6}, band \
3372                             {offset_skin_tolerance:.1e}), so the cavity between them has no \
3373                             thickness there; a cavity pinched to zero thickness is not supported",
3374                            carrier.source_face_id,
3375                            fragment.test_point.x,
3376                            fragment.test_point.y,
3377                            fragment.test_point.z,
3378                            distance.abs(),
3379                        )));
3380                    }
3381                }
3382                let selected = if drop_debris { None } else { selected };
3383                if let Some(fragment) = selected {
3384                    // A pinched face's seeds each find their own region; a
3385                    // fallback that ignores the seed can answer the same
3386                    // fragment twice, and one skin must enter once.
3387                    if !region_skins
3388                        .iter()
3389                        .any(|other: &FaceFragmentRecord| {
3390                            other.test_point.sub(fragment.test_point).length() <= 1e-12
3391                        })
3392                    {
3393                        region_skins.push(fragment);
3394                    }
3395                }
3396            }
3397            // EVERY SKIN PIECE (`BREP_OFFSET_EVERY_SKIN_PIECE`, default on):
3398            // one source region's offset skin can come out in several pieces
3399            // when another offset cuts it (the drilled block's bore skin,
3400            // radius 4, runs into the wall skin x = 19 and parts it at
3401            // y = 10 ± √15/2) or the carrier's seam parts it (the bore skin
3402            // itself, at its seam). The seed answers one piece; every
3403            // classified fragment already reads on the skin, inside the source
3404            // and short of the openings, so all of them are the skin, as for
3405            // the extended walls below. Left out, the pieces the seed missed
3406            // left their outlines one-use (shell/hole-skin-merging-wall).
3407            // Only where the seed could not choose: an inward shell whose every
3408            // on-skin fragment touches the source (`viable` empty), so the
3409            // largest stood in for the region; an outward shell's fragments and
3410            // a seeded choice keep the seed's answer. And only a piece whose
3411            // test point lies the distance from its OWN trimmed face: "on the
3412            // skin" says no retained face is nearer, which a point inside the
3413            // offset body also reads (the cylinder's offset past a reflex
3414            // junction, inside the box's offset wall: 0.139 from the trimmed
3415            // cylinder against 0.1, reflex_junction_under_a_filleted_top).
3416            if every_skin_piece_enabled()
3417                && distance > 0.0
3418                && (viable.is_empty() || every_seeded_piece)
3419                && skin_filter_active
3420                && inward_extended_walls.is_empty()
3421                && classified.len() > region_skins.len()
3422            {
3423                for fragment in &classified {
3424                    if region_skins.iter().any(|other: &FaceFragmentRecord| other.test_point.sub(fragment.test_point).length() <= 1e-12) {
3425                        continue;
3426                    }
3427                    let departure = own_offset_departure(fragment.test_point, carrier.source_face_id, &retained_faces_with_edges, distance);
3428                    os_debug!("  select[{index}] every skin piece: test point ({:.4},{:.4},{:.4}) departs its own face's offset by {departure:?}", fragment.test_point.x, fragment.test_point.y, fragment.test_point.z);
3429                    if departure.is_some_and(|departure| departure.abs() <= offset_skin_tolerance) {
3430                        region_skins.push(fragment.clone());
3431                    }
3432                }
3433            }
3434            if !inward_extended_walls.is_empty() && skin_filter_active {
3435                // The extended opening cuts beyond the source footprint.
3436                // Other finite carriers can subdivide a connected offset
3437                // region there (the box/revolve report splits both box caps
3438                // at x=1). A single source seed keeps only one of those cells.
3439                // Keep every cell already proved inside the source and on
3440                // the offset skin, then merge their shared boundaries.
3441                region_skins = classified;
3442            }
3443            chosen_offsets.extend(region_skins);
3444        } else if body == Body::Whole {
3445            // A HELD face of the offset body: its carrier is the face at
3446            // distance zero, cut by the neighbouring offset skins; the body
3447            // keeps the region the face's own seed lies in, whole. There is
3448            // no source rim to stop at and no void in front of it.
3449            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3450                if seeds.iter().any(|seed| {
3451                    parameter_point_in_face(&fragment_as_trim(fragment), *seed, 1e-8)
3452                        .is_ok_and(|class| class != PolygonClass::Outside)
3453                }) {
3454                    os_debug!("  held[{index}.{fragment_index}] kept: contains the face's seed");
3455                    chosen_walls.push(fragment.clone());
3456                }
3457            }
3458        } else {
3459            // Keep arrangement order stable. Besides making the result
3460            // reproducible, this matches the reference kernel's Set insertion
3461            // order when the final manifold-wall guard admits fragments.
3462            let opening = source_by_id[&carrier.source_face_id];
3463            let wall_seeds = opening_wall_seeds(
3464                opening,
3465                &split_carriers[index].shells[0].faces[0],
3466                source,
3467                &opening_set,
3468                distance,
3469            )?;
3470            // The wall-seed exemptions below rest on "the coplanar-rim weld
3471            // cuts the void hole later" — which only ever happens on PLANAR
3472            // opening carriers. A curved carrier (e.g. the sphere face used
3473            // directly as the opening) keeps its un-split fragment forever:
3474            // exempting it would seal the opening with the source face itself
3475            // and fabricate a closed hollow solid. Curved carriers therefore
3476            // get the strict void guard.
3477            let carrier_planar =
3478                surface_is_planar(&split_carriers[index].shells[0].faces[0].surface, tolerance)
3479                    .unwrap_or(false);
3480            let extended_inward = inward_extended_walls.contains(&index);
3481            let outside_source = |point| -> Result<bool, KernelRefusal> {
3482                Ok(extended_inward
3483                    && classify_point(point, source, tolerance * 10.0)
3484                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::Out)
3485            };
3486            let wall_on_skin = |point| {
3487                if extended_inward {
3488                    let inside_source = classify_point(point, source, tolerance * 10.0)
3489                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In;
3490                    point_on_inward_opening_skin(
3491                        point,
3492                        &retained_faces_with_edges,
3493                        &reflex_wall_neighbors[&index],
3494                        inside_source,
3495                        distance,
3496                        offset_skin_tolerance,
3497                    )
3498                } else {
3499                    point_on_offset_skin(
3500                        point,
3501                        &retained_faces_with_edges,
3502                        distance,
3503                        offset_skin_tolerance,
3504                    )
3505                }
3506            };
3507            let mut selected_indices = Vec::new();
3508            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3509                if outside_source(fragment.test_point)? {
3510                    continue;
3511                }
3512                if parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")?
3513                    == PolygonClass::Outside
3514                {
3515                    if in_front_of_other_opening(index, fragment.test_point)? {
3516                        os_debug!(
3517                            "  wall[{index}.{fragment_index}] skipped: in front of another \
3518                             opening at ({:.3},{:.3},{:.3})",
3519                            fragment.test_point.x,
3520                            fragment.test_point.y,
3521                            fragment.test_point.z,
3522                        );
3523                        continue;
3524                    }
3525                    // Wall = the material cross-section exposed at the
3526                    // opening: every point of a genuine wall fragment lies
3527                    // WITHIN the offset distance of some retained face (it is
3528                    // the thickness between that face and its offset skin). A
3529                    // fragment at ≥ distance from EVERY retained face — and
3530                    // containing no expected wall seed (an un-split cap
3531                    // fragment can span both the void AND the wall annulus;
3532                    // the coplanar-rim weld cuts its hole later) — is the
3533                    // core's own cross-section: a HOLE in the opening (e.g.
3534                    // the corner void where a carve's offset circle passes
3535                    // just inside the opening's corner). Welding it shut
3536                    // would fabricate a wall over the void.
3537                    if wall_on_skin(fragment.test_point)? && !(carrier_planar
3538                        && !extended_inward
3539                        && wall_seeds.iter().any(|wall_seed| {
3540                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3541                                .is_ok_and(|class| class != PolygonClass::Outside)
3542                        }))
3543                    {
3544                        os_debug!(
3545                            "  wall[{index}.{fragment_index}] skipped: void cross-section at \
3546                             ({:.3},{:.3},{:.3})",
3547                            fragment.test_point.x,
3548                            fragment.test_point.y,
3549                            fragment.test_point.z,
3550                        );
3551                        continue;
3552                    }
3553                    // A SURPLUS fragment beyond a sharp convex corner: it
3554                    // touches the wall's own outline, no edge of it was cut by
3555                    // the SOURCE (the rim every genuine wall region borders),
3556                    // and it holds no wall seed. The void test above reads it
3557                    // as material, because it measures a planar neighbour in the
3558                    // MITER metric (its extended plane, 0.277 from this region
3559                    // on the free-form D turning 83.7° at d = 0.3). The
3560                    // opening wall's clearance cuts such a region off between
3561                    // the carriers' tails past the mitre, and kept, it
3562                    // assembled as "non-integral genus" (8 of the D band's 42
3563                    // cells, 2026-09-26).
3564                    if distance < 0.0
3565                        && wall_surplus_beyond_the_sections(fragment, index as u8, |piece_id| {
3566                            imprint.pieces.iter().find(|piece| piece.id == piece_id).is_some_and(|piece| {
3567                                piece.support_faces.iter().any(|key| key.operand == SOURCE_OPERAND)
3568                            })
3569                        })
3570                        && !wall_seeds.iter().any(|wall_seed| {
3571                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3572                                .is_ok_and(|class| class != PolygonClass::Outside)
3573                        })
3574                    {
3575                        os_debug!(
3576                            "  wall[{index}.{fragment_index}] skipped: surplus beyond the sections at \
3577                             ({:.3},{:.3},{:.3}), touching the wall outline and no source rim",
3578                            fragment.test_point.x,
3579                            fragment.test_point.y,
3580                            fragment.test_point.z,
3581                        );
3582                        continue;
3583                    }
3584                    selected_indices.push(fragment_index);
3585                }
3586            }
3587            for wall_seed in wall_seeds {
3588                let fragments = &fragments_by_carrier[index];
3589                let nearest_containing = fragments
3590                    .iter()
3591                    .enumerate()
3592                    .filter(|(_, fragment)| {
3593                        parameter_point_in_face(&fragment_as_trim(fragment), wall_seed, 1e-8)
3594                            .is_ok_and(|class| class != PolygonClass::Outside)
3595                    })
3596                    .min_by(|(_, first), (_, second)| {
3597                        first
3598                            .test_uv
3599                            .sub(wall_seed)
3600                            .length()
3601                            .total_cmp(&second.test_uv.sub(wall_seed).length())
3602                    })
3603                    .map(|(fragment_index, _)| fragment_index);
3604                // Arrangement fitting can leave the seed just outside every
3605                // fragment by a small amount. Match the reference kernel's
3606                // geometric fallback instead of silently omitting the wall
3607                // fragment and leaving the assembled shell open.
3608                let nearest = if nearest_containing.is_some() {
3609                    nearest_containing
3610                } else {
3611                    let seed_point = split_carriers[index].shells[0].faces[0]
3612                        .surface
3613                        .evaluate(wall_seed.x, wall_seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
3614                    fragments
3615                        .iter()
3616                        .enumerate()
3617                        .min_by(|(_, first), (_, second)| {
3618                            first
3619                                .test_point
3620                                .sub(seed_point)
3621                                .length()
3622                                .total_cmp(&second.test_point.sub(seed_point).length())
3623                        })
3624                        .map(|(fragment_index, _)| fragment_index)
3625                };
3626                if let Some(fragment_index) = nearest {
3627                    let candidate = &fragments_by_carrier[index][fragment_index];
3628                    if outside_source(candidate.test_point)?
3629                        || in_front_of_other_opening(index, candidate.test_point)?
3630                    {
3631                        continue;
3632                    }
3633                    // Void-cross-section guard. On a PLANAR carrier it applies
3634                    // to the GEOMETRIC FALLBACK only: a fragment that
3635                    // genuinely contains this wall seed is wall content by
3636                    // construction (even when un-split it also spans void —
3637                    // the rim weld cuts the hole later), but a merely-nearest
3638                    // fragment must not resurrect a hole in the opening. On a
3639                    // CURVED carrier no later weld cuts the hole, so even a
3640                    // seed-containing fragment gets the strict guard.
3641                    // Extended inward walls are cut by the source as well:
3642                    // a seed must not resurrect the opposite side of a
3643                    // reflex rim merely because its unsigned distance is small.
3644                    if (nearest_containing.is_none() || !carrier_planar || extended_inward)
3645                        && wall_on_skin(candidate.test_point)?
3646                    {
3647                        os_debug!(
3648                            "  wall[{index}.{fragment_index}] seed-hit skipped: void \
3649                             cross-section (planar={carrier_planar}) at ({:.3},{:.3},{:.3})",
3650                            candidate.test_point.x,
3651                            candidate.test_point.y,
3652                            candidate.test_point.z,
3653                        );
3654                        continue;
3655                    }
3656                    let existing = chosen_offsets.iter().cloned().chain(
3657                        selected_indices
3658                            .iter()
3659                            .map(|selected| fragments_by_carrier[index][*selected].clone()),
3660                    );
3661                    if !selected_indices.contains(&fragment_index)
3662                        && !would_overuse_existing_boundary(
3663                            candidate,
3664                            existing,
3665                            &assembly_sources,
3666                            &imprint,
3667                            2e-3,
3668                        )?
3669                    {
3670                        selected_indices.push(fragment_index);
3671                    }
3672                }
3673            }
3674            for fragment_index in selected_indices.iter().copied() {
3675                let mut fragment = fragments_by_carrier[index][fragment_index].clone();
3676                // An OUTWARD wall is the grown body's section less the source:
3677                // none of it lies inside the source. A kept fragment that does
3678                // is the opening's plane carried past a reflex outline edge
3679                // (an L-block opened at its step: the plane beyond the step
3680                // runs inside the block's leg), and the fragments around it
3681                // were cut only where the source meets the plane, so the
3682                // selection cannot tell wall from material there. The boolean
3683                // lane builds that shell exactly; refuse by name to reach it.
3684                if distance < 0.0
3685                    && !extended_inward
3686                    && wall_inside_source_lane_on()
3687                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3688                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3689                {
3690                    return Err(KernelRefusal::unsupported(
3691                        KernelStage::Select,
3692                        "offset_shell_wall_inside_source",
3693                        format!(
3694                            "offset_shell: opening face {}'s outward wall keeps a fragment inside the \
3695                             source at ({:.3},{:.3},{:.3})",
3696                            carrier.source_face_id, fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3697                        ),
3698                    ));
3699                }
3700                // Past a reflex rim the wall closes the cavity on the other
3701                // side of the opening plane, so its normal reverses too.
3702                if extended_inward
3703                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3704                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3705                {
3706                    flip_fragment(&mut fragment)?;
3707                }
3708                chosen_walls.push(fragment);
3709            }
3710        }
3711    }
3712    if debug_enabled() {
3713        for fragment in &chosen_offsets {
3714            os_debug!(
3715                "chosen offset: operand={} src={} test=({:.3},{:.3},{:.3})",
3716                fragment.operand,
3717                carriers[fragment.operand as usize].source_face_id,
3718                fragment.test_point.x,
3719                fragment.test_point.y,
3720                fragment.test_point.z,
3721            );
3722            for (loop_index, loop_record) in fragment.loops.iter().enumerate() {
3723                for coedge in &loop_record.coedges {
3724                    let surface = &fragment.surface;
3725                    let [c0, c1] = coedge.pcurve.domain().unwrap_or([0.0, 0.0]);
3726                    let uv0 = coedge.pcurve.evaluate(c0);
3727                    let uv1 = coedge.pcurve.evaluate(c1);
3728                    if let (Ok(uv0), Ok(uv1)) = (uv0, uv1) {
3729                        let p0 = surface.evaluate(uv0.x, uv0.y);
3730                        let p1 = surface.evaluate(uv1.x, uv1.y);
3731                        if let (Ok(p0), Ok(p1)) = (p0, p1) {
3732                            let kind = match &coedge.source {
3733                                FragmentEdgeSource::Boundary { edge_id, .. } => {
3734                                    format!("bnd:{edge_id}")
3735                                }
3736                                FragmentEdgeSource::SharedBoundary { edge_id, .. } => {
3737                                    format!("sbnd:{edge_id}")
3738                                }
3739                                FragmentEdgeSource::Imprint { piece_id } => {
3740                                    format!("imp:{piece_id}")
3741                                }
3742                                FragmentEdgeSource::Derived { .. } => "derived".to_string(),
3743                            };
3744                            os_debug!(
3745                                "    loop{loop_index} {kind} ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})",
3746                                p0.x, p0.y, p0.z, p1.x, p1.y, p1.z,
3747                            );
3748                        }
3749                    }
3750                }
3751            }
3752        }
3753        for fragment in &chosen_walls {
3754            os_debug!(
3755                "chosen wall: operand={} src={} test=({:.3},{:.3},{:.3})",
3756                fragment.operand,
3757                carriers[fragment.operand as usize].source_face_id,
3758                fragment.test_point.x,
3759                fragment.test_point.y,
3760                fragment.test_point.z,
3761            );
3762        }
3763    }
3764    // A re-run must omit something this pass did not, or it replays this pass
3765    // exactly and recurses until the stack overflows: only supports not
3766    // already omitted count. A carrier riding an omitted support's id (a
3767    // synthetic carrier the omission did not remove) reading shadowed is
3768    // refused by name instead.
3769    let already_omitted = newly_shadowed.iter().filter(|id| shadowed_supports.contains(id)).copied().collect::<Vec<_>>();
3770    newly_shadowed.retain(|id| !shadowed_supports.contains(id));
3771    if newly_shadowed.is_empty() && !already_omitted.is_empty() {
3772        let mut faces = already_omitted;
3773        faces.sort_unstable();
3774        return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::SHADOW_RETRY_STALLED, format!(
3775            "offset_shell: a carrier built for the already omitted source face(s) {faces:?} reads shadowed \
3776             over its whole extent, so omitting it again cannot change the construction"
3777        )));
3778    }
3779    if !newly_shadowed.is_empty() {
3780        let mut omitted = shadowed_supports.clone();
3781        omitted.extend(newly_shadowed.iter().copied());
3782        os_debug!(
3783            "re-running without shadowed offset supports {:?} (omitted before: {:?})",
3784            newly_shadowed,
3785            shadowed_supports
3786        );
3787        // What this pass sampled belongs to carriers the next pass may not
3788        // build.
3789        shadowed_points.clear();
3790        profile::lap(&mut clock, profile::SELECT);
3791        let cascaded = !shadowed_supports.is_empty();
3792        let rebuilt = offset_shell_impl(
3793            source,
3794            opening_face_ids,
3795            distance,
3796            body,
3797            extend_oblique_carriers,
3798            extension_fired,
3799            reflex_rebuilds,
3800            &omitted,
3801            cavity_bounds,
3802            every_seeded_piece,
3803            shadowed_points,
3804            omitted_supports,
3805            vacated_notes,
3806        );
3807        let rebuilt = rebuilt?;
3808        if cascaded {
3809            refuse_a_cascade_that_kept_the_cavity(source, opening_face_ids, distance, &rebuilt.solid)?;
3810        }
3811        return Ok(rebuilt);
3812    }
3813    if chosen_offsets.is_empty() && !shadowed_supports.is_empty() {
3814        if matches!(body, Body::Shell) {
3815            if let Some(witness) = cavity_witness(source, opening_face_ids, distance)? {
3816                if !witness.bounds.is_subset(cavity_bounds) {
3817                    let mut bounds = cavity_bounds.clone();
3818                    bounds.extend(witness.bounds.iter().copied());
3819                    os_debug!(
3820                        "every skin read shadowed, but ({:.4}, {:.4}, {:.4}) lies {:.6} from every retained face: re-running with faces {:?} kept",
3821                        witness.point.x, witness.point.y, witness.point.z, witness.clearance, bounds
3822                    );
3823                    shadowed_points.clear();
3824                    profile::lap(&mut clock, profile::SELECT);
3825                    return offset_shell_impl(
3826                        source,
3827                        opening_face_ids,
3828                        distance,
3829                        body,
3830                        extend_oblique_carriers,
3831                        extension_fired,
3832                        reflex_rebuilds,
3833                        &HashSet::default(),
3834                        &bounds,
3835                        every_seeded_piece,
3836                        shadowed_points,
3837                        omitted_supports,
3838                        vacated_notes,
3839                    );
3840                }
3841                return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_cavity_unbuilt", format!(
3842                    "offset_shell: a cavity remains at this distance (the point ({:.4}, {:.4}, {:.4}) is {:.4} from \
3843                     every retained face, past the shell distance {distance}), but every offset skin around it \
3844                     reads as covered by another face, so it could not be built; returning the solid unchanged \
3845                     would be wrong — use a smaller shell distance",
3846                    witness.point.x, witness.point.y, witness.point.z, witness.clearance
3847                )));
3848            }
3849            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3850                return Ok(unchanged);
3851            }
3852        }
3853        let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3854        omitted.sort_unstable();
3855        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_all_shadowed", format!(
3856            "offset_shell: no retained face keeps any offset skin once the shadowed offsets of \
3857             source faces {omitted:?} are omitted — the solid is nowhere thicker than twice the \
3858             shell distance, so there is no cavity to shell"
3859        )));
3860    }
3861    if chosen_offsets.is_empty() {
3862        // NO SKIN, NONE SHADOWED (`BREP_OFFSET_SHELL_EMPTY_CAVITY`, default on; `=0` restores): every offset
3863        // skin lies wholly outside the solid, so none was selected, though no support read
3864        // shadowed (a cone r 3 h 4 open at its base at wall 2.5: its offset cone's own apex falls
3865        // below the opening plane). That is the empty cavity the shadowed branch above answers
3866        // with the solid unchanged; it is answered the same way, on the same two readings: no
3867        // witness of a cavity, and no point of the solid farther than the wall from every
3868        // retained face.
3869        if matches!(body, Body::Shell) && empty_cavity_any_enabled() && cavity_witness(source, opening_face_ids, distance)?.is_none() {
3870            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3871                os_debug!("no offset skin was selected and no cavity remains: the solid is its own shell");
3872                return Ok(unchanged);
3873            }
3874        }
3875        return Err(KernelRefusal::internal(KernelStage::Select, "offset_shell_no_boundary", "offset_shell: carrier intersections produced no offset boundary"));
3876    }
3877    // Opening-wall fragments can overlap at dense carrier junctions. The
3878    // seed-time guard above handles geometric containment; this final pass
3879    // mirrors the topology-level rule and counts exact fragment edge sources.
3880    let mut boundary_use_count = HashMap::<[i64; 9], usize>::default();
3881    for fragment in &chosen_offsets {
3882        for coedge in fragment
3883            .loops
3884            .iter()
3885            .flat_map(|loop_record| &loop_record.coedges)
3886        {
3887            let key = fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint)?;
3888            *boundary_use_count.entry(key).or_default() += 1;
3889        }
3890    }
3891    let mut manifold_walls = Vec::new();
3892    for fragment in chosen_walls {
3893        let keys = fragment
3894            .loops
3895            .iter()
3896            .flat_map(|loop_record| &loop_record.coedges)
3897            .map(|coedge| fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint))
3898            .collect::<Result<Vec<_>, _>>()?;
3899        if !keys
3900            .iter()
3901            .any(|key| boundary_use_count.get(key).copied().unwrap_or(0) >= 2)
3902        {
3903            for key in keys {
3904                *boundary_use_count.entry(key).or_default() += 1;
3905            }
3906            manifold_walls.push(fragment);
3907        }
3908    }
3909    os_debug!(
3910        "manifold walls kept: {} operands={:?}",
3911        manifold_walls.len(),
3912        manifold_walls
3913            .iter()
3914            .map(|fragment| fragment.operand)
3915            .collect::<Vec<_>>(),
3916    );
3917    let mut chosen_walls = manifold_walls;
3918    // A part of the selected cavity skin with no path to an opening wall is a
3919    // SEALED hollow; named only if the assembly then refuses.
3920    let sealed = if sealed_hollow_on() && body == Body::Shell {
3921        sealed_skins(&chosen_offsets, &chosen_walls, &assembly_sources, &imprint, |fragment| {
3922            carriers[fragment.operand as usize].source_face_id
3923        })?
3924    } else {
3925        Vec::new()
3926    };
3927    // EVERY SKIN SEALED (`BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE`, default on; `=0` restores): no selected
3928    // skin reaches an opening, so the cavity is a closed void below them and each opening face
3929    // stays as it is. Its wall fragments were cut by the skins' carriers PAST the cavity's own
3930    // end (the 8 x 8 pyramid cut at 4, shelled open at its top at 1.9: the sides' offsets cross
3931    // at z 3.75 and their mirrored continuations cut the opening in a square 0.25 across, which
3932    // the wall selection dropped as the cavity's mouth and nothing filled). The opening faces
3933    // are kept whole from the source instead of as wall fragments.
3934    // A skin with an edge cut by an opening's wall carrier reaches that opening, whatever the
3935    // fragment connectivity reads (a pinched lemon shelled through both caps reads sealed by it).
3936    let reaches_an_opening = || {
3937        chosen_offsets.iter().flat_map(|fragment| fragment.loops.iter().flat_map(|loop_record| &loop_record.coedges)).any(|coedge| {
3938            let FragmentEdgeSource::Imprint { piece_id } = &coedge.source else { return false };
3939            imprint.pieces.iter().find(|piece| piece.id == *piece_id).is_some_and(|piece| {
3940                piece.support_faces.iter().any(|key| carriers.get(key.operand as usize).is_some_and(|carrier| carrier.kind == OffsetFaceRole::Wall))
3941            })
3942        })
3943    };
3944    // ... or whose edge lies on an opening face (a carrier reaching its opening plane meets it
3945    // along its own boundary, not an imprint).
3946    let touches_an_opening = || -> Result<bool, KernelRefusal> {
3947        let openings = source.shells.iter().flat_map(|shell| &shell.faces).filter(|face| opening_face_ids.contains(&face.id)).collect::<Vec<_>>();
3948        let band = 1e-7 * crate::solid_scale(source).max(1.0);
3949        for (_, middle) in sealed.iter().flat_map(|skin| &skin.edge_middles) {
3950            for face in &openings {
3951                let Ok(foot) = crate::project_point_to_surface(&face.surface, *middle) else { continue };
3952                if foot.distance <= band
3953                    && parameter_point_in_face(face, Vec2 { x: foot.u, y: foot.v }, 1e-9).or_refuse(KernelStage::Select, "parameter_point_in_face")? != PolygonClass::Outside
3954                {
3955                    return Ok(true);
3956                }
3957            }
3958        }
3959        Ok(false)
3960    };
3961    let all_sealed = sealed_openings_whole_on()
3962        && !chosen_offsets.is_empty()
3963        && sealed.iter().map(|skin| skin.fragments).sum::<usize>() == chosen_offsets.len()
3964        && !reaches_an_opening()
3965        && !touches_an_opening()?;
3966    if all_sealed {
3967        os_debug!("every selected skin is sealed: the openings stay whole");
3968        chosen_walls.clear();
3969    }
3970    if !sealed.is_empty() {
3971        os_debug!(
3972            "sealed skins: {:?}",
3973            sealed.iter().map(|skin| (&skin.sources, skin.centre, skin.edge_middles.len())).collect::<Vec<_>>()
3974        );
3975    }
3976
3977    profile::lap(&mut clock, profile::SELECT);
3978    let stage_clock = web_time::Instant::now();
3979    // The offset BODY has no source face in it: it is the skins (and the held
3980    // faces) alone, oriented as the source is, so nothing is flipped either.
3981    let source_fragments = if body == Body::Whole {
3982        Vec::new()
3983    } else {
3984        fragment_solid(source, SOURCE_OPERAND, &empty_imprint())?
3985    };
3986    os_debug!("stage: source fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
3987    let mut selected = source_fragments
3988        .into_iter()
3989        .filter(|fragment| retained.contains(&fragment.source_face_id) || (all_sealed && opening_face_ids.contains(&fragment.source_face_id)))
3990        .collect::<Vec<_>>();
3991    let mut face_images = selected
3992        .iter()
3993        .map(|fragment| OffsetShellFaceImageRecord {
3994            role: OffsetFaceRole::Source,
3995            source_face_id: fragment.source_face_id,
3996        })
3997        .collect::<Vec<_>>();
3998    if distance < 0.0 {
3999        for fragment in &mut selected {
4000            flip_fragment(fragment)?;
4001        }
4002    }
4003    if distance > 0.0 && body == Body::Shell {
4004        for fragment in &mut chosen_offsets {
4005            flip_fragment(fragment)?;
4006        }
4007    }
4008    face_images.extend(
4009        chosen_offsets
4010            .iter()
4011            .map(|fragment| OffsetShellFaceImageRecord {
4012                role: OffsetFaceRole::Offset,
4013                source_face_id: carriers[fragment.operand as usize].source_face_id,
4014            }),
4015    );
4016    face_images.extend(
4017        chosen_walls
4018            .iter()
4019            .map(|fragment| OffsetShellFaceImageRecord {
4020                role: OffsetFaceRole::Wall,
4021                source_face_id: carriers[fragment.operand as usize].source_face_id,
4022            }),
4023    );
4024    selected.extend(chosen_offsets);
4025    selected.extend(chosen_walls);
4026    // `BREP_OFFSET_THIN_SKIN_PAD`: the same fixed 2e-3 floor as the skin band
4027    // welded the 1e-3 rim of box-paper-thin into points (every rim edge
4028    // degenerate, the rim eight one-face shells, the volume short by the
4029    // rim's 0.072); a thin inward shell's weld is held to a quarter of it.
4030    let mut assembly_weld = 2e-3f64.max(scale * 5e-5);
4031    if thin_skin_pad_enabled() && distance > 0.0 {
4032        assembly_weld = assembly_weld.min(0.25 * distance.abs());
4033    }
4034    let mut solid = profile::detail("assemble_open_fragments", || assemble_open_fragments(
4035        selected,
4036        &assembly_sources,
4037        &imprint,
4038        assembly_weld,
4039    ))?;
4040    os_debug!("stage: assembled open fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
4041    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
4042    os_debug!("stage: oriented {:.3}s", stage_clock.elapsed().as_secs_f64());
4043    let connector_images = profile::detail("complete_sharp_offset_connectors", || complete_sharp_offset_connectors(
4044        &mut solid,
4045        source,
4046        &face_images,
4047        distance,
4048        2e-3f64.max(scale * 5e-5),
4049    ))?;
4050    os_debug!(
4051        "sharp connector completion added {} faces ({:.3}s)",
4052        connector_images.len(),
4053        stage_clock.elapsed().as_secs_f64()
4054    );
4055    if !connector_images.is_empty() {
4056        // Wall fragments were arranged before the sharp seam was closed, so
4057        // their prospective inner boundary was an open chain. Rebuild the
4058        // wall from the now-closed source/offset cycles instead of retaining
4059        // that pre-connector fragment.
4060        for shell in &mut solid.shells {
4061            shell.faces.retain(|face| {
4062                !matches!(
4063                    face_images
4064                        .get(face.id.saturating_sub(1) as usize)
4065                        .map(|image| image.role),
4066                    Some(OffsetFaceRole::Wall)
4067                )
4068            });
4069        }
4070        solid.shells.retain(|shell| !shell.faces.is_empty());
4071    }
4072    face_images.extend(connector_images);
4073    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
4074    // Weld curved-face offset rims that the wall fragmentation left orphaned
4075    // into their coplanar opening cap (cylinder / straight-hole shells). This
4076    // is the seam-rim consistency step the offset pipeline previously lacked.
4077    let welded_rims = profile::detail("weld_coplanar_orphan_rims", || weld_coplanar_orphan_rims(&mut solid, 2e-3f64.max(scale * 5e-5)))?;
4078    os_debug!("welded {welded_rims} coplanar orphan rims into opening caps");
4079    // A rim that is not a circle: a free-form or non-iso rim whose offset image
4080    // falls short of the opening. It runs after every earlier weld because it
4081    // only ever sees rims none of them closed.
4082    let rim_band = profile::detail("weld_free_form_rim_bands", || weld_free_form_rim_bands(
4083        &mut solid,
4084        &mut face_images,
4085        &carriers,
4086        source,
4087        2e-3f64.max(scale * 5e-5),
4088    ))?;
4089    let rim_bands = rim_band.welded;
4090    os_debug!("welded {rim_bands} free-form rim bands");
4091    // Weld leftover coaxial coplanar rim PAIRS (a through-hole's exposed wall
4092    // thickness at each opening) into new planar annulus faces.
4093    let pair_rims =
4094        profile::detail("weld_coplanar_rim_pair_annuli", || weld_coplanar_rim_pair_annuli(&mut solid, &mut face_images, 2e-3f64.max(scale * 5e-5)))?;
4095    os_debug!("welded {pair_rims} coplanar rim pairs into annulus walls");
4096    if debug_enabled() {
4097        for (shell_index, shell) in solid.shells.iter().enumerate() {
4098            for face in &shell.faces {
4099                os_debug!(
4100                    "POSTWELD shell {} face {} same_sense={} loops={}",
4101                    shell_index,
4102                    face.id,
4103                    face.same_sense,
4104                    face.loops.len()
4105                );
4106                for (loop_index, loop_record) in face.loops.iter().enumerate() {
4107                    let walk = loop_record
4108                        .coedges
4109                        .iter()
4110                        .map(|coedge| {
4111                            let spin = (|| -> Result<f64, KernelRefusal> {
4112                                let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
4113                                let a = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.45).or_refuse(KernelStage::Sew, "evaluate")?;
4114                                let b = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.55).or_refuse(KernelStage::Sew, "evaluate")?;
4115                                let pa = face.surface.evaluate(a.x, a.y).or_refuse(KernelStage::Sew, "evaluate")?;
4116                                let pb = face.surface.evaluate(b.x, b.y).or_refuse(KernelStage::Sew, "evaluate")?;
4117                                Ok(pa.cross(pb).z)
4118                            })()
4119                            .unwrap_or(f64::NAN);
4120                            format!(
4121                                "{}{}(spin{:+.0})",
4122                                if coedge.forward { "+" } else { "-" },
4123                                coedge.edge_id,
4124                                spin.signum()
4125                            )
4126                        })
4127                        .collect::<Vec<_>>();
4128                    os_debug!("    loop {} {:?}", loop_index, walk);
4129                }
4130            }
4131        }
4132    }
4133    let completion_carriers = carriers.iter().collect::<Vec<_>>();
4134    let completion_tolerance = 2e-3f64.max(scale * 5e-5);
4135    // Unify geometric duplicate arc records BEFORE completion: a ring that is
4136    // already covered by both its faces (frustum + apex cap) must not read as
4137    // an open boundary, or completion papers over it with duplicate faces.
4138    let duplicate_welds = profile::detail("weld_duplicate_one_use_arcs", || weld_duplicate_one_use_arcs(&mut solid, completion_tolerance))?;
4139    os_debug!("welded {duplicate_welds} duplicate one-use boundary arcs");
4140    if debug_enabled() {
4141        let mut use_counts = HashMap::<u64, usize>::default();
4142        for coedge in solid
4143            .shells
4144            .iter()
4145            .flat_map(|shell| &shell.faces)
4146            .flat_map(|face| &face.loops)
4147            .flat_map(|loop_record| &loop_record.coedges)
4148        {
4149            *use_counts.entry(coedge.edge_id).or_default() += 1;
4150        }
4151        let open = use_counts.values().filter(|count| **count == 1).count();
4152        os_debug!(
4153            "assembled: faces={} open_edges={open}",
4154            solid
4155                .shells
4156                .iter()
4157                .map(|shell| shell.faces.len())
4158                .sum::<usize>()
4159        );
4160    }
4161    let completed_images = profile::detail("complete_opening_boundary_cycles", || complete_opening_boundary_cycles(
4162        &mut solid,
4163        &completion_carriers,
4164        &face_images,
4165        completion_tolerance,
4166    ))?;
4167    os_debug!("completion added {} faces", completed_images.len());
4168    face_images.extend(completed_images);
4169    let solid = profile::detail("merge_same_surface_faces_open", || merge_same_surface_faces_open(&solid, (1e-7f64).max(scale * 1e-9)))?;
4170    let assembly_tolerance = 2e-3f64.max(scale * 5e-5);
4171    // No faceted fallback here: an offset shell must be made of real analytic
4172    // surfaces. Failing loudly beats silently returning a tessellated BREP
4173    // with destroyed face provenance.
4174    // A shell the rim band lane recognized but could not close fails here as it
4175    // always did; the refusal now carries the lane's reason.
4176    let finalized = profile::detail("finalize_assembled_solid", || finalize_assembled_solid(solid, assembly_tolerance)).map_err(|error| {
4177        match &rim_band.decline {
4178            Some(reason) => error.with_message(|message| format!("{message}; offset_shell: {reason}")),
4179            None => error,
4180        }
4181    });
4182    let mut solid = match finalized {
4183        Ok(solid) => solid,
4184        Err(error) => {
4185            os_debug!("finalize_assembled_solid: {}", error.message);
4186            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
4187                let retried = offset_shell_impl(
4188                    source,
4189                    opening_face_ids,
4190                    distance,
4191                    body,
4192                    extend_oblique_carriers,
4193                    extension_fired,
4194                    reflex_rebuilds,
4195                    shadowed_supports,
4196                    cavity_bounds,
4197                    true,
4198                    shadowed_points,
4199                    omitted_supports,
4200                    vacated_notes,
4201                );
4202                if retried.is_ok() {
4203                    return retried;
4204                }
4205            }
4206            if let Some((index, own, other, thickness)) = sealing_distance(
4207                &sealed,
4208                source,
4209                &retained_faces_with_edges,
4210                distance,
4211                offset_skin_tolerance,
4212            )? {
4213                let skin = &sealed[index];
4214                let bounding = skin.sources.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
4215                return Err(KernelRefusal::unsupported(KernelStage::Sew, refusals::SEALED_HOLLOW, format!(
4216                    "offset_shell: at this distance the cavity splits — a hollow bounded by the offsets of \
4217                     source faces {bounding} near ({:.4}, {:.4}, {:.4}) is sealed off from the opening, and a \
4218                     sealed hollow could not be assembled here. It is closed off where the offsets of source \
4219                     faces {own} and {other} cross, which they do from {:.4} up ({thickness:.4} of material \
4220                     between them); below {:.4} it opens into the rest of the cavity, so use a shell distance \
4221                     below that",
4222                    skin.centre.x,
4223                    skin.centre.y,
4224                    skin.centre.z,
4225                    0.5 * thickness,
4226                    0.5 * thickness,
4227                )));
4228            }
4229            return Err(error);
4230        }
4231    };
4232    profile::detail("reconstruct_analytic_shell", || crate::offset_retrim::reconstruct_analytic_shell(&mut solid))?;
4233    if exact_planar_pcurves_on() {
4234        // Only the faces the offset BUILT: a retained source face keeps the
4235        // source's own trims, so the shell and its source still agree there
4236        // (a cavity read as source less shell cancels what they share).
4237        let built = solid
4238            .shells
4239            .iter()
4240            .flat_map(|shell| &shell.faces)
4241            .filter(|face| face_images.get(face.id.saturating_sub(1) as usize).is_some_and(|image| !matches!(image.role, OffsetFaceRole::Source)))
4242            .map(|face| face.id)
4243            .collect::<HashSet<u64>>();
4244        let replaced = exact_planar_pcurves(&mut solid, &built, (1e-7f64).max(scale * 1e-8))?;
4245        os_debug!("exact planar pcurves: {replaced} coedge(s) re-derived from their edges");
4246    }
4247    if rim_bands + pair_rims > 0 || !inward_extended_walls.is_empty() {
4248        // Rim welds and extended reflex walls join independently-oriented skins;
4249        // put the whole finalized manifold on one normal convention so the
4250        // shell reports its exact wall volume (coplanar-only shells keep
4251        // their assembled sense).
4252        profile::detail("coheres_face_normals", || coheres_face_normals(&mut solid))?;
4253    }
4254    let solid = solid;
4255    profile::lap(&mut clock, profile::ASSEMBLY);
4256    face_images = solid
4257        .shells
4258        .iter()
4259        .flat_map(|shell| &shell.faces)
4260        .map(|face| {
4261            face_images
4262                .get(face.id.saturating_sub(1) as usize)
4263                .cloned()
4264                .ok_or_else(|| "offset_shell: merged face lost provenance".to_string())
4265        })
4266        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Sew, "offset_shell_merged_face_lost_provenance")?;
4267    // A bore's end ring carries the bore wall's provenance whichever
4268    // construction built it (the opening's fragmentation or the rim-pair
4269    // weld), so its name does not depend on the path the rims took.
4270    let bore_rings = claim_bore_end_rings(&solid, &mut face_images)?;
4271    os_debug!("{bore_rings} bore end rings took the bore wall's provenance");
4272    // Honesty gate: a real rim left one-use is a hole in the shell that the
4273    // degenerate marking hides from `validate()` (degenerate edges are allowed
4274    // to be face-local). Refuse such a result instead of shipping a
4275    // non-watertight solid as valid. A rim is a CLOSED edge whose interior
4276    // sweeps measurably away from its seam vertex — a genuine circle, not a
4277    // legitimate pole point placeholder (which stays one-use by design).
4278    let mut rim_use_counts = HashMap::<u64, usize>::default();
4279    for coedge in solid
4280        .shells
4281        .iter()
4282        .flat_map(|shell| &shell.faces)
4283        .flat_map(|face| &face.loops)
4284        .flat_map(|loop_record| &loop_record.coedges)
4285    {
4286        *rim_use_counts.entry(coedge.edge_id).or_default() += 1;
4287    }
4288    if debug_enabled() {
4289        for (shell_index, shell) in solid.shells.iter().enumerate() {
4290            for face in &shell.faces {
4291                let role = face_images
4292                    .get(face.id.saturating_sub(1) as usize)
4293                    .map(|image| image.role);
4294                let c = face.surface.evaluate(0.5, 0.5).unwrap_or_default();
4295                os_debug!(
4296                    "DUMPFACE shell {} face {} affine={} role={:?} loops={} center=({:.3},{:.3},{:.3})",
4297                    shell_index, face.id, face.surface.is_affine().unwrap_or(false), role,
4298                    face.loops.len(), c.x, c.y, c.z
4299                );
4300                for (li, lp) in face.loops.iter().enumerate() {
4301                    let ids = lp.coedges.iter().map(|c| c.edge_id).collect::<Vec<_>>();
4302                    os_debug!("    loop {} edges {:?}", li, ids);
4303                }
4304            }
4305        }
4306        for edge in &solid.edges {
4307            let uses = rim_use_counts.get(&edge.id).copied().unwrap_or(0);
4308            let s = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4309            let m = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4310            let q = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * 0.25).or_refuse(KernelStage::Sew, "evaluate")?;
4311            os_debug!(
4312                "DUMPEDGE edge {} uses={} closed={} deg={} cpts={} cdeg={} knots={:?} start=({:.3},{:.3},{:.3}) q=({:.3},{:.3},{:.3}) mid=({:.3},{:.3},{:.3})",
4313                edge.id, uses, edge.start_vertex_id == edge.end_vertex_id, edge.degenerate,
4314                edge.curve.control_points.len(), edge.curve.degree, edge.curve.knots,
4315                s.x, s.y, s.z, q.x, q.y, q.z, m.x, m.y, m.z
4316            );
4317        }
4318    }
4319    for edge in &solid.edges {
4320        if rim_use_counts.get(&edge.id).copied().unwrap_or(0) != 1
4321            || edge.start_vertex_id != edge.end_vertex_id
4322        {
4323            continue;
4324        }
4325        let anchor = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4326        let sweep_threshold = 1e-4f64.max(scale * 1e-6);
4327        let sweeps = [0.25, 0.5, 0.75].into_iter().any(|fraction| {
4328            edge.curve
4329                .evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction)
4330                .map(|point| point.sub(anchor).length() > sweep_threshold)
4331                .unwrap_or(false)
4332        });
4333        if sweeps {
4334            if debug_enabled() {
4335                let rim_mid = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4336                os_debug!(
4337                    "PROBE orphan rim edge {} anchor=({:.4},{:.4},{:.4}) mid=({:.4},{:.4},{:.4})",
4338                    edge.id,
4339                    anchor.x,
4340                    anchor.y,
4341                    anchor.z,
4342                    rim_mid.x,
4343                    rim_mid.y,
4344                    rim_mid.z
4345                );
4346                for (shell_index, shell) in solid.shells.iter().enumerate() {
4347                    for face in &shell.faces {
4348                        let uses_rim = face
4349                            .loops
4350                            .iter()
4351                            .flat_map(|l| &l.coedges)
4352                            .any(|c| c.edge_id == edge.id);
4353                        let affine = face.surface.is_affine().unwrap_or(false);
4354                        let on = edge_on_surface(edge, &face.surface, 2e-3f64.max(scale * 5e-5))
4355                            .unwrap_or(false);
4356                        let proj = project_point_to_surface(&face.surface, rim_mid).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
4357                        let contains = if on {
4358                            parameter_point_in_face(
4359                                face,
4360                                Vec2 {
4361                                    x: proj.u,
4362                                    y: proj.v,
4363                                },
4364                                2e-3f64.max(scale * 5e-5),
4365                            ).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside
4366                        } else {
4367                            false
4368                        };
4369                        if on || uses_rim {
4370                            os_debug!(
4371                                "  face {} shell {} affine={} uses_rim={} on_surf={} proj_dist={:.5} contains={}",
4372                                face.id, shell_index, affine, uses_rim, on, proj.distance, contains
4373                            );
4374                        }
4375                    }
4376                }
4377            }
4378            // The pieces a single seed missed leave their outlines one-use
4379            // here as at the assembly's own exit: the same retry answers it.
4380            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
4381                let retried = offset_shell_impl(
4382                    source,
4383                    opening_face_ids,
4384                    distance,
4385                    body,
4386                    extend_oblique_carriers,
4387                    extension_fired,
4388                    reflex_rebuilds,
4389                    shadowed_supports,
4390                    cavity_bounds,
4391                    true,
4392                    shadowed_points,
4393                    omitted_supports,
4394                    vacated_notes,
4395                );
4396                if retried.is_ok() {
4397                    return retried;
4398                }
4399            }
4400            return Err(refusals::unwelded_curved_rim(edge.id, anchor).into());
4401        }
4402    }
4403    // The shell's single exit. An offset skin that crosses another wall, or
4404    // folds through itself where the source turned tighter than the distance,
4405    // leaves a body that validates and measures — so it is asked here, and
4406    // repaired or refused by name rather than returned.
4407    let mut solid = solid;
4408    // Face-local rim construction and planar merging can reuse wire IDs.
4409    // Reserve every existing ID, then replace only duplicates so the completed
4410    // body can cross the arena/buffer ingestion boundary. These IDs have no
4411    // external references; face/edge identities and provenance stay intact.
4412    let mut loop_ids = HashSet::default();
4413    let mut coedge_ids = HashSet::default();
4414    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
4415        for wire in &face.loops {
4416            loop_ids.insert(wire.id);
4417            coedge_ids.extend(wire.coedges.iter().map(|coedge| coedge.id));
4418        }
4419    }
4420    let mut seen_loops = HashSet::default();
4421    let mut seen_coedges = HashSet::default();
4422    let mut next_loop = 1;
4423    let mut next_coedge = 1;
4424    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
4425        for wire in &mut face.loops {
4426            if !seen_loops.insert(wire.id) {
4427                while !loop_ids.insert(next_loop) { next_loop += 1; }
4428                wire.id = next_loop;
4429            }
4430            for coedge in &mut wire.coedges {
4431                if !seen_coedges.insert(coedge.id) {
4432                    while !coedge_ids.insert(next_coedge) { next_coedge += 1; }
4433                    coedge.id = next_coedge;
4434                }
4435            }
4436        }
4437    }
4438    let solid = profile::detail("accept_offset_result", || super::acceptance::accept_offset_result(solid))?;
4439    profile::lap(&mut clock, profile::ACCEPTANCE);
4440    Ok(OffsetShellResultRecord { solid, face_images })
4441}
4442
4443/// Run offset shell with stable counters and validation diagnostics suitable
4444/// for automated regressions and UI presentation.
4445pub fn offset_shell_with_diagnostics(
4446    source: &BrepSolid,
4447    opening_face_ids: &[u64],
4448    distance: f64,
4449    tolerances: Option<KernelTolerances>,
4450) -> Result<KernelOutcome<OffsetShellResultRecord>, KernelRefusal> {
4451    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
4452        let mut outcome = offset_shell_with_diagnostics(&scaled.source, opening_face_ids, scaled.distance, tolerances)
4453            .map_err(|error| scaled.refusal(error))?;
4454        outcome.value.solid = scaled.back(&outcome.value.solid, "offset_shell")?;
4455        outcome.diagnostics.count_n("working_scale.fired", 1);
4456        outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
4457        return Ok(outcome);
4458    }
4459    let policy = tolerances.unwrap_or_else(|| KernelTolerances::for_solid(source, 1e-7));
4460    policy.check().or_refuse(KernelStage::Sew, "check")?;
4461    let mut diagnostics = KernelDiagnostics::default();
4462    diagnostics.count_n(
4463        "collect.source_faces",
4464        source
4465            .shells
4466            .iter()
4467            .map(|shell| shell.faces.len() as u64)
4468            .sum(),
4469    );
4470    diagnostics.count_n("collect.opening_faces", opening_face_ids.len() as u64);
4471    diagnostics.measure_max("offset.distance", distance.abs());
4472    diagnostics.measure_max("tolerance.model", policy.model);
4473    // Tally every pcurve fit the shell makes (its own re-trims and any boolean
4474    // it runs) so `pcurve.unmet_floor` reports a trim that stopped at the
4475    // sample ceiling instead of passing it off as one that met the floor.
4476    let fit_scope = crate::PcurveFitScope::open();
4477    // Same for the polyline fits of its carrier×carrier sections, which is
4478    // where a marched rim's accuracy is decided (`geometry/fit.rs`).
4479    let polyline_scope = crate::PolylineFitScope::open();
4480    let result = offset_shell(source, opening_face_ids, distance)?;
4481    fit_scope.close().report_into(&mut diagnostics);
4482    polyline_scope.close().report_into(&mut diagnostics);
4483    // The phase split of the run that just finished (`profile.rs`), in the
4484    // boolean's `timing.<phase>_ms` shape so one reader serves both.
4485    let timings = profile::snapshot();
4486    diagnostics.count_n("shell.attempts", timings.attempts);
4487    for (phase, count) in &timings.carriers {
4488        diagnostics.count_n(format!("shell.{phase}"), *count);
4489    }
4490    for (phase, ms) in &timings.ms {
4491        diagnostics.measure_max(format!("timing.{phase}_ms"), *ms);
4492    }
4493    diagnostics.count_n(
4494        "sew.output_faces",
4495        result
4496            .solid
4497            .shells
4498            .iter()
4499            .map(|shell| shell.faces.len() as u64)
4500            .sum(),
4501    );
4502    diagnostics.count_n("sew.face_images", result.face_images.len() as u64);
4503    let validation = result.solid.validate_detailed(&policy);
4504    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4505    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4506    diagnostics.count_n(
4507        "validate.wire_warnings",
4508        validation.wire_warnings.len() as u64,
4509    );
4510    for warning in validation.wire_warnings {
4511        diagnostics.event(
4512            DiagnosticSeverity::Warning,
4513            KernelStage::Validate,
4514            "validate.uv_wire",
4515            warning.message,
4516        );
4517    }
4518    if !validation.issues.is_empty() {
4519        for issue in &validation.issues {
4520            diagnostics.event(
4521                DiagnosticSeverity::Error,
4522                KernelStage::Validate,
4523                "validate.brep",
4524                issue.message.clone(),
4525            );
4526        }
4527        return Err(KernelRefusal::internal(KernelStage::Validate, "offset_shell_diagnostic_result", format!(
4528            "offset_shell: invalid diagnostic result: {:?}",
4529            validation.issues
4530        )));
4531    }
4532    Ok(KernelOutcome {
4533        value: result,
4534        diagnostics,
4535    })
4536}
4537
4538/// Whether a wall fragment lies wholly in the wall's surplus: it has an edge on
4539/// the wall carrier's own outline (`Boundary` of operand `wall_operand`) and no
4540/// edge imprinted by the SOURCE solid, whose rim every genuine opening-wall
4541/// region borders. `cut_by_source` answers whether an imprint piece has the
4542/// source among its two support faces.
4543pub fn wall_surplus_beyond_the_sections(
4544    fragment: &FaceFragmentRecord,
4545    wall_operand: u8,
4546    cut_by_source: impl Fn(u64) -> bool,
4547) -> bool {
4548    let mut on_outline = false;
4549    for coedge in fragment.loops.iter().flat_map(|record| &record.coedges) {
4550        match &coedge.source {
4551            FragmentEdgeSource::Boundary { operand, .. } if *operand == wall_operand => on_outline = true,
4552            FragmentEdgeSource::Boundary { operand, .. } | FragmentEdgeSource::SharedBoundary { operand, .. }
4553                if *operand == SOURCE_OPERAND =>
4554            {
4555                return false;
4556            }
4557            FragmentEdgeSource::Imprint { piece_id } => {
4558                if cut_by_source(*piece_id) {
4559                    return false;
4560                }
4561            }
4562            _ => {}
4563        }
4564    }
4565    on_outline
4566}
4567
4568
4569/// `BREP_OFFSET_SHELL_CASCADE_OMISSION` (default on; `=0` restores): an inward
4570/// shell judges a carrier that reads shadowed at every fragment's test point
4571/// by its true skin instead ([`fragments_holding_true_skin`]). One test point
4572/// cannot speak for a fragment that is partly skin: a reported cylinder boss model's
4573/// root fillets bound the cavity's bulge toward the boss mouth at every
4574/// distance past the boss limit (checked with
4575/// `scripts/offset_cavity_volume.py`), and were dropped as shadowed. A carrier
4576/// holding no skin at all may then be omitted even after an earlier omission.
4577/// `BREP_OFFSET_ABUT_COPLANAR_CARRIERS` (default on; `=0` restores): see
4578/// [`abut_coplanar_offset_carriers`].
4579fn abut_coplanar_carriers_on() -> bool {
4580    switch!("BREP_OFFSET_ABUT_COPLANAR_CARRIERS", true)
4581}
4582
4583/// Two retained planar faces on ONE plane with the same outward sense (the
4584/// matching side walls of two pockets) have offsets on one plane too, and each
4585/// carrier is continued past its trim to its mitre — so across the material
4586/// between them (a divider thinner than 2d) the two carriers OVERLAP. Every
4587/// carrier crossing that plane then imprints two partly overlapping copies of
4588/// one cut, which the arrangement cannot use: the frame's offset over two
4589/// pockets lost all its cuts once the divider's own (shadowed) offsets stopped
4590/// splitting them, and the shell refused.
4591///
4592/// Such a pair is cut back to abut at the middle of its overlap, each keeping
4593/// its own side: the union of the two, the plane the cavity is bounded by, is
4594/// unchanged, and each keeps its own source face. Planar degree-(1, 1)
4595/// carriers whose trim is a parameter rectangle, overlapping along one
4596/// direction and matching along the other; any other pair is left as it was.
4597/// Run only in a pass after the cascade omitted a shadowed carrier: until then
4598/// that carrier cuts both copies at the same points and the overlap is
4599/// harmless (the outward divider builds exactly in its first pass, and cut
4600/// back there it gained a 342-area membrane). Returns how many pairs were cut
4601/// back.
4602fn abut_coplanar_offset_carriers(carriers: &mut [Carrier], tolerance: f64) -> Result<usize, KernelRefusal> {
4603    struct Plate {
4604        index: usize,
4605        origin: Vec3,
4606        axes: [Vec3; 2],
4607        lengths: [f64; 2],
4608        normal: Vec3,
4609        height: f64,
4610    }
4611    let plate = |index: usize, carrier: &Carrier| -> Result<Option<Plate>, KernelRefusal> {
4612        if !matches!(carrier.kind, OffsetFaceRole::Offset) {
4613            return Ok(None);
4614        }
4615        let face = &carrier.solid.shells[0].faces[0];
4616        let surface = &face.surface;
4617        if surface.degree_u != 1 || surface.degree_v != 1 || surface.control_points.len() != 2 || surface.control_points[0].len() != 2 {
4618            return Ok(None);
4619        }
4620        if surface.control_points.iter().flatten().any(|point| (point.w - 1.0).abs() > 1e-12) || face.loops.len() != 1 {
4621            return Ok(None);
4622        }
4623        let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
4624        let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
4625        // A rectangular trim: four straight pcurves, each running along u or
4626        // along v, whose box lies inside the domain.
4627        if face.loops[0].coedges.len() != 4 {
4628            return Ok(None);
4629        }
4630        let mut uv_box = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY];
4631        for coedge in &face.loops[0].coedges {
4632            if coedge.pcurve.degree != 1 || coedge.pcurve.control_points.len() != 2 {
4633                return Ok(None);
4634            }
4635            let (Ok(a), Ok(b)) = (coedge.pcurve.control_points[0].point(), coedge.pcurve.control_points[1].point()) else { return Ok(None) };
4636            let (du, dv) = ((b.x - a.x).abs(), (b.y - a.y).abs());
4637            if du.min(dv) > 1e-12 * du.max(dv) {
4638                return Ok(None);
4639            }
4640            let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
4641            for t in [a, b] {
4642                let uv = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
4643                uv_box = [uv_box[0].min(uv.x), uv_box[1].max(uv.x), uv_box[2].min(uv.y), uv_box[3].max(uv.y)];
4644            }
4645        }
4646        let span = (u1 - u0).abs().max(v1 - v0).max(1.0);
4647        let [bu0, bu1, bv0, bv1] = uv_box;
4648        let box_area = (bu1 - bu0) * (bv1 - bv0);
4649        if bu0 < u0 - 1e-9 * span || bu1 > u1 + 1e-9 * span || bv0 < v0 - 1e-9 * span || bv1 > v1 + 1e-9 * span
4650            || !(box_area > 0.0)
4651            || (parameter_space_area(face).or_refuse(KernelStage::Refine, "parameter_space_area")?.abs() - box_area).abs() > 1e-9 * box_area
4652        {
4653            return Ok(None);
4654        }
4655        let origin = surface.evaluate(bu0, bv0).or_refuse(KernelStage::Refine, "evaluate")?;
4656        let along_u = surface.evaluate(bu1, bv0).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4657        let along_v = surface.evaluate(bu0, bv1).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4658        let lengths = [along_u.length(), along_v.length()];
4659        if lengths[0] <= tolerance || lengths[1] <= tolerance {
4660            return Ok(None);
4661        }
4662        let axes = [along_u.scale(1.0 / lengths[0]), along_v.scale(1.0 / lengths[1])];
4663        if axes[0].dot(axes[1]).abs() > 1e-9 {
4664            return Ok(None);
4665        }
4666        // A rectangle, not a bilinear quadrilateral: the fourth corner closes it.
4667        let far = surface.evaluate(bu1, bv1).or_refuse(KernelStage::Refine, "evaluate")?;
4668        if far.sub(origin.add(along_u).add(along_v)).length() > tolerance {
4669            return Ok(None);
4670        }
4671        let sense = if face.same_sense { 1.0 } else { -1.0 };
4672        let normal = axes[0].cross(axes[1]).scale(sense);
4673        Ok(Some(Plate { index, origin, axes, lengths, normal, height: normal.dot(origin) }))
4674    };
4675    let mut abutted = 0usize;
4676    'pairs: loop {
4677        let plates = carriers
4678            .iter()
4679            .enumerate()
4680            .map(|(index, carrier)| plate(index, carrier))
4681            .collect::<Result<Vec<_>, _>>()?
4682            .into_iter()
4683            .flatten()
4684            .collect::<Vec<_>>();
4685        for (i, first) in plates.iter().enumerate() {
4686            for second in &plates[i + 1..] {
4687                if first.normal.dot(second.normal) < 1.0 - 1e-12 || (first.height - second.height).abs() > tolerance {
4688                    continue;
4689                }
4690                // ONE plane: every corner of the second on the first's plane, so a
4691                // slightly tilted pair (equal near one point) is not cut back.
4692                let on_plane = |point: Vec3| (first.normal.dot(point) - first.height).abs() <= tolerance;
4693                let second_far = second.origin.add(second.axes[0].scale(second.lengths[0]));
4694                let second_up = second.origin.add(second.axes[1].scale(second.lengths[1]));
4695                if !on_plane(second.origin) || !on_plane(second_far) || !on_plane(second_up)
4696                    || !on_plane(second_far.add(second.axes[1].scale(second.lengths[1])))
4697                    || !on_plane(first.origin.add(first.axes[0].scale(first.lengths[0])).add(first.axes[1].scale(first.lengths[1])))
4698                {
4699                    continue;
4700                }
4701                // The second's extent in the first's frame, along each axis.
4702                let corners = [
4703                    second.origin,
4704                    second.origin.add(second.axes[0].scale(second.lengths[0])),
4705                    second.origin.add(second.axes[1].scale(second.lengths[1])),
4706                    second.origin.add(second.axes[0].scale(second.lengths[0])).add(second.axes[1].scale(second.lengths[1])),
4707                ];
4708                let range = |axis: usize| {
4709                    corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), corner| {
4710                        let at = corner.sub(first.origin).dot(first.axes[axis]);
4711                        (low.min(at), high.max(at))
4712                    })
4713                };
4714                let ranges = [range(0), range(1)];
4715                // The second must be a rectangle aligned with the first.
4716                if second.axes.iter().any(|axis| axis.dot(first.axes[0]).abs().min(axis.dot(first.axes[1]).abs()) > 1e-9) {
4717                    continue;
4718                }
4719                for (along, across) in [(0usize, 1usize), (1, 0)] {
4720                    let (low, high) = ranges[along];
4721                    let (across_low, across_high) = ranges[across];
4722                    if (across_low).abs() > tolerance || (across_high - first.lengths[across]).abs() > tolerance {
4723                        continue;
4724                    }
4725                    let overlap = (high.min(first.lengths[along]), low.max(0.0));
4726                    if overlap.0 - overlap.1 <= tolerance {
4727                        continue;
4728                    }
4729                    let first_holds = low >= -tolerance && high <= first.lengths[along] + tolerance;
4730                    let second_holds = low <= tolerance && high >= first.lengths[along] - tolerance;
4731                    if first_holds || second_holds {
4732                        continue;
4733                    }
4734                    let cut = 0.5 * (overlap.0 + overlap.1);
4735                    let point = first.origin.add(first.axes[along].scale(cut));
4736                    let first_low_side = 0.5 * first.lengths[along] < cut;
4737                    clip_plate(&mut carriers[first.index], point, first.axes[along], first_low_side)?;
4738                    clip_plate(&mut carriers[second.index], point, first.axes[along], !first_low_side)?;
4739                    abutted += 1;
4740                    continue 'pairs;
4741                }
4742            }
4743        }
4744        break;
4745    }
4746    Ok(abutted)
4747}
4748
4749/// Cut a planar degree-(1, 1) carrier back at the plane through `point`
4750/// normal to `axis`, keeping the side below it (`keep_low`) or above it, and
4751/// rebuild its trim as the new parameter rectangle.
4752fn clip_plate(carrier: &mut Carrier, point: Vec3, axis: Vec3, keep_low: bool) -> Result<(), KernelRefusal> {
4753    let face = carrier.solid.shells[0].faces[0].clone();
4754    let surface = &face.surface;
4755    let mut uv_box = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY];
4756    for coedge in &face.loops[0].coedges {
4757        let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
4758        for t in [a, b] {
4759            let uv = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
4760            uv_box = [uv_box[0].min(uv.x), uv_box[1].max(uv.x), uv_box[2].min(uv.y), uv_box[3].max(uv.y)];
4761        }
4762    }
4763    let [u0, u1, v0, v1] = uv_box;
4764    let origin = surface.evaluate(u0, v0).or_refuse(KernelStage::Refine, "evaluate")?;
4765    let du = surface.evaluate(u1, v0).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4766    let dv = surface.evaluate(u0, v1).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4767    let level = point.sub(origin).dot(axis);
4768    let (mut ru, mut rv) = ([u0, u1], [v0, v1]);
4769    // Which parameter runs along the axis, and where it reaches the cut.
4770    if du.dot(axis).abs() > dv.dot(axis).abs() {
4771        let at = u0 + (u1 - u0) * level / du.dot(axis);
4772        let low_end_is_u0 = du.dot(axis) > 0.0;
4773        if keep_low == low_end_is_u0 { ru[1] = at } else { ru[0] = at }
4774        if ru[0] > ru[1] { ru.swap(0, 1) }
4775    } else {
4776        let at = v0 + (v1 - v0) * level / dv.dot(axis);
4777        let low_end_is_v0 = dv.dot(axis) > 0.0;
4778        if keep_low == low_end_is_v0 { rv[1] = at } else { rv[0] = at }
4779        if rv[0] > rv[1] { rv.swap(0, 1) }
4780    }
4781    let corner = |u: f64, v: f64| -> Result<crate::Vec4, KernelRefusal> {
4782        Ok(crate::Vec4::from_point(surface.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?, 1.0))
4783    };
4784    let clipped = crate::NurbsSurface::new(
4785        1,
4786        1,
4787        vec![ru[0], ru[0], ru[1], ru[1]],
4788        vec![rv[0], rv[0], rv[1], rv[1]],
4789        vec![vec![corner(ru[0], rv[0])?, corner(ru[0], rv[1])?], vec![corner(ru[1], rv[0])?, corner(ru[1], rv[1])?]],
4790    )
4791    .or_refuse(KernelStage::Refine, "new")?;
4792    let mut rebuilt = face;
4793    rebuilt.surface = clipped;
4794    carrier.solid = full_rectangle_face(&carrier.solid, &rebuilt)?;
4795    Ok(())
4796}
4797
4798/// `BREP_OFFSET_PER_EDGE_OPENING_PADS` (default on; `=0` restores): a planar outward
4799/// opening wall's outline is offset per edge, each by its own junction's pad
4800/// (`outward_wall_pads_per_edge`), not all by the worst one's.
4801fn per_edge_opening_pads_on() -> bool {
4802    switch!("BREP_OFFSET_PER_EDGE_OPENING_PADS", true)
4803}
4804
4805/// `BREP_OFFSET_NONUNIFORM_SLID_TRIM` (default on; `=0` restores): an outward planar
4806/// carrier whose extension is NOT uniform also takes its full rectangle when
4807/// its slid trim falls short of its narrowest pad.
4808fn nonuniform_slid_trim_on() -> bool {
4809    switch!("BREP_OFFSET_NONUNIFORM_SLID_TRIM", true)
4810}
4811
4812fn cascade_omission_enabled() -> bool {
4813    switch!("BREP_OFFSET_SHELL_CASCADE_OMISSION", true)
4814}
4815
4816/// A cascade of omissions must leave the deepest point of the true cavity
4817/// hollow: a carrier omitted on a test point that did not stand for its
4818/// fragment would show as material there.
4819fn refuse_a_cascade_that_kept_the_cavity(
4820    source: &BrepSolid,
4821    opening_face_ids: &[u64],
4822    distance: f64,
4823    result: &BrepSolid,
4824) -> Result<(), KernelRefusal> {
4825    let Some(witness) = cavity_witness(source, opening_face_ids, distance)? else {
4826        return Ok(());
4827    };
4828    let scale = crate::solid_scale(source).max(1.0);
4829    let class = classify_point(witness.point, result, 1e-8 * scale).or_refuse(KernelStage::Select, "classify_point")?.class;
4830    if class == PointClass::In {
4831        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
4832            "offset_shell: omitting offsets that read shadowed only after earlier omissions leaves material at \
4833             ({:.4}, {:.4}, {:.4}), which is {:.4} from every retained face, past the shell distance {distance}; \
4834             the cavity there could not be built — use a smaller shell distance",
4835            witness.point.x, witness.point.y, witness.point.z, witness.clearance
4836        )));
4837    }
4838    Ok(())
4839}
4840
4841/// `BREP_OFFSET_SHELL_CAVITY_WITNESS` (default on; `=0` restores): [`cavity_witness`].
4842fn retained_faces_of<'a>(retained: &[(&'a FaceRecord, Vec<&'a EdgeRecord>)]) -> Vec<&'a FaceRecord> {
4843    retained.iter().map(|(face, _)| *face).collect()
4844}
4845
4846fn sealed_openings_whole_on() -> bool {
4847    switch!("BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE", true)
4848}
4849
4850fn empty_cavity_any_enabled() -> bool {
4851    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
4852}
4853
4854fn cavity_witness_enabled() -> bool {
4855    switch!("BREP_OFFSET_SHELL_CAVITY_WITNESS", true)
4856}
4857
4858/// A point of the solid farther than the shell distance from every retained
4859/// face, and the faces nearest it, whose skins bound that cavity.
4860#[derive(Debug)]
4861pub struct CavityWitness {
4862    pub(super) point: Vec3,
4863    pub clearance: f64,
4864    pub bounds: HashSet<u64>,
4865}
4866
4867/// Looks for the cavity the shadow reading says is not there. A fragment's
4868/// single test point can read shadowed while most of the fragment is real skin
4869/// (a reported cylinder boss model at 4.8: the r 0.2 bore of a cylinder r 5, one uncut
4870/// fragment whose test point lies 4.72 from a boss wall), and a cavity that
4871/// thin falls between the 12³ cells of [`empty_cavity_shell`], which then
4872/// returned the source as a success.
4873///
4874/// Distance to the retained faces is 1-Lipschitz, so any cavity's maximum is
4875/// climbed to from the samples that read highest: the best cell centres start
4876/// a pattern search that stays inside the solid. It is a search, not a proof;
4877/// what it cannot miss is a cavity whose ridge those starts climb.
4878pub fn cavity_witness(
4879    source: &BrepSolid,
4880    opening_face_ids: &[u64],
4881    distance: f64,
4882) -> Result<Option<CavityWitness>, KernelRefusal> {
4883    if !cavity_witness_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
4884        return Ok(None);
4885    }
4886    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
4887    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
4888    if retained.is_empty() {
4889        return Ok(None);
4890    }
4891    // Each face's own edges: a foot off the trim falls back on the edges it is
4892    // given, and the whole solid's would read a wall as near as any rim.
4893    let edge_by_id = source.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
4894    let retained = retained
4895        .into_iter()
4896        .map(|face| {
4897            let edges = face
4898                .loops
4899                .iter()
4900                .flat_map(|loop_record| &loop_record.coedges)
4901                .filter_map(|coedge| edge_by_id.get(&coedge.edge_id).copied())
4902                .collect::<Vec<_>>();
4903            (face, edges)
4904        })
4905        .collect::<Vec<_>>();
4906    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
4907    let scale = crate::solid_scale(source).max(1.0);
4908    let classify_tolerance = 1e-8 * scale;
4909    let margin = 1e-6 * scale;
4910    let readings = |point: Vec3| -> Result<Vec<(u64, f64)>, KernelRefusal> {
4911        retained
4912            .iter()
4913            .map(|(face, edges)| {
4914                // `BREP_OFFSET_RULED_MITER`: a ruled face reads the mitered metric the skin test
4915                // reads it by, or the witness finds a cavity past a rim the skins never reach.
4916                let ruled = if super::carriers::ruled_miter_on() { super::carriers::ruled_miter_distance(face, edges, point, &retained_faces_of(&retained))? } else { None };
4917                Ok((face.id, match ruled {
4918                    Some(mitered) => mitered,
4919                    None => distance_to_trimmed_face(face, edges, point)?,
4920                }))
4921            })
4922            .collect()
4923    };
4924    let clearance = |values: &[(u64, f64)]| values.iter().map(|(_, value)| *value).fold(f64::INFINITY, f64::min);
4925    let inside = |point: Vec3| -> Result<bool, KernelRefusal> {
4926        Ok(classify_point(point, source, classify_tolerance).or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In)
4927    };
4928    const CELLS: usize = 12;
4929    const STARTS: usize = 24;
4930    const MOVES: usize = 160;
4931    let span = high.sub(low);
4932    let mut starts = Vec::new();
4933    for i in 0..CELLS {
4934        for j in 0..CELLS {
4935            for k in 0..CELLS {
4936                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
4937                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
4938                if inside(point)? {
4939                    starts.push((clearance(&readings(point)?), point));
4940                }
4941            }
4942        }
4943    }
4944    starts.sort_by(|a, b| b.0.total_cmp(&a.0));
4945    starts.truncate(STARTS);
4946    const DIRECTIONS: [(f64, f64, f64); 14] = [
4947        (1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0),
4948        (1.0, 1.0, 1.0), (-1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, -1.0, 1.0),
4949        (1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0),
4950    ];
4951    let first_step = span.x.max(span.y).max(span.z) / CELLS as f64;
4952    let mut footless = None;
4953    for (start_clearance, start) in starts {
4954        let (mut point, mut best, mut step) = (start, start_clearance, first_step);
4955        for _ in 0..MOVES {
4956            if step < 1e-6 * scale {
4957                break;
4958            }
4959            let mut moved = false;
4960            for (x, y, z) in DIRECTIONS {
4961                let length = (x * x + y * y + z * z).sqrt();
4962                let next = Vec3::new(point.x + step * x / length, point.y + step * y / length, point.z + step * z / length);
4963                let value = clearance(&readings(next)?);
4964                if value > best && inside(next)? {
4965                    (point, best, moved) = (next, value, true);
4966                    break;
4967                }
4968            }
4969            if !moved {
4970                step *= 0.5;
4971            }
4972        }
4973        if best > distance + margin {
4974            // The climb ends on the ridge, where every face around it ties.
4975            // Nudged off the ridge, still inside the cavity, each point has one
4976            // nearest face, which counts if its foot lands inside its trim (a
4977            // tie through a face's rim is that edge, not its offset). The faces
4978            // that wrap the cavity collect the votes; a fillet seen only
4979            // through the mouth of a boss does not.
4980            let nudge = 0.5 * (best - distance);
4981            let mut votes = HashMap::<u64, usize>::default();
4982            for (x, y, z) in DIRECTIONS {
4983                let length = (x * x + y * y + z * z).sqrt();
4984                let near = Vec3::new(point.x + nudge * x / length, point.y + nudge * y / length, point.z + nudge * z / length);
4985                let values = readings(near)?;
4986                let Some((id, _)) = values.iter().min_by(|a, b| a.1.total_cmp(&b.1)).copied() else { continue };
4987                let Some((face, _)) = retained.iter().find(|(face, _)| face.id == id) else { continue };
4988                if foot_inside_trim(face, near)? {
4989                    *votes.entry(id).or_default() += 1;
4990                }
4991            }
4992            let most = votes.values().copied().max().unwrap_or(0);
4993            let bounds = votes.iter().filter(|(_, count)| **count * 2 >= most).map(|(id, _)| *id).collect::<HashSet<_>>();
4994            let witness = CavityWitness { point, clearance: best, bounds };
4995            if !witness.bounds.is_empty() {
4996                return Ok(Some(witness));
4997            }
4998            footless = Some(witness);
4999        }
5000    }
5001    Ok(footless)
5002}
5003
5004/// The box of the solid's vertices and face control points; `None` when a
5005/// control point cannot be read.
5006fn control_hull(source: &BrepSolid, faces: &[&FaceRecord]) -> Option<(Vec3, Vec3)> {
5007    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
5008    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
5009    for vertex in &source.vertices {
5010        low = Vec3::new(low.x.min(vertex.point.x), low.y.min(vertex.point.y), low.z.min(vertex.point.z));
5011        high = Vec3::new(high.x.max(vertex.point.x), high.y.max(vertex.point.y), high.z.max(vertex.point.z));
5012    }
5013    for control in faces.iter().flat_map(|face| face.surface.control_points.iter().flatten()) {
5014        let point = control.point().ok()?;
5015        low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
5016        high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
5017    }
5018    Some((low, high))
5019}
5020
5021/// `BREP_OFFSET_SHELL_EMPTY_CAVITY` (default on; `=0` restores): [`empty_cavity_shell`].
5022pub(super) fn empty_cavity_enabled() -> bool {
5023    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
5024}
5025
5026
5027/// An INWARD shell whose every retained face's offset skin is shadowed: the
5028/// cavity, the points of the solid farther than `distance` from every retained
5029/// face, is empty, so the shell is the solid itself, every face its own
5030/// `Source` image (brep-bench shell/box-walls-meeting: the box 10 x 8 x 6
5031/// shelled by 4 open at its top, whose y walls' offsets meet in the plane
5032/// y = 4, was refused "no retained face keeps any offset skin ... there is no
5033/// cavity to shell"; the case reads the box, 480 and 376).
5034///
5035/// The shadow reading is checked before the solid is returned: on a 12³ grid
5036/// of cell centres over the solid's control hull, no point the solid
5037/// classifies Inside may lie farther than `distance` (plus 1e-9 of the
5038/// solid's size) from every retained face. A point that does means the
5039/// cavity is not empty, and the refusal stands.
5040fn empty_cavity_shell(
5041    source: &BrepSolid,
5042    opening_face_ids: &[u64],
5043    distance: f64,
5044) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
5045    if !empty_cavity_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
5046        return Ok(None);
5047    }
5048    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
5049    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
5050    if retained.is_empty() {
5051        return Ok(None);
5052    }
5053    let edges = source.edges.iter().collect::<Vec<_>>();
5054    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
5055    let scale = crate::solid_scale(source).max(1.0);
5056    let tolerance = 1e-9 * scale;
5057    const CELLS: usize = 12;
5058    let span = high.sub(low);
5059    let mut inside = 0usize;
5060    for i in 0..CELLS {
5061        for j in 0..CELLS {
5062            for k in 0..CELLS {
5063                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
5064                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
5065                let class = classify_point(point, source, tolerance * 10.0).or_refuse(KernelStage::Select, "classify_point")?.class;
5066                if class != PointClass::In {
5067                    continue;
5068                }
5069                inside += 1;
5070                let mut nearest = f64::INFINITY;
5071                for face in &retained {
5072                    nearest = nearest.min(distance_to_trimmed_face(face, &edges, point)?);
5073                    if nearest <= distance + tolerance {
5074                        break;
5075                    }
5076                }
5077                if nearest > distance + tolerance {
5078                    os_debug!(
5079                        "empty cavity declined: ({:.4}, {:.4}, {:.4}) lies {nearest:.6} from every retained face",
5080                        point.x, point.y, point.z
5081                    );
5082                    return Ok(None);
5083                }
5084            }
5085        }
5086    }
5087    if inside == 0 {
5088        return Ok(None);
5089    }
5090    os_debug!("empty cavity: every retained skin is shadowed and {inside} sampled interior points lie within the distance");
5091    let face_images = faces
5092        .iter()
5093        .map(|face| OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
5094        .collect();
5095    Ok(Some(OffsetShellResultRecord { solid: source.clone(), face_images }))
5096}
5097
5098/// `BREP_OFFSET_THIN_PAD_RECTANGLE` (default on; `=0` restores): a thin-skin
5099/// padded plane with a curved outline is trimmed by its padded rectangle, not
5100/// by its slid outline (see the carrier construction).
5101fn thin_pad_rectangle_enabled() -> bool {
5102    switch!("BREP_OFFSET_THIN_PAD_RECTANGLE", true)
5103}
5104
5105/// `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): [`thin_skin_pad`].
5106fn thin_skin_pad_enabled() -> bool {
5107    switch!("BREP_OFFSET_THIN_SKIN_PAD", true)
5108}
5109
5110
5111/// The pad of an INWARD planar carrier whose shell is thinner than the
5112/// fragmenter's graze band: `None` otherwise.
5113///
5114/// Cause (the 10 × 8 × 6 box shelled 0.001 open at its top, brep-bench
5115/// shell/box-paper-thin, read 0.1653 against 0.2959 with an open mesh): each
5116/// carrier is its source face moved 0.001, and its neighbours' skins cut it
5117/// 0.001 inside its rim, with both ends 0.001 from the carrier's corners. The
5118/// imprint's pcurves are right (v = 0.001), but `fragment_face_arranged` lets a
5119/// CUT endpoint join a boundary corner image within `arrangement_tolerance ·
5120/// 100` (1.2e-3 on a 10 × 8 chart) with no 3D check, so both ends moved onto
5121/// the corners, the cut lay on the rim and was dropped as its duplicate
5122/// ("drop cut chain 6 as duplicate of boundary chain 0"). Padded past its rims,
5123/// the carrier's corners are far from every section's ends; the surplus
5124/// strips beyond the sections are outside the source or shadowed by the
5125/// neighbours and are dropped by the ordinary selection.
5126///
5127/// Thin: `distance` under 2e-3 of the solid's size (the band is 1e-4 of a
5128/// chart's diagonal, a chart at most the solid's size). The pad is 4e-3 of
5129/// the size plus the distance.
5130///
5131/// The same switch holds the selection's skin band and the assembly's weld to
5132/// a quarter of an inward distance: both had a fixed 2e-3 floor, twice this
5133/// shell's thickness (see `offset_skin_tolerance` and `assembly_weld`).
5134fn thin_skin_pad(source: &BrepSolid, face: &FaceRecord, distance: f64) -> Result<Option<f64>, KernelRefusal> {
5135    if !thin_skin_pad_enabled() || distance <= 0.0 || !face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
5136        return Ok(None);
5137    }
5138    let size = crate::solid_scale(source).max(1e-9);
5139    if distance >= 2e-3 * size {
5140        return Ok(None);
5141    }
5142    Ok(Some(4e-3 * size + distance))
5143}