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