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