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