Skip to main content

brep_offset/offset/offset_shell/
pipeline.rs

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