Skip to main content

brep_boolean/csg/fragment/
face_split.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3use super::types::{Chain, ChainSource};
4use super::sampling::{enforce_boundary_crossing_parity, refine_near_hints, sag_refine_chain, sample_boundary_chain, sample_chain, trimmed_curve};
5pub use super::loops::{build_loop, edge_for, interior_points, pcurve_for, point_in_polygon, segment_tag, tag_chain, vertex_point};
6pub use super::loop_split::{fragments_agree, loop_split_census, loop_split_face, loop_split_mode, LoopSplitMode};
7/// `BREP_BOUNDARY_VERTEX_HINTS=0|off` restores boundary sampling that is blind
8/// to the face's other loops (see the BOUNDARY-VERTEX HINTS note in
9/// `fragment_face`).
10fn boundary_vertex_hints_enabled() -> bool {
11    switch!("BREP_BOUNDARY_VERTEX_HINTS", true)
12}
13
14/// Imprint id-index shared across every face of one operand. Built ONCE in
15/// `fragment_solid`; without it each face rebuilt `pieces_by_id`/`vertex_by_id`
16/// over ALL pieces (O(F*(P + P*V))) and linear-scanned `by_face`. Lookup-only,
17/// so every face gets the identical pieces/points the scans returned.
18/// `BREP_FRAGMENT_SMALL_RING` (default on; `0`/`off` restores the old
19/// thinning): a chain smaller than the arrangement's junction radius keeps its
20/// shape (see SMALL RING in `fragment_face_arranged`) instead of collapsing
21/// onto its ends.
22pub fn small_ring_enabled() -> bool {
23    switch!("BREP_FRAGMENT_SMALL_RING", true)
24}
25
26/// `BREP_BRIDGE_T_JUNCTION_ANCHOR` (default on; `=0` restores): a cut end lying
27/// on the run of another cut chain is a T-junction the arrangement nodes
28/// exactly, not half of a broken cut, so it is no bridge candidate. Without
29/// this, two independent T-ends close together on one chain read as a broken
30/// junction and are welded to their midpoint, or refused as a missing piece.
31fn bridge_t_junction_anchor_enabled() -> bool {
32    switch!("BREP_BRIDGE_T_JUNCTION_ANCHOR", true)
33}
34
35/// `BREP_BRIDGE_BOUNDARY_T_JUNCTION_ANCHOR` (default on; `=0` restores): a cut end lying on
36/// the run of one of the face's own BOUNDARY chains is a T-junction with the
37/// trim, which the arrangement nodes like any cut meeting the boundary, so it is
38/// no bridge candidate either. Cause (a reported box and pin model at 2.51 and
39/// 2.52): on the wall offset x = d, the bore and floor sections end on the
40/// opening edge 0.25 apart. Their other ends lie within the junction radius of
41/// the front offset's section (d - 2.5 = 0.01 from them), which reads them as
42/// anchored, so the two ends on the opening edge read as a broken cut and were
43/// welded to their midpoint, deleting the short bore arc there.
44fn bridge_boundary_t_junction_anchor_enabled() -> bool {
45    switch!("BREP_BRIDGE_BOUNDARY_T_JUNCTION_ANCHOR", true)
46}
47
48/// `BREP_BRIDGE_SKIP_CROSSING_PAIRS` (default on; `=0` restores): two loose cut ends whose
49/// chains cross each other are not a broken cut. The crossing is their
50/// junction, which the arrangement nodes, and its degree-1 pruning drops both
51/// overshoot stubs, so the pair is never bridged. Cause (a reported
52/// box and pin model at 2.54): on the floor offset, the wall and bore sections cross
53/// 0.061 from the wall section's end, inside the junction radius 0.064, so the
54/// overshoot exclusion did not see it; their ends lay 0.066 apart, just past
55/// that radius, so both read as loose and were welded to their midpoint, which
56/// left the loops open.
57fn bridge_skip_crossing_pairs_enabled() -> bool {
58    switch!("BREP_BRIDGE_SKIP_CROSSING_PAIRS", true)
59}
60
61pub struct FragmentIndex<'a> {
62    pub by_face: HashMap<(u8, u64), &'a [u64]>,
63    pub pieces_by_id: HashMap<u64, &'a ImprintPieceRecord>,
64    pub(super) vertex_points: HashMap<u64, Vec3>,
65    pub(super) cosurface_pairs: HashSet<(FaceKey, FaceKey)>,
66}
67
68impl<'a> FragmentIndex<'a> {
69    pub fn build(imprint: &'a ImprintResultRecord) -> Self {
70        let mut by_face: HashMap<(u8, u64), &'a [u64]> = HashMap::default();
71        for entry in &imprint.by_face {
72            // `.entry().or_insert` keeps the FIRST entry, matching the previous
73            // `by_face.iter().find(...)` (keys are unique in practice anyway).
74            by_face
75                .entry((entry.operand, entry.face_id))
76                .or_insert_with(|| entry.piece_ids.as_slice());
77        }
78        FragmentIndex {
79            by_face,
80            cosurface_pairs: imprint.cosurface_pairs.iter()
81                .flat_map(|&(a,b)| [(a,b),(b,a)]).collect(),
82            pieces_by_id: imprint
83                .pieces
84                .iter()
85                .map(|piece| (piece.id, piece))
86                .collect(),
87            vertex_points: imprint
88                .vertices
89                .iter()
90                .map(|vertex| (vertex.id, vertex.point))
91                .collect(),
92        }
93    }
94}
95
96/// Back-compat entry point: builds the imprint index for this single face.
97/// `fragment_solid` builds it once and calls `fragment_face_indexed` directly.
98pub fn fragment_face(
99    solid: &BrepSolid,
100    operand: u8,
101    face: &FaceRecord,
102    imprint: &ImprintResultRecord,
103) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
104    let index = FragmentIndex::build(imprint);
105    let mut profile = FragmentProfile::new();
106    let fragments = fragment_face_indexed(solid, operand, face, &index, &mut profile)?;
107    profile.report(operand);
108    Ok(fragments)
109}
110
111/// The winding the SOURCE face's own outer loop uses in its (u,v) chart:
112/// `Some(true)` when it is negative (clockwise), `Some(false)` when positive,
113/// `None` when the sign cannot be trusted.
114///
115/// `build_loop` orients a rebuilt fragment loop against the arrangement, whose
116/// outer cycles are ALWAYS positive-area (`arrangement.rs`: a cycle goes to
117/// `positive` only when `area > tol²`, and negative cycles become holes), and
118/// reversed it only for `!same_sense` — *material runs counter-clockwise in
119/// (u,v) exactly when `same_sense`*.
120///
121/// That rule is CORRECT and is this kernel's stated invariant: it is what
122/// `validate_uv_wire` checks (`brep/topology/validate.rs`, "wire winding
123/// disagrees with face sense"), what `watertight_tessellation::periodic::trim`
124/// cites as the authority for the same question, and what nine sites in `src/`
125/// compare a winding against. It is also forced by the definitions — with
126/// `n_s = S_u × S_v` and `n_f = same_sense ? n_s : −n_s`, material-on-the-left
127/// projected into the chart with `n_s` up leaves no freedom.
128///
129/// So a face carrying a CW outer loop with `same_sense = true` is MALFORMED,
130/// not merely unusual. This function exists because one arrives anyway: nothing
131/// refuses it on the way in, and `validate_uv_wire`'s verdict is filed under
132/// `ValidationReport::wire_warnings`, which `validate()` does not return — so
133/// every `validate().is_empty()` in the kernel reads clean on it.
134///
135/// Reading the source winding here is DEFENCE IN DEPTH, not a blessing of the
136/// chart: it stops the boolean refusing on such a face and builds the correct
137/// body instead. It does not make the face correct, and the real defect is
138/// upstream in whatever produced it.
139///
140/// Measured on the 2026-09-21 through-tunnel body: five of the stretched
141/// wedge's six faces wind positive, `Box_PZ` winds −1.2334e3 with `same_sense =
142/// true` (the plain box's `Box_PZ` winds +1.2143e3; `TF3` is what flips it).
143/// Rebuilding `Box_PZ` against the arrangement's CCW convention flips every
144/// coedge on it, which is the six same-sense edges the boolean then refuses on.
145///
146/// Restricted to OPEN charts on purpose. On a closed/periodic chart a raw
147/// shoelace is meaningless without the seam unwrap the arrangement scan does,
148/// and that path already has its own material-orientation authority in
149/// `full_span_loop_area`; leaving periodic faces on the old rule keeps this
150/// change to the case it was measured on. `None` also covers a loop with too
151/// few samples or an area too small to carry a reliable sign — the caller then
152/// keeps today's `!same_sense`.
153fn source_loop_winding_negative(face: &FaceRecord) -> Result<Option<bool>, KernelRefusal> {
154    let closed = face
155        .surface
156        .closed_directions()
157        .or_refuse(KernelStage::Fragment, "closed_directions")?;
158    if closed.0 || closed.1 {
159        return Ok(None);
160    }
161    // The OUTER loop is the one bounding the most parameter area; holes wind
162    // against it. Reading `loops[0]` would trust a convention this function
163    // exists to stop trusting.
164    let mut best: Option<f64> = None;
165    for loop_record in &face.loops {
166        let mut points: Vec<Vec2> = Vec::new();
167        for coedge in &loop_record.coedges {
168            let [d0, d1] = coedge
169                .pcurve
170                .domain()
171                .or_refuse(KernelStage::Fragment, "domain")?;
172            const SAMPLES: usize = 24;
173            for step in 0..SAMPLES {
174                let fraction = step as f64 / SAMPLES as f64;
175                // `d0 -> d1` ALWAYS. A pcurve is stored in its coedge's own
176                // traversal direction -- `reverse_fragment` flips `forward` and
177                // calls `pcurve.reversed()` together, and the loop-polygon
178                // builder below walks every pcurve `d0 -> d1` regardless of
179                // `forward`. Consulting `forward` here would reverse those
180                // segments in place and trace a zig-zag: on the plain box's
181                // `Box_NZ` (60.715 x 20 in parameter space) that yields 607.15,
182                // exactly half the 1214.3 the loop actually bounds, and the
183                // sign of a self-intersecting polygon is not the loop's
184                // winding.
185                let t = d0 + (d1 - d0) * fraction;
186                let point = coedge
187                    .pcurve
188                    .evaluate(t)
189                    .or_refuse(KernelStage::Fragment, "evaluate")?;
190                points.push(Vec2 { x: point.x, y: point.y });
191            }
192        }
193        if points.len() < 3 {
194            continue;
195        }
196        let mut area = 0.0;
197        for (index, point) in points.iter().enumerate() {
198            let next = points[(index + 1) % points.len()];
199            area += 0.5 * (crate::polygon::area_term([point.x, point.y], [next.x, next.y]));
200        }
201        if best.map(|current: f64| area.abs() > current.abs()).unwrap_or(true) {
202            best = Some(area);
203        }
204    }
205    // Scale the "is this sign real" floor to the chart, so a millimetre-wide
206    // face is not judged by a millimetre-squared absolute.
207    let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)
208        .or_refuse(KernelStage::Fragment, "new")?
209        .domain();
210    let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)
211        .or_refuse(KernelStage::Fragment, "new")?
212        .domain();
213    let chart = (u_domain[1] - u_domain[0]) * (v_domain[1] - v_domain[0]);
214    let floor = (chart.abs() * 1e-9).max(f64::MIN_POSITIVE);
215    Ok(match best {
216        Some(area) if area.abs() > floor => Some(area < 0.0),
217        _ => None,
218    })
219}
220
221/// A cut against the other operand's coincident copy of an incident face
222/// inherits that already-established face identity. This permits bounded rim
223/// repair without treating an unrelated nearby curve as the same boundary.
224fn boundary_has_cosurface_partner(
225    solid: &BrepSolid,
226    face: FaceKey,
227    boundary_edge: u64,
228    piece: &ImprintPieceRecord,
229    index: &FragmentIndex,
230) -> bool {
231    piece.support_faces.iter().filter(|other| other.operand != face.operand).any(|other| {
232        solid.shells.iter().flat_map(|shell| &shell.faces).any(|neighbour| {
233            neighbour.id != face.face_id
234                && index.cosurface_pairs.contains(&(FaceKey { operand:face.operand, face_id:neighbour.id }, *other))
235                && neighbour.loops.iter().flat_map(|lp| &lp.coedges)
236                    .any(|coedge| coedge.edge_id == boundary_edge)
237        })
238    })
239}
240
241/// Detect a distinct narrow strip before replacing its curves by chords.
242/// Search tolerance only nominates a nearby boundary; positive separation in
243/// model space and parallel interior tangents establish a resolvable strip.
244///
245/// FEATURE SCALE B4 (`BREP_FEATURE_SCALE_FRAGMENT`, default on, `=0` off): a
246/// strip between two CUTS is measured the same way. brep-bench
247/// tangent/hairline-slot: the saw's two walls cross the cube's top 1e-6
248/// apart, under the 1.4e-5 resolution of its 10-wide chart, so the
249/// arrangement read them as one line and the strip between them was never
250/// formed.
251fn thin_boundary_resolution(
252    solid: &BrepSolid,
253    face: &FaceRecord,
254    face_key: FaceKey,
255    piece_ids: &[u64],
256    index: &FragmentIndex,
257    search: f64,
258) -> (Option<(f64, f64)>, bool) {
259    let mut resolution: Option<(f64, f64)> = None;
260    // Whether a feature-scale measure (a near touch, or a strip between two
261    // cuts) found a strip: only then are the image bands narrowed.
262    let mut feature_found = false;
263    let mut take = |strip: Option<(f64, f64)>| {
264        if let Some((arrangement, sampling)) = strip {
265            resolution = Some(match resolution {
266                Some((a, s)) => (a.min(arrangement), s.min(sampling)),
267                None => (arrangement, sampling),
268            });
269        }
270    };
271    let cuts: Vec<&NurbsCurve> = piece_ids
272        .iter()
273        .filter_map(|piece_id| index.pieces_by_id.get(piece_id).and_then(|piece| pcurve_for(piece, face_key).ok()))
274        .collect();
275    for piece_id in piece_ids {
276        let Some(piece) = index.pieces_by_id.get(piece_id) else { continue };
277        let Ok(cut) = pcurve_for(piece, face_key) else { continue };
278        for boundary in face.loops.iter().flat_map(|lp| &lp.coedges) {
279            if boundary_has_cosurface_partner(solid, face_key, boundary.edge_id, piece, index) {
280                continue;
281            }
282            let strip = strip_between(face, &cut, &boundary.pcurve, search);
283            take(match strip {
284                None if crate::feature_scale::fragment_enabled() => {
285                    let touch = near_touch(face, &cut, &boundary.pcurve, search);
286                    if touch.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
287                        eprintln!("feature_scale: face {} near touch cut p{piece_id} / boundary e{} -> {touch:?}", face.id, boundary.edge_id);
288                    }
289                    feature_found |= touch.is_some();
290                    touch
291                }
292                strip => strip,
293            });
294            if end_gap_enabled() {
295                let gap = end_gap(face, &cut, &boundary.pcurve, search);
296                if gap.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
297                    eprintln!("feature_scale: face {} end gap cut p{piece_id} / boundary e{} -> {gap:?}", face.id, boundary.edge_id);
298                }
299                feature_found |= gap.is_some();
300                take(gap);
301            }
302        }
303    }
304    if crate::feature_scale::fragment_enabled() {
305        for (i, cut) in cuts.iter().enumerate() {
306            for other in &cuts[i + 1..] {
307                let strip = strip_between(face, cut, other, search);
308                let found = strip.or_else(|| near_touch(face, cut, other, search));
309                if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
310                    eprintln!("feature_scale: face {} cut pair {i} {} -> {} {found:?}", face.id, if strip.is_some() { "strip" } else { "near touch" }, i);
311                }
312                feature_found |= found.is_some();
313                take(found);
314            }
315        }
316    }
317    (resolution, feature_found)
318}
319
320/// FEATURE SCALE, end gap (`BREP_FEATURE_SCALE_END_GAP`, default on, `=0` off): an
321/// open cut that ENDS near a boundary edge of the face without ending on it.
322/// `near_touch` declines every approach at a cut's end, because a marched cut
323/// stops a few 1e-6 short of the boundary it ends on and resolving to that
324/// slack kept its end from snapping to its junction. A section that ends at a
325/// genuine vertex a small but real distance off the boundary is another
326/// thing: a cube against a copy turned 0.01 deg has a section on the cube's
327/// side that ends where the turned top edge pierces it, 3.9e-4 below the
328/// side's own top edge, inside the chart's wide bands (1.4e-3 image band and
329/// 2.1e-2 junction radius on a 10-wide face), and the arrangement joined that
330/// end to the top edge: a vertex the solid does not have, and a valid shell
331/// 1.9e-5 out in volume. An end is a gap when it stands off the boundary by
332/// more than the weld floor in model space (so a marched cut's slack is not
333/// one) and within the wide bands in the chart; the face's resolutions are
334/// then taken to that gap, as for a near touch.
335pub fn end_gap_enabled() -> bool {
336    crate::switch!("BREP_FEATURE_SCALE_END_GAP", true)
337}
338
339fn end_gap(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
340    // Planar faces whose cut and boundary are both straight: the regime the
341    // measure was read on. Curved faces and curved trims keep their bands
342    // (fillet corners, pole bridges and rim strips are tuned to them).
343    let straight = |curve: &NurbsCurve| curve.degree == 1 && curve.control_points.len() == 2;
344    if !face.surface.is_affine().ok()? || !straight(cut) || !straight(other) {
345        return None;
346    }
347    let [lo, hi] = cut.domain().ok()?;
348    let start = cut.evaluate(lo).ok()?;
349    let end = cut.evaluate(hi).ok()?;
350    if start.sub(end).length() <= search {
351        return None;
352    }
353    let u_domain = face.surface.domain_u().ok()?;
354    let v_domain = face.surface.domain_v().ok()?;
355    let diagonal = ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
356    let reach = (search * 100.0).max(diagonal * 1.5e-3);
357    let mut found: Option<(f64, f64)> = None;
358    for point in [start, end] {
359        let Ok(foot) = project_point_to_curve(other, point) else { continue };
360        if foot.distance > reach {
361            continue;
362        }
363        let (Ok(here), Ok(there)) = (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) else {
364            continue;
365        };
366        if here.sub(there).length() <= crate::tolerance::WELD_FLOOR {
367            continue;
368        }
369        let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
370        if foot.distance <= identity * 8.0 {
371            continue;
372        }
373        let resolution = (search.min((foot.distance / 128.0).max(identity)), search.min(foot.distance / 8.0));
374        found = Some(match found {
375            Some((a, s)) => (a.min(resolution.0), s.min(resolution.1)),
376            None => resolution,
377        });
378    }
379    found
380}
381
382/// FEATURE SCALE B4, near touch (`BREP_FEATURE_SCALE_FRAGMENT`): the
383/// resolutions a cut needs where it comes closer to `other` than the
384/// arrangement resolves without meeting it. brep-bench
385/// tangent/bore-a-micron-from-the-wall: the bore's circle on each cap passes
386/// 1e-6 inside the rim circle at (5, 0), under the cap's 1.4e-5 resolution, so
387/// the two circles fused there and both cap loops opened. The gaps vary from
388/// 1e-6 to 2 around the circle, which `strip_between` reads as a tangency. The
389/// closest approach is found by 257 samples refined by golden section; it is
390/// a near touch when it lies within `8·search` in the chart yet more than 8e-7
391/// apart in model space and beyond the chart's identity band.
392fn near_touch(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
393    // Curves lie in their control hulls: hulls farther apart than the reach
394    // cannot hold a near touch, and most pairs on a face are that far apart.
395    let hull = |curve: &NurbsCurve| crate::spatial::Aabb::from_curve_controls(curve).ok();
396    if !hull(cut)?.intersects(hull(other)?, search * 8.0) {
397        return None;
398    }
399    let [lo, hi] = cut.domain().ok()?;
400    let [other_lo, other_hi] = other.domain().ok()?;
401    // A cut that ENDS on `other` has no near touch with it, and saying so
402    // takes two projections instead of the search's 417 (brep-bench
403    // boolean/cross-drilled-cube: the Steinmetz arcs of crossing bores meet
404    // at their ends, and this search was 70% of that case's time). The search
405    // below samples the cut's ends exactly, so its closest approach is no
406    // wider in the chart than this end's gap (under 1e-3 of the reach and
407    // the identity band, below any gap it takes as a near touch), and the refined approach then lies
408    // at an open cut's end (`at_end`) or within 8e-7 in model space: None
409    // either way. The gap must be tiny in the chart AND in space (at a pole
410    // the chart's points meet in space while far apart in the chart). A cut
411    // that stops short of a boundary (a marched cut, by a few 1e-6) keeps
412    // the search.
413    let ends_on_other = [lo, hi].into_iter().any(|t| {
414        let Ok(point) = cut.evaluate(t) else { return false };
415        let Ok(foot) = project_point_to_curve(other, point) else { return false };
416        let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
417        if foot.distance > (search * 1e-3).min(identity) {
418            return false;
419        }
420        match (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) {
421            (Ok(here), Ok(there)) => here.sub(there).length() <= 1e-9,
422            _ => false,
423        }
424    });
425    if ends_on_other {
426        return None;
427    }
428    let gap = |parameter: f64| -> Option<(f64, Vec3, Vec3, f64)> {
429        let point = cut.evaluate(parameter).ok()?;
430        let projected = project_point_to_curve(other, point).ok()?;
431        Some((projected.distance, point, projected.point, projected.u))
432    };
433    // A closed curve's ends are a seam, not a junction; an open one's are
434    // where it meets the rest of the arrangement.
435    let closed = |curve: &NurbsCurve, a: f64, b: f64| -> bool {
436        match (curve.evaluate(a), curve.evaluate(b)) {
437            (Ok(start), Ok(end)) => start.sub(end).length() <= search,
438            _ => false,
439        }
440    };
441    let (cut_closed, other_closed) = (closed(cut, lo, hi), closed(other, other_lo, other_hi));
442    const SAMPLES: usize = 256;
443    let step = (hi - lo) / SAMPLES as f64;
444    let mut best: Option<(f64, f64)> = None;
445    for i in 0..=SAMPLES {
446        let parameter = lo + step * i as f64;
447        if let Some((distance, _, _, _)) = gap(parameter) {
448            if best.is_none_or(|(_, d)| distance < d) {
449                best = Some((parameter, distance));
450            }
451        }
452    }
453    let (centre, _) = best?;
454    let (mut a, mut b) = ((centre - step).max(lo), (centre + step).min(hi));
455    let ratio = 0.5 * (5f64.sqrt() - 1.0);
456    for _ in 0..80 {
457        let c = b - ratio * (b - a);
458        let d = a + ratio * (b - a);
459        if gap(c)?.0 < gap(d)?.0 { b = d } else { a = c }
460    }
461    let parameter = 0.5 * (a + b);
462    let (low_gap, point, foot, foot_parameter) = gap(parameter)?;
463    if low_gap > search * 8.0 {
464        return None;
465    }
466    // Only an approach in the middle of both curves is a near touch. A marched
467    // cut stops a few 1e-6 short of the boundary it ends on (its slack past the
468    // trim), and resolving the arrangement to that gap kept its end from
469    // snapping to its junction (r16: eleven boolean fixtures refused).
470    let at_end = |t: f64, a: f64, b: f64| (t - a).abs() <= 0.01 * (b - a) || (b - t).abs() <= 0.01 * (b - a);
471    if (!cut_closed && at_end(parameter, lo, hi)) || (!other_closed && at_end(foot_parameter, other_lo, other_hi)) {
472        return None;
473    }
474    let actual = face.surface.evaluate(point.x, point.y).ok()?;
475    let rim = face.surface.evaluate(foot.x, foot.y).ok()?;
476    if actual.sub(rim).length() <= 8e-7 {
477        return None;
478    }
479    let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
480    if low_gap <= identity * 8.0 {
481        return None;
482    }
483    Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
484}
485
486/// The arrangement and sampling resolutions a strip between `cut` and
487/// `other` (both pcurves on `face`) needs, or `None` when they do not bound a
488/// strip: some sample of `cut` farther than `8·search` from `other`, a
489/// tangent not parallel to it, a sample within 8e-7 of it in model space or
490/// within the chart's identity band, or gaps varying more than fourfold (a
491/// crossing or an isolated tangency).
492fn strip_between(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
493    let [lo, hi] = cut.domain().ok()?;
494    let middle = cut.evaluate((lo + hi) * 0.5).ok()?;
495    let nearest = project_point_to_curve(other, middle).ok()?;
496    if nearest.distance > search * 8.0 { return None; }
497    let mut low_gap = f64::INFINITY;
498    let mut high_gap = 0.0f64;
499    let mut identity = 0.0f64;
500    for fraction in [0.125, 0.25, 0.5, 0.75, 0.875] {
501        let parameter = lo + (hi - lo) * fraction;
502        let cut_sample = cut.derivatives(parameter, 1).ok()?;
503        let point = cut_sample[0];
504        let projected = project_point_to_curve(other, point).ok()?;
505        if projected.distance > search * 8.0 { return None; }
506        let other_sample = other.derivatives(projected.u, 1).ok()?;
507        let a = cut_sample[1];
508        let b = other_sample[1];
509        let lengths = a.length() * b.length();
510        if lengths <= 1e-30 || a.dot(b).abs() < 0.995 * lengths { return None; }
511        let actual = face.surface.evaluate(point.x, point.y).ok()?;
512        let rim = face.surface.evaluate(projected.point.x, projected.point.y).ok()?;
513        if actual.sub(rim).length() <= 8e-7 { return None; }
514        let floor = crate::classification::surface_uv_band(
515            &face.surface, point.x, point.y, 1e-7,
516        );
517        if projected.distance <= floor * 8.0 { return None; }
518        low_gap = low_gap.min(projected.distance);
519        high_gap = high_gap.max(projected.distance);
520        identity = identity.max(floor);
521    }
522    // A crossing or isolated tangency does not describe a strip.
523    if high_gap > low_gap * 4.0 { return None; }
524    Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
525}
526
527fn fragment_face_indexed(
528    solid: &BrepSolid,
529    operand: u8,
530    face: &FaceRecord,
531    index: &FragmentIndex,
532    profile: &mut FragmentProfile,
533) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
534    let face_started = profile.enabled.then(Instant::now);
535    let mut lap_start = face_started;
536    let result = fragment_face_stages(solid, operand, face, index, profile, &mut lap_start);
537    profile.face_done(face.id, face_started);
538    result
539}
540
541fn fragment_face_stages(
542    solid: &BrepSolid,
543    operand: u8,
544    face: &FaceRecord,
545    index: &FragmentIndex,
546    profile: &mut FragmentProfile,
547    lap_start: &mut Option<Instant>,
548) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
549    let face_key = FaceKey {
550        operand,
551        face_id: face.id,
552    };
553    let piece_ids = index
554        .by_face
555        .get(&(operand, face.id))
556        .copied()
557        .unwrap_or(&[]);
558    if piece_ids.is_empty() {
559        profile.uncut_probe_faces += 1;
560        let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
561        let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
562        let uv = Vec2 {
563            x: (u[0] + u[1]) / 2.0,
564            y: (v[0] + v[1]) / 2.0,
565        };
566        let probe_started = profile.enabled.then(Instant::now);
567        let centre_inside = parameter_point_in_face(face, uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
568        if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
569        if !centre_inside {
570            // Trimmed faces need the arrangement path even without cuts to
571            // find a point in their actual outer loop.
572        } else {
573            let mut extra_test_points = Vec::new();
574            for (fu, fv) in [(0.35, 0.35), (0.65, 0.65)] {
575                let candidate = Vec2 {
576                    x: u[0] + (u[1] - u[0]) * fu,
577                    y: v[0] + (v[1] - v[0]) * fv,
578                };
579                let probe_started = profile.enabled.then(Instant::now);
580                let inside = parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
581                if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
582                if inside {
583                    extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
584                }
585            }
586            let untouched = vec![untouched_fragment(face, operand, uv, extra_test_points)?];
587            profile.untouched += profile.lap(lap_start);
588            return Ok(untouched);
589        }
590    }
591    if !piece_ids.is_empty() {
592        profile.cut_faces += 1;
593    }
594    // LOOP SPLIT (`fragment/loop_split.rs`): a face whose pieces are simple is
595    // split loop by loop; `check` runs both paths and returns the
596    // arrangement's; `on` returns the split's where it applies.
597    let mode = loop_split_mode();
598    let mut split_result: Option<Result<Vec<FaceFragmentRecord>, super::loop_split::Decline>> = None;
599    if mode != LoopSplitMode::Off && !piece_ids.is_empty() {
600        let started = profile.enabled.then(Instant::now);
601        let outcome = loop_split_face(solid, operand, face, face_key, piece_ids, index)?;
602        if let Some(started) = started {
603            profile.loop_split += started.elapsed();
604        }
605        match &outcome {
606            Ok(_) => profile.loop_split_faces += 1,
607            Err(_) => profile.loop_split_declined += 1,
608        }
609        if mode == LoopSplitMode::On {
610            if let Ok(fragments) = outcome {
611                *lap_start = profile.enabled.then(Instant::now);
612                return Ok(fragments);
613            }
614        }
615        split_result = Some(outcome);
616        *lap_start = profile.enabled.then(Instant::now);
617    }
618    let arranged = fragment_face_arranged(solid, operand, face, face_key, piece_ids, index, profile, lap_start);
619    // A face no section touches that the arrangement answered with NOTHING is
620    // not gone: it is one fragment, itself, and all it needs is a point of
621    // its own material, found beside its trim (`trim_interior_probe`). The
622    // arrangement keeps every face it does split (a pinched loop into two).
623    if piece_ids.is_empty() && trim_probe_enabled() && matches!(&arranged, Ok(fragments) if fragments.is_empty()) {
624        let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
625        let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
626        if let Some((uv, extra_test_points)) = trim_interior_probe(face, u, v)? {
627            return Ok(vec![untouched_fragment(face, operand, uv, extra_test_points)?]);
628        }
629    }
630    if let Some(split) = split_result {
631        let verdict = match (&split, &arranged) {
632            (Err(decline), _) => format!("declined {decline}"),
633            (Ok(_), Err(refusal)) => format!("MISMATCH split built {} fragments, arrangement refused: {refusal}", split.as_ref().map_or(0, Vec::len)),
634            (Ok(split), Ok(arranged)) => match fragments_agree(split, arranged) {
635                Ok(agreement) => agreement.to_string(),
636                Err(why) => format!("MISMATCH {why}"),
637            },
638        };
639        loop_split_census(|| format!("operand {operand} face {} pieces {} loops {} {verdict}", face.id, piece_ids.len(), face.loops.len()));
640    }
641    arranged
642}
643
644
645#[allow(clippy::too_many_arguments)]
646fn fragment_face_arranged(
647    solid: &BrepSolid,
648    operand: u8,
649    face: &FaceRecord,
650    face_key: FaceKey,
651    piece_ids: &[u64],
652    index: &FragmentIndex,
653    profile: &mut FragmentProfile,
654    lap_start: &mut Option<Instant>,
655) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
656
657    let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
658    let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
659    let diagonal =
660        ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
661    let original_resolution = 1e-7f64.max(diagonal * 1e-6);
662    let (strip_resolution, feature_strip) = thin_boundary_resolution(solid, face, face_key, piece_ids, index, original_resolution);
663    let (arrangement_tolerance, sampling_bound) = strip_resolution
664        .unwrap_or((original_resolution, original_resolution));
665    // FEATURE SCALE B4 (`BREP_FEATURE_SCALE_FRAGMENT`): with a thin strip
666    // between two cuts or a near touch on the face, a chain end is matched to another vertex's image only within
667    // the strip's own sampling bound in the chart and 1e-7 in model space
668    // (`strip_between` admits only strips over 8e-7 wide), not 100
669    // resolutions and 1e-5: the hairline slot's two walls end 1e-6 apart on
670    // the cube's top, and each wall's cut took the other's far end.
671    // Only for a strip a feature-scale measure found: a cut-against-boundary
672    // strip the fragmenter always measured kept its wide bands (narrowing them
673    // too opened loops on revolve ∪ wedge fixtures with coincident side planes).
674    let strip_snap = feature_strip;
675    let (image_band, image_band_3d) = if strip_snap {
676        (sampling_bound, 1e-7)
677    } else {
678        (arrangement_tolerance * 100.0, 1e-5)
679    };
680    let snap_threshold = 0.1 * diagonal;
681    let junction_radius = (arrangement_tolerance * 50.0).max(diagonal * 1.5e-3);
682    // WRAPPED-BAND RE-BASE: a face on a closed direction whose material is the
683    // wrapped COMPLEMENT of its trim hull (two full-wrap rims at the hull
684    // edges, material crossing the seam between them — trial 35's torus face:
685    // rims at v=0.25/1.0, material v∈[0,0.25]) cannot be arranged in the flat
686    // domain rectangle: a cut through the band ends at v=0 while its junction
687    // partner (the split rim vertex) sits at v=1, so every cut dangles, cycle
688    // extraction fails, and the face is dropped wholesale (one-use cascade).
689    // Re-base into the material-coherent frame [hull_high, hull_low+period]:
690    // shift every chain point on the low side of the hull window (+period), so
691    // rims and cuts junction in ONE unwrapped chart, and wrap region test
692    // points back into the domain on exit. Detection mirrors the imprint's
693    // restricted-carrier wrap guard: the hull-complement strip contains no
694    // loop curves, so one sample at its middle decides materiality exactly.
695    // Escape hatch: BREP_BAND_REBASE=0.
696    let band_rebase: [Option<(f64, f64)>; 2] = {
697        let mut rebase = [None, None];
698        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
699        if (closed.0 || closed.1) && std::env::var("BREP_BAND_REBASE").as_deref() != Ok("0") {
700            // Per-coedge hulls on each axis, plus whether any ISO-RIM
701            // (a coedge whose pcurve is near-constant on the axis) sits at a
702            // domain edge — the discriminator for the wrapped-band class.
703            // A seam-straddling boundary band (helmet Face_15, whose source
704            // pcurves are already unwrapped past the domain) has no such rim
705            // and its frame is already coherent; it must NOT be re-based.
706            let mut coverage: [Vec<[f64; 2]>; 2] = [Vec::new(), Vec::new()];
707            let mut edge_rim = [false, false];
708            let mut hull = [
709                [f64::INFINITY, f64::NEG_INFINITY],
710                [f64::INFINITY, f64::NEG_INFINITY],
711            ];
712            for coedge in face
713                .loops
714                .iter()
715                .flat_map(|loop_record| &loop_record.coedges)
716            {
717                let mut extent = [
718                    [f64::INFINITY, f64::NEG_INFINITY],
719                    [f64::INFINITY, f64::NEG_INFINITY],
720                ];
721                for control in &coedge.pcurve.control_points {
722                    if control.w.abs() <= 1e-300 {
723                        continue;
724                    }
725                    let point = [control.x / control.w, control.y / control.w];
726                    for axis in 0..2 {
727                        extent[axis][0] = extent[axis][0].min(point[axis]);
728                        extent[axis][1] = extent[axis][1].max(point[axis]);
729                        hull[axis][0] = hull[axis][0].min(point[axis]);
730                        hull[axis][1] = hull[axis][1].max(point[axis]);
731                    }
732                }
733                for axis in 0..2 {
734                    if !extent[axis][0].is_finite() {
735                        continue;
736                    }
737                    let domain = if axis == 0 { u_domain } else { v_domain };
738                    let span = domain[1] - domain[0];
739                    coverage[axis].push(extent[axis]);
740                    let flat = extent[axis][1] - extent[axis][0] <= 1e-3 * span;
741                    let at_edge = (extent[axis][0] - domain[0]).abs() <= 1e-6 * span
742                        || (extent[axis][1] - domain[1]).abs() <= 1e-6 * span;
743                    if flat && at_edge {
744                        edge_rim[axis] = true;
745                    }
746                }
747            }
748            for axis in 0..2 {
749                if !(if axis == 0 { closed.0 } else { closed.1 }) || !edge_rim[axis] {
750                    continue;
751                }
752                let domain = if axis == 0 { u_domain } else { v_domain };
753                let span = domain[1] - domain[0];
754                // Merge the coverage intervals (clamped into the domain) and
755                // find the largest uncovered gap. The gap contains no boundary
756                // curve, so it is uniformly material or uniformly void — one
757                // sample at its middle decides exactly. A strictly INTERIOR
758                // void gap means the material wraps through the domain edge.
759                let mut intervals: Vec<[f64; 2]> = coverage[axis]
760                    .iter()
761                    .map(|window| {
762                        [window[0].max(domain[0]), window[1].min(domain[1])]
763                    })
764                    .filter(|window| window[1] >= window[0])
765                    .collect();
766                intervals.sort_by(|a, b| a[0].total_cmp(&b[0]));
767                let mut gaps: Vec<[f64; 2]> = Vec::new();
768                let mut reach = domain[0];
769                for window in &intervals {
770                    if window[0] > reach {
771                        gaps.push([reach, window[0]]);
772                    }
773                    reach = reach.max(window[1]);
774                }
775                if reach < domain[1] {
776                    gaps.push([reach, domain[1]]);
777                }
778                let other_mid = (hull[1 - axis][0].max(if axis == 0 {
779                    v_domain[0]
780                } else {
781                    u_domain[0]
782                }) + hull[1 - axis][1].min(if axis == 0 {
783                    v_domain[1]
784                } else {
785                    u_domain[1]
786                })) / 2.0;
787                let mut void: Option<[f64; 2]> = None;
788                for gap in gaps {
789                    if gap[1] - gap[0] <= 1e-6 * span {
790                        continue;
791                    }
792                    let mid = (gap[0] + gap[1]) / 2.0;
793                    let sample = if axis == 0 {
794                        Vec2 {
795                            x: mid,
796                            y: other_mid,
797                        }
798                    } else {
799                        Vec2 {
800                            x: other_mid,
801                            y: mid,
802                        }
803                    };
804                    if parameter_point_in_face(face, sample, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? != PolygonClass::Inside
805                        && void
806                            .map(|best| gap[1] - gap[0] > best[1] - best[0])
807                            .unwrap_or(true)
808                    {
809                        void = Some(gap);
810                    }
811                }
812                if let Some([g0, g1]) = void {
813                    // The material+boundary arc wraps the domain edge exactly
814                    // when boundary coverage touches BOTH edge representations
815                    // (the on-seam rim at one, the material-side chains at the
816                    // other) with the void between them. An ordinary band
817                    // (material inside the rims) touches only one edge and
818                    // must keep the flat frame.
819                    let touches_low = intervals
820                        .iter()
821                        .any(|window| window[0] <= domain[0] + 1e-6 * span);
822                    let touches_high = intervals
823                        .iter()
824                        .any(|window| window[1] >= domain[1] - 1e-6 * span);
825                    if touches_low && touches_high {
826                        // Shift everything on the low side of the void up one
827                        // period so the band is contiguous in the arrangement
828                        // frame.
829                        rebase[axis] = Some(((g0 + g1) / 2.0, span));
830                    }
831                }
832            }
833        }
834        rebase
835    };
836    let rebase_point = |mut point: Vec2| -> Vec2 {
837        if let Some((cutoff, period)) = band_rebase[0] {
838            if point.x < cutoff {
839                point.x += period;
840            }
841        }
842        if let Some((cutoff, period)) = band_rebase[1] {
843            if point.y < cutoff {
844                point.y += period;
845            }
846        }
847        point
848    };
849    // Region test points computed in a re-based or unwrapped frame must be
850    // folded back into the domain before trim classification / evaluation.
851    // Wrapping is gated on the axis being CLOSED (a coherent flat face never
852    // produces out-of-domain interior points, so this is a no-op there).
853    let wrap_back = {
854        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
855        move |mut point: Vec2| -> Vec2 {
856            if closed.0 {
857                let span = u_domain[1] - u_domain[0];
858                if point.x < u_domain[0] || point.x > u_domain[1] {
859                    point.x = u_domain[0] + (point.x - u_domain[0]).rem_euclid(span);
860                }
861            }
862            if closed.1 {
863                let span = v_domain[1] - v_domain[0];
864                if point.y < v_domain[0] || point.y > v_domain[1] {
865                    point.y = v_domain[0] + (point.y - v_domain[0]).rem_euclid(span);
866                }
867            }
868            point
869        }
870    };
871    profile.setup += profile.lap(lap_start);
872    let pieces_by_id = &index.pieces_by_id;
873    let mut cut_hints = Vec::new();
874    let mut active_pieces = Vec::new();
875    let mut cut_keys = HashMap::default();
876    for piece_id in piece_ids {
877        let piece = pieces_by_id
878            .get(piece_id)
879            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint piece"))?;
880        let pcurve = pcurve_for(piece, face_key)?;
881        let [start, end] = pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
882        let a = pcurve.evaluate(start).or_refuse(KernelStage::Fragment, "evaluate")?;
883        let b = pcurve.evaluate(end).or_refuse(KernelStage::Fragment, "evaluate")?;
884        let middle = pcurve.evaluate((start + end) / 2.0).or_refuse(KernelStage::Fragment, "evaluate")?;
885        for point in [a, b] {
886            cut_hints.push(Vec2 {
887                x: point.x,
888                y: point.y,
889            });
890        }
891        let quantize = |point: Vec3| {
892            (
893                (point.x / arrangement_tolerance).round() as i64,
894                (point.y / arrangement_tolerance).round() as i64,
895            )
896        };
897        let mut endpoints = [quantize(a), quantize(b)];
898        endpoints.sort();
899        let key = (endpoints[0], quantize(middle), endpoints[1]);
900        if cut_keys.insert(key, *piece_id).is_none() {
901            active_pieces.push(*piece_id);
902        }
903    }
904
905    let mut segments = Vec::new();
906    let mut chains = Vec::new();
907    let mut vertex_images: std::collections::HashMap<String, Vec<Vec2>> =
908        std::collections::HashMap::new();
909    let mut endpoint_images: Vec<(Vec3, Vec2)> = Vec::new();
910    // Each boundary image carries its 3D vertex point so the boundary-side
911    // canonicalization can refuse to unify two DISTINCT boundary vertices.
912    let mut boundary_images: Vec<(Vec2, Vec3)> = Vec::new();
913    // BOUNDARY-VERTEX ANCHOR (t427 box-corner graze). The boundary-side snap
914    // below (rule 3) merges a chain endpoint onto a same-side boundary image
915    // within arr_tol*100 with NO 3D check. For a CUT/section terminus that is
916    // the intended near-tangent graze bridge onto a trim edge. For a BOUNDARY
917    // endpoint it is a bug: two genuinely-distinct same-operand boundary
918    // vertices (t427: box corner v8 at v=68.4851 vs the edge-16 split A at
919    // v=68.4783, 6.8e-3 apart on the u=max domain edge, 6.8e-3 apart in 3D ≫
920    // the 1e-5 weld floor) get unified, which droops edge 21's pcurve and
921    // mints a phantom corner lens bounded by derived edges → a one-use cluster
922    // that only strands in UNION (where the unsectioned neighbour keeps the
923    // whole edge 21). Anchor a boundary endpoint to a same-side image only when
924    // they are the SAME physical vertex (3D-coincident within the weld floor).
925    // Hatch BREP_BOUNDARY_VERTEX_ANCHOR=0 restores the pre-fix behaviour.
926    let boundary_vertex_anchor_off =
927        std::env::var("BREP_BOUNDARY_VERTEX_ANCHOR").as_deref() == Ok("0");
928    let boundary_side = |point: Vec2| {
929        let distances = [
930            (point.x - u_domain[0]).abs(),
931            (point.x - u_domain[1]).abs(),
932            (point.y - v_domain[0]).abs(),
933            (point.y - v_domain[1]).abs(),
934        ];
935        let index = distances
936            .iter()
937            .enumerate()
938            .min_by(|a, b| a.1.total_cmp(b.1))
939            .map(|entry| entry.0)
940            .unwrap();
941        (distances[index] <= arrangement_tolerance * 50.0).then_some(index)
942    };
943
944    // RIM BRIDGE (`BREP_RIM_BRIDGE`, default on, `=0` off; the imprint mints the
945    // bridge): a straight section a few `tol / |tan·n|` long between two
946    // rim pierces, one end on a vertex of this face's rim (within the weld)
947    // and the other a distinct vertex just inside it. The far end lies far closer to the rim in the chart
948    // than in space, so rule 3 below (a cut end onto a same-side boundary
949    // image, no 3-D check) would fold the bridge onto the rim vertex and the
950    // sections meeting it would skip it. Its ends keep their own images.
951    let bridge_keys: HashSet<String> = if rim_bridge_enabled() {
952        let weld = crate::tolerance::assembler_weld(1e-7);
953        // The face's own boundary vertices: a bridge has one end on its rim.
954        let mut rim_points = Vec::new();
955        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
956            if let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) {
957                for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
958                    rim_points.push(vertex_point(solid, vertex_id)?);
959                }
960            }
961        }
962        let on_rim = |point: &Vec3| rim_points.iter().any(|rim| rim.sub(*point).length() <= weld);
963        piece_ids
964            .iter()
965            .filter_map(|piece_id| pieces_by_id.get(piece_id))
966            .filter(|piece| {
967                piece.start_vertex_id != piece.end_vertex_id
968                    && piece.curve.degree == 1
969                    && piece.curve.control_points.len() == 2
970                    && match (index.vertex_points.get(&piece.start_vertex_id), index.vertex_points.get(&piece.end_vertex_id)) {
971                        (Some(a), Some(b)) => {
972                            let gap = a.sub(*b).length();
973                            gap > weld && gap <= 1e-3 && (on_rim(a) || on_rim(b))
974                        }
975                        _ => false,
976                    }
977            })
978            .flat_map(|piece| [format!("i:{}", piece.start_vertex_id), format!("i:{}", piece.end_vertex_id)])
979            .collect()
980    } else {
981        HashSet::default()
982    };
983    // Vertices where two or more cut pieces of this face meet: an interior
984    // junction of the section, never a boundary vertex it merely nears.
985    let junction_keys: HashSet<String> = if crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", false) {
986        let mut seen: HashMap<u64, usize> = HashMap::default();
987        for piece in active_pieces.iter().filter_map(|piece_id| pieces_by_id.get(piece_id)) {
988            if piece.start_vertex_id != piece.end_vertex_id {
989                *seen.entry(piece.start_vertex_id).or_default() += 1;
990                *seen.entry(piece.end_vertex_id).or_default() += 1;
991            }
992        }
993        seen.into_iter().filter(|(_, uses)| *uses >= 2).map(|(id, _)| format!("i:{id}")).collect()
994    } else {
995        HashSet::default()
996    };
997    let mut add_chain = |mut points: Vec<Vec2>,
998                         source: ChainSource,
999                         vertex_start_key: String,
1000                         vertex_start_point: Vec3,
1001                         vertex_end_key: String,
1002                         vertex_end_point: Vec3,
1003                         is_boundary: bool|
1004     -> Result<(), KernelRefusal> {
1005        for (at, key, point3) in [
1006            (0usize, vertex_start_key, vertex_start_point),
1007            (points.len() - 1, vertex_end_key, vertex_end_point),
1008        ] {
1009            let point = points[at];
1010            let bridged = bridge_keys.contains(&key);
1011            let junction = junction_keys.contains(&key);
1012            let images = vertex_images.entry(key).or_default();
1013            let canonical = images
1014                .iter()
1015                .copied()
1016                .find(|image| image.sub(point).length() <= snap_threshold)
1017                .or_else(|| {
1018                    endpoint_images
1019                        .iter()
1020                        .find(|(candidate3, candidate)| {
1021                            candidate3.sub(point3).length() <= image_band_3d
1022                                && candidate.sub(point).length() <= image_band
1023                        })
1024                        .map(|candidate| candidate.1)
1025                })
1026                .or_else(|| {
1027                    if bridged {
1028                        return None;
1029                    }
1030                    boundary_side(point).and_then(|side| {
1031                        boundary_images
1032                            .iter()
1033                            .find(|(candidate, candidate3)| {
1034                                boundary_side(*candidate) == Some(side)
1035                                    && candidate.sub(point).length()
1036                                        <= image_band
1037                                    // Boundary endpoints only merge to a same-side
1038                                    // image when 3D-coincident (same physical
1039                                    // vertex); cut endpoints keep the graze bridge.
1040                                    && (boundary_vertex_anchor_off
1041                                        || (!is_boundary && !junction)
1042                                        || candidate3.sub(point3).length() <= 1e-5)
1043                            })
1044                            .map(|(candidate, _)| *candidate)
1045                    })
1046                });
1047            if let Some(canonical) = canonical {
1048                points[at] = canonical;
1049                images.push(canonical);
1050            } else {
1051                images.push(point);
1052                endpoint_images.push((point3, point));
1053                if is_boundary && boundary_side(point).is_some() {
1054                    boundary_images.push((point, point3));
1055                }
1056            }
1057        }
1058        if points.len() > 2 {
1059            let start = points[0];
1060            let end = points[points.len() - 1];
1061            let thin = |radius: f64| {
1062                let mut kept = vec![start];
1063                kept.extend(points[1..points.len() - 1].iter().copied().filter(|point| {
1064                    point.sub(start).length() > radius && point.sub(end).length() > radius
1065                }));
1066                kept.push(end);
1067                kept
1068            };
1069            let mut kept = thin(junction_radius);
1070            // SMALL RING (`BREP_FRAGMENT_SMALL_RING`): a chain that lies wholly
1071            // inside the junction radius of its own ends (the 0.028 pinhole on a
1072            // plane charted over [0, 30]², radius 0.064) loses every interior
1073            // point: a closed one bounds nothing and two half-circles fold onto
1074            // one chord, so the region they ring is never carved. When the
1075            // thinning would leave the chain flatter than it is (its bulge off
1076            // the chord, or off its vertex when closed, past ten tolerances),
1077            // thin it at a tenth of that bulge instead.
1078            let closed = start.sub(end).length() <= arrangement_tolerance;
1079            if kept.len() < if closed { 4 } else { 3 } && small_ring_enabled() {
1080                let chord = end.sub(start);
1081                let span = chord.length();
1082                let bulge = points
1083                    .iter()
1084                    .map(|point| {
1085                        let offset = point.sub(start);
1086                        if closed || span <= arrangement_tolerance {
1087                            offset.length()
1088                        } else {
1089                            (offset.x * chord.y - offset.y * chord.x).abs() / span
1090                        }
1091                    })
1092                    .fold(0.0, f64::max);
1093                if bulge > arrangement_tolerance * 10.0 {
1094                    kept = thin(bulge * 0.1);
1095                }
1096            }
1097            points = kept;
1098        }
1099        let chain_index = chains.len();
1100        let chain_segments = points
1101            .windows(2)
1102            .map(|pair| (pair[0], pair[1]))
1103            .collect::<Vec<_>>();
1104        for (segment_index, pair) in points.windows(2).enumerate() {
1105            segments.push(Segment2 {
1106                a: pair[0],
1107                b: pair[1],
1108                tag: segment_tag(chain_index, segment_index),
1109            });
1110        }
1111        chains.push(Chain {
1112            source,
1113            count: points.len() - 1,
1114            start: points[0],
1115            end: points[points.len() - 1],
1116            segments: chain_segments,
1117        });
1118        Ok(())
1119    };
1120
1121    profile.hints += profile.lap(lap_start);
1122    // SEAM-IMAGE LOOPS: per-loop u-control-hulls, computed once for the
1123    // straddling-hole gate below (does any OTHER loop span the full closed-u
1124    // domain — the rectangle-with-seam outer that closes the strip walls).
1125    let loop_hull_u: Vec<[f64; 2]> = face
1126        .loops
1127        .iter()
1128        .map(|loop_record| {
1129            let mut hull = [f64::INFINITY, f64::NEG_INFINITY];
1130            for coedge in &loop_record.coedges {
1131                for control in &coedge.pcurve.control_points {
1132                    if control.w.abs() <= 1e-300 {
1133                        continue;
1134                    }
1135                    hull[0] = hull[0].min(control.x / control.w);
1136                    hull[1] = hull[1].max(control.x / control.w);
1137                }
1138            }
1139            hull
1140        })
1141        .collect();
1142    // Signed area of the face's full-u-span loop (the rectangle-with-seam
1143    // outer), recorded as it is processed: it defines the chart's material
1144    // orientation, so a HOLE is any loop winding OPPOSITE to it (the absolute
1145    // sign is chart-dependent — mirrored charts flip both).
1146    let mut full_span_loop_area: Option<f64> = None;
1147    // Post-rebase boundary polyline segments (incl. seam-image copies), kept
1148    // for the sag-refinement boundary-crossing parity guard on cut chains.
1149    let mut boundary_segments: Vec<(Vec2, Vec2)> = Vec::new();
1150    // The u and v extent of the boundary chains as the arrangement places
1151    // them — after the seam-hop unwrap and the band re-base, before any
1152    // seam-image copy — which is the period window the face's material lives
1153    // in. See the cut-chain period lift below.
1154    let mut band_hull = [[f64::INFINITY, f64::NEG_INFINITY]; 2];
1155    // BOUNDARY-VERTEX HINTS (2026-11-02): a curved boundary chord is refined
1156    // where ANOTHER boundary vertex of the face lies within its length, exactly
1157    // as `refine_near_hints` already refines it near a cut's endpoints.
1158    // `sample_boundary_chain` only keeps a chord within a ten-thousandth of the
1159    // domain diagonal of its pcurve, and that bound cannot see a second loop:
1160    // the plate's top face (diagonal 222) drew its r 10.7 blend-corner arc at
1161    // 16 chords sagging 0.0128, while the corner vertex of the hole the earlier
1162    // subtracts cut sits 0.011 inside that arc. The hole loop poked through the
1163    // outer loop's polyline, the arrangement cut the rim at the chord crossings
1164    // (0.04 from the true arc, on the far side of the hole vertex), and the
1165    // subtract refused with four one-use rim edges and a 0.0125 vertex gap. The
1166    // face's own vertices are hints, so a chord that a neighbouring vertex
1167    // approaches within its length is drawn sixteen times finer there (sag 5e-5
1168    // against the 0.011 clearance). A chord's own endpoints are not hints for
1169    // it (every chord ends at a vertex), and a straight pcurve has no chords to
1170    // refine. Escape hatch `BREP_BOUNDARY_VERTEX_HINTS=0|off`.
1171    let boundary_vertex_hints: Vec<Vec2> = if boundary_vertex_hints_enabled() {
1172        let mut hints = Vec::new();
1173        for loop_record in &face.loops {
1174            for coedge in &loop_record.coedges {
1175                let [start, end] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1176                for parameter in [start, end] {
1177                    let point = coedge.pcurve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
1178                    hints.push(Vec2 { x: point.x, y: point.y });
1179                }
1180            }
1181        }
1182        hints
1183    } else {
1184        Vec::new()
1185    };
1186    for (loop_index, loop_record) in face.loops.iter().enumerate() {
1187        // SEAM-HOP UNWRAP: a loop whose pcurves are drawn IN-DOMAIN but hop
1188        // the seam between consecutive coedges (t91's face 675: the boundary
1189        // jumps u=1→0 at v≈0.967 and back at v≈0.453) is incoherent in the
1190        // flat chart — its cut chains mint fine and then dangle against the
1191        // hopping boundary, cycle extraction fails, and the face drops
1192        // wholesale (the trial-35 zero-fragment signature, third variant).
1193        // Unwrap onto the covering plane with the SAME per-coedge offsets the
1194        // mass integrator / tessellator / seam-band classifier use
1195        // (`loop_seam_offsets`); a continuous loop gets all-zero offsets and
1196        // is untouched (helmet-class unwrapped sources, native seam-edge
1197        // loops, plain faces). Composes with the band re-base above: offsets
1198        // normalize the boundary FIRST, after which the re-base's
1199        // below-cutoff boundary shifts are no-ops and only its cut-chain
1200        // shifts still apply. Escape hatch: BREP_LOOP_UNWRAP=0.
1201        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1202        let offsets = if (closed.0 || closed.1)
1203            && std::env::var("BREP_LOOP_UNWRAP").as_deref() != Ok("0")
1204        {
1205            crate::topology::loop_seam_offsets(
1206                &loop_record.coedges,
1207                closed.0,
1208                closed.1,
1209                u_domain[1] - u_domain[0],
1210                v_domain[1] - v_domain[0],
1211            ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?
1212        } else {
1213            vec![[0.0, 0.0]; loop_record.coedges.len()]
1214        };
1215        let mut sampled: Vec<(usize, Vec<Vec2>, NurbsCurve, u64, u64)> =
1216            Vec::with_capacity(loop_record.coedges.len());
1217        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1218            let edge = edge_for(solid, coedge.edge_id)?;
1219            let (start_vertex, end_vertex) = if coedge.forward {
1220                (edge.start_vertex_id, edge.end_vertex_id)
1221            } else {
1222                (edge.end_vertex_id, edge.start_vertex_id)
1223            };
1224            let offset = offsets
1225                .get(coedge_index)
1226                .copied()
1227                .unwrap_or([0.0, 0.0]);
1228            // Adaptive samples are not uniformly spaced in parameter. Do not
1229            // feed them to refine_near_hints, which assumes uniform input.
1230            let boundary_points = if strip_resolution.is_some() {
1231                let initial = sample_chain(&coedge.pcurve)?;
1232                sag_refine_chain(&coedge.pcurve, initial, sampling_bound)?.0
1233            } else {
1234                // A curved boundary is drawn within a ten-thousandth of the
1235                // domain's diagonal of itself (`sample_boundary_chain`), so a
1236                // narrow face's two rims cannot cross each other.
1237                let initial = sample_boundary_chain(&coedge.pcurve, (diagonal * 1e-4).max(sampling_bound), 1024)?;
1238                if boundary_vertex_hints.is_empty() || initial.len() < 3 {
1239                    refine_near_hints(&initial, &coedge.pcurve, &cut_hints)?
1240                } else {
1241                    let own = [initial[0], initial[initial.len() - 1]];
1242                    let hints: Vec<Vec2> = cut_hints
1243                        .iter()
1244                        .copied()
1245                        .chain(boundary_vertex_hints.iter().copied().filter(|hint| {
1246                            own.iter().all(|end| hint.sub(*end).length() > arrangement_tolerance)
1247                        }))
1248                        .collect();
1249                    refine_near_hints(&initial, &coedge.pcurve, &hints)?
1250                }
1251            };
1252            let points: Vec<Vec2> = boundary_points
1253                    .into_iter()
1254                    .map(|point| {
1255                        rebase_point(Vec2 {
1256                            x: point.x + offset[0],
1257                            y: point.y + offset[1],
1258                        })
1259                    })
1260                    .collect();
1261            let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1262            let curve = if coedge.forward {
1263                curve
1264            } else {
1265                curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?
1266            };
1267            sampled.push((coedge_index, points, curve, start_vertex, end_vertex));
1268        }
1269        // SEAM-IMAGE for a STRADDLING HOLE loop: an inner (hole) loop whose
1270        // unwrapped chains poke past a closed-u domain wall exists at only ONE
1271        // period image in the arrangement strip, so the strip's OTHER side
1272        // never sees it — the seam-adjacent region there keeps a boundary
1273        // running straight through the hole opening (t181/00000312#p7: face
1274        // 519's decagon hole unwraps to u∈[−0.039,0.039]; the region left of
1275        // the seam used the FULL seam edge 475 while the right region split at
1276        // the hole crossings; the hole's far-half rim edges stranded one-use
1277        // and an 18mm derived chord bridged the gap). Insert a duplicate of
1278        // the loop's chains shifted one period toward the strip's other side,
1279        // so BOTH walls are split by the hole and the half-hole phantom
1280        // regions (rejected by the cross-frame containment) carve it out.
1281        // STRUCTURAL GATE (all required): u-closed face; ≥2 loops; the loop's
1282        // unwrapped span crosses a u-wall by > junction slack; loop width ≤
1283        // half the period (a compact hole, never a rim/horizon); winding
1284        // OPPOSITE to the full-span outer loop (hole orientation relative to
1285        // the chart — an outer loop copy would double-cover material); and
1286        // some OTHER loop's control hull spans the full u-domain (the
1287        // seam-carrying rectangle exists). Escape hatch:
1288        // BREP_SEAM_IMAGE_LOOPS=0.
1289        let image_shift: Option<f64> = {
1290            let span = u_domain[1] - u_domain[0];
1291            let slack = arrangement_tolerance * 50.0;
1292            if !closed.0
1293                || face.loops.len() < 2
1294                || span <= 0.0
1295                || std::env::var("BREP_SEAM_IMAGE_LOOPS").as_deref() == Ok("0")
1296            {
1297                None
1298            } else {
1299                let mut min_u = f64::INFINITY;
1300                let mut max_u = f64::NEG_INFINITY;
1301                let mut area = 0.0;
1302                let mut flat: Vec<Vec2> = sampled
1303                    .iter()
1304                    .flat_map(|(_, points, ..)| points.iter().copied())
1305                    .collect();
1306                if flat.len() < 3 {
1307                    flat.clear();
1308                }
1309                for (index, point) in flat.iter().enumerate() {
1310                    min_u = min_u.min(point.x);
1311                    max_u = max_u.max(point.x);
1312                    let next = flat[(index + 1) % flat.len()];
1313                    area += crate::polygon::area_term([point.x, point.y], [next.x, next.y]);
1314                }
1315                // Full-span discrimination must use the UNWRAPPED width: a
1316                // straddling hole's raw control hull spans the whole domain
1317                // (its halves are stored at both seam sides), but its
1318                // unwrapped chains are compact; only the true outer rectangle
1319                // stays period-wide after unwrapping.
1320                let spans_full_domain =
1321                    !flat.is_empty() && max_u - min_u >= span * (1.0 - 1e-6);
1322                if spans_full_domain && full_span_loop_area.is_none() {
1323                    full_span_loop_area = Some(area);
1324                }
1325                let straddles_low = min_u < u_domain[0] - slack;
1326                let straddles_high = max_u > u_domain[1] + slack;
1327                let compact = max_u - min_u <= 0.5 * span;
1328                let is_hole = full_span_loop_area
1329                    .map(|outer| !spans_full_domain && area * outer < 0.0)
1330                    .unwrap_or(false);
1331                let has_full_span_other = loop_hull_u.iter().enumerate().any(|(other, hull)| {
1332                    other != loop_index
1333                        && hull[0] <= u_domain[0] + 1e-6 * span
1334                        && hull[1] >= u_domain[1] - 1e-6 * span
1335                });
1336                if compact && is_hole && has_full_span_other && (straddles_low ^ straddles_high) {
1337                    if env_read!("BREP_DEBUG_FRAG")
1338                        .map(|value| value == face.id.to_string())
1339                        .unwrap_or(false)
1340                    {
1341                        eprintln!(
1342                            "  seam-image: face {} loop {loop_index} straddles u-wall (u=[{min_u:.6},{max_u:.6}]) — inserting {} period image",
1343                            face.id,
1344                            if straddles_low { "+1" } else { "-1" }
1345                        );
1346                    }
1347                    Some(if straddles_low { span } else { -span })
1348                } else {
1349                    None
1350                }
1351            }
1352        };
1353        for (coedge_index, points, curve, start_vertex, end_vertex) in sampled {
1354            let coedge = &loop_record.coedges[coedge_index];
1355            for point in &points {
1356                band_hull[0] = [band_hull[0][0].min(point.x), band_hull[0][1].max(point.x)];
1357                band_hull[1] = [band_hull[1][0].min(point.y), band_hull[1][1].max(point.y)];
1358            }
1359            boundary_segments.extend(points.windows(2).map(|pair| (pair[0], pair[1])));
1360            add_chain(
1361                points.clone(),
1362                ChainSource::Boundary {
1363                    coedge: coedge.clone(),
1364                    curve: curve.clone(),
1365                },
1366                format!("b:{operand}:{start_vertex}"),
1367                vertex_point(solid, start_vertex)?,
1368                format!("b:{operand}:{end_vertex}"),
1369                vertex_point(solid, end_vertex)?,
1370                true,
1371            )?;
1372            if let Some(shift) = image_shift {
1373                let shifted: Vec<Vec2> = points
1374                    .iter()
1375                    .map(|point| Vec2 {
1376                        x: point.x + shift,
1377                        y: point.y,
1378                    })
1379                    .collect();
1380                boundary_segments
1381                    .extend(shifted.windows(2).map(|pair| (pair[0], pair[1])));
1382                add_chain(
1383                    shifted,
1384                    ChainSource::Boundary {
1385                        coedge: coedge.clone(),
1386                        curve,
1387                    },
1388                    format!("b:{operand}:{start_vertex}"),
1389                    vertex_point(solid, start_vertex)?,
1390                    format!("b:{operand}:{end_vertex}"),
1391                    vertex_point(solid, end_vertex)?,
1392                    true,
1393                )?;
1394            }
1395        }
1396    }
1397    // CUT-CHAIN CLAMP BOUND: on a CLOSED direction the face's boundary band may
1398    // legitimately extend past the surface domain — a seam-straddling face is
1399    // arranged in UNWRAPPED coordinates (helmet Face_15's boundary chains run
1400    // u∈[-0.178, 0.295] on a [0,1]-domain surface). Clamping a cut pcurve to
1401    // the surface domain there tears it off the band: the branch-preserved
1402    // truncation bridge collapsed to a count=1 sliver hugging u=0 and the face
1403    // never split. Widen the clamp bound to domain ∪ trim-pcurve control hulls
1404    // (the hulls bound the boundary chains); a cut already inside the domain is
1405    // untouched, and OPEN directions keep the plain domain clamp. Escape hatch
1406    // BREP_FRAG_ENV_CLAMP=0.
1407    let (clamp_u, clamp_v) = {
1408        let mut clamp_u = u_domain;
1409        let mut clamp_v = v_domain;
1410        let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1411        // NOTE (2026-09-16): this hatch's ONLY tamper guard,
1412        // `csg/fragment/tests.rs::seam_band_cut_chain_splits_periodic_face`, went
1413        // INERT when the march-window lift landed — that test now passes with this
1414        // hatch off, so nothing tamper-verifies this mechanism any more. Not that it
1415        // is untested: no other test NAMES this hatch.
1416        if (closed_u || closed_v) && std::env::var("BREP_FRAG_ENV_CLAMP").as_deref() != Ok("0") {
1417            for loop_record in &face.loops {
1418                for coedge in &loop_record.coedges {
1419                    for point in &coedge.pcurve.control_points {
1420                        if point.w.abs() <= 1e-300 {
1421                            continue;
1422                        }
1423                        if closed_u {
1424                            clamp_u[0] = clamp_u[0].min(point.x / point.w);
1425                            clamp_u[1] = clamp_u[1].max(point.x / point.w);
1426                        }
1427                        if closed_v {
1428                            clamp_v[0] = clamp_v[0].min(point.y / point.w);
1429                            clamp_v[1] = clamp_v[1].max(point.y / point.w);
1430                        }
1431                    }
1432                }
1433            }
1434        }
1435        (clamp_u, clamp_v)
1436    };
1437    profile.boundary += profile.lap(lap_start);
1438    for piece_id in active_pieces {
1439        let piece = pieces_by_id[&piece_id];
1440        let pcurve = pcurve_for(piece, face_key)?.clone();
1441        // SAG-BOUNDED CUT-CHAIN FIDELITY (t70 split-set asynchrony class).
1442        // `sample_chain`'s uniform sampling is knot-driven, so the SAME
1443        // imprint piece gets a 16-segment polyline on one support face and a
1444        // 92-segment one on the other (the counts follow each face's pcurve
1445        // knot structure, not the curvature). A coarse chord can then sag
1446        // MILLIMETRE-scale away from the true pcurve and invade a trim
1447        // region the true curve clears — t70: piece 55's chord on face
1448        // 1:405 sagged ~3e-3 into a hole corner the true pcurve misses by
1449        // 1.3e-3, so the arrangement carved phantom micro-junctions on that
1450        // face only, the two owners' split sets diverged (whole Imprint
1451        // edge vs a 4-piece Derived chain of the same locus), and every op
1452        // failed with one-use edges. Refining every cut chain until its
1453        // chords hug the true pcurve within the arrangement's own tolerance
1454        // makes both owners' polylines faithful to the ONE shared curve, so
1455        // their junction sets agree structurally (no proximity decisions
1456        // anywhere). Escape hatch: BREP_CHAIN_SAG_REFINE=0.
1457        let (mut points, original_flags) = sag_refine_chain(
1458            &pcurve,
1459            sample_chain(&pcurve)?,
1460            sampling_bound,
1461        )?;
1462        for point in &mut points {
1463            if point.x < clamp_u[0] {
1464                point.x = clamp_u[0] + arrangement_tolerance * 10.0;
1465            } else if point.x > clamp_u[1] {
1466                point.x = clamp_u[1] - arrangement_tolerance * 10.0;
1467            }
1468            if point.y < clamp_v[0] {
1469                point.y = clamp_v[0] + arrangement_tolerance * 10.0;
1470            } else if point.y > clamp_v[1] {
1471                point.y = clamp_v[1] - arrangement_tolerance * 10.0;
1472            }
1473        }
1474        let snap_endpoint_to_domain = |point: Vec2| {
1475            let candidates = [
1476                (
1477                    (point.x - u_domain[0]).abs(),
1478                    Vec2 {
1479                        x: u_domain[0],
1480                        y: point.y,
1481                    },
1482                ),
1483                (
1484                    (point.x - u_domain[1]).abs(),
1485                    Vec2 {
1486                        x: u_domain[1],
1487                        y: point.y,
1488                    },
1489                ),
1490                (
1491                    (point.y - v_domain[0]).abs(),
1492                    Vec2 {
1493                        x: point.x,
1494                        y: v_domain[0],
1495                    },
1496                ),
1497                (
1498                    (point.y - v_domain[1]).abs(),
1499                    Vec2 {
1500                        x: point.x,
1501                        y: v_domain[1],
1502                    },
1503                ),
1504            ];
1505            let nearest = candidates
1506                .into_iter()
1507                .min_by(|first, second| first.0.total_cmp(&second.0))
1508                .unwrap();
1509            if nearest.0 <= arrangement_tolerance * 50.0 {
1510                nearest.1
1511            } else {
1512                point
1513            }
1514        };
1515        let last = points.len() - 1;
1516        // A rim bridge's ends keep their own place (see RIM BRIDGE above): the
1517        // end inside the face is a distinct vertex a chart hair from the edge.
1518        // A cut's end at a vertex INSIDE the face a few 1e-5 of the period
1519        // from the seam (another body's seam vertex on a section that runs
1520        // along this face's seam) is inside the snap band, and snapping it
1521        // onto the domain edge moved that vertex to the seam: the section's
1522        // short piece then closed into a whole ring and the face never split.
1523        // With `BREP_NEAR_SEAM_CLOSED_RUN` an end snaps only when the edge's
1524        // image is at least as near the piece's own vertex as its place is.
1525        // The end's own vertex is the piece's vertex nearest its image (the
1526        // piece's vertex order need not follow its pcurve).
1527        let keeps_vertex = |snapped: Vec2, original: Vec2, _vertex_id: u64| -> bool {
1528            if !crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", false) || (snapped.x == original.x && snapped.y == original.y) {
1529                return true;
1530            }
1531            let (Ok(at), Ok(moved)) = (face.surface.evaluate(original.x, original.y), face.surface.evaluate(snapped.x, snapped.y)) else {
1532                return true;
1533            };
1534            let own = [piece.start_vertex_id, piece.end_vertex_id]
1535                .iter()
1536                .filter_map(|id| index.vertex_points.get(id))
1537                .min_by(|a, b| a.sub(at).length().total_cmp(&b.sub(at).length()));
1538            let keep = own.is_none_or(|vertex| moved.sub(*vertex).length() <= at.sub(*vertex).length());
1539            keep
1540        };
1541        if !bridge_keys.contains(&format!("i:{}", piece.start_vertex_id)) {
1542            let snapped = snap_endpoint_to_domain(points[0]);
1543            if keeps_vertex(snapped, points[0], piece.start_vertex_id) {
1544                points[0] = snapped;
1545            }
1546        }
1547        if !bridge_keys.contains(&format!("i:{}", piece.end_vertex_id)) {
1548            let snapped = snap_endpoint_to_domain(points[last]);
1549            if keeps_vertex(snapped, points[last], piece.end_vertex_id) {
1550                points[last] = snapped;
1551            }
1552        }
1553        for point in &mut points {
1554            *point = rebase_point(*point);
1555        }
1556        // CUT-CHAIN PERIOD LIFT. A section's pcurve on a closed carrier is
1557        // drawn on the carrier's own period, but the boundary chains above can
1558        // sit a period away from it: an imported face whose seam edge is not
1559        // at the carrier's parameter origin carries rims split AT that origin,
1560        // so its loop hops the branch cut between coedges and the seam-hop
1561        // unwrap lays it out over [seam, seam + period] (the 2026-09-14 gear:
1562        // cone and fillet torus with seam edges at u = 1/2, boundary chains on
1563        // u ∈ [0.5, 1.5], section arcs on [0, 0.5] and [0.5, 1]). The arc a
1564        // period off never meets the band, the section never closes across the
1565        // face, the face stays one fragment and is kept or dropped whole — one
1566        // rim and the section ring then strand one-use. Every piece the imprint
1567        // attaches to a face has its midpoint inside that face's trim, so the
1568        // chain's image whose middle lies inside the band is the one the
1569        // arrangement must see; a whole-period shift is exact on a periodic
1570        // carrier. The chain is lifted only when its middle is OUTSIDE the band
1571        // and exactly one period image puts it inside, so a chain already
1572        // coherent with its band — every native face, every re-based band —
1573        // is untouched. The pcurve keeps the carrier's own period (the lift is
1574        // an arrangement coordinate, recorded on the chain for the partial-run
1575        // rescue). A lifted chain that still crosses a wall of the band crosses
1576        // the face's seam edge unsplit, and the face refuses by name. Escape
1577        // hatch `BREP_CUT_PERIOD_LIFT=0`.
1578        let mut lift = Vec2 { x: 0.0, y: 0.0 };
1579        if std::env::var("BREP_CUT_PERIOD_LIFT").as_deref() != Ok("0") {
1580            let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1581            for axis in 0..2 {
1582                let (is_closed, domain) = if axis == 0 { (closed.0, u_domain) } else { (closed.1, v_domain) };
1583                let [low, high] = band_hull[axis];
1584                let span = domain[1] - domain[0];
1585                if !is_closed || !(span > 0.0) || !(low < domain[0] || high > domain[1]) {
1586                    continue;
1587                }
1588                let coordinate = |point: &Vec2| if axis == 0 { point.x } else { point.y };
1589                let middle = coordinate(&points[points.len() / 2]);
1590                let inside = |value: f64| value > low && value < high;
1591                if inside(middle) {
1592                    continue;
1593                }
1594                let images: Vec<f64> = [-2.0, -1.0, 1.0, 2.0]
1595                    .into_iter()
1596                    .map(|periods| periods * span)
1597                    .filter(|shift| inside(middle + shift))
1598                    .collect();
1599                let [shift] = images[..] else {
1600                    continue;
1601                };
1602                let slack = arrangement_tolerance * 50.0;
1603                let (reach_low, reach_high) = points.iter().map(coordinate).fold(
1604                    (f64::INFINITY, f64::NEG_INFINITY),
1605                    |(lo, hi), value| (lo.min(value), hi.max(value)),
1606                );
1607                if reach_low + shift < low - slack || reach_high + shift > high + slack {
1608                    let [first, second] = piece.support_faces;
1609                    return Err(KernelRefusal::internal(
1610                        KernelStage::Fragment,
1611                        "fragment.face_split",
1612                        format!(
1613                            "fragment_face: section piece {piece_id} of faces {}:{} x {}:{} crosses \
1614                             the seam wall of face {}:{}'s unwrapped band ({} in [{low:.9}, {high:.9}], \
1615                             the section's period image [{:.9}, {:.9}]) without a vertex there",
1616                            first.operand,
1617                            first.face_id,
1618                            second.operand,
1619                            second.face_id,
1620                            operand,
1621                            face.id,
1622                            if axis == 0 { "u" } else { "v" },
1623                            reach_low + shift,
1624                            reach_high + shift,
1625                        ),
1626                    ));
1627                }
1628                for point in &mut points {
1629                    if axis == 0 {
1630                        point.x += shift;
1631                    } else {
1632                        point.y += shift;
1633                    }
1634                }
1635                if axis == 0 {
1636                    lift.x = shift;
1637                } else {
1638                    lift.y = shift;
1639                }
1640                if env_read!("BREP_DEBUG_FRAG")
1641                    .map(|value| value == face.id.to_string())
1642                    .unwrap_or(false)
1643                {
1644                    eprintln!(
1645                        "  period lift: face {} cut p{piece_id} {} {shift:+} into the band [{low:.6},{high:.6}]",
1646                        face.id,
1647                        if axis == 0 { "u" } else { "v" }
1648                    );
1649                }
1650            }
1651        }
1652        // Guard runs on the FINAL (clamped/snapped/rebased) coordinates — the
1653        // same frame the boundary chains were sampled into — so crossing
1654        // parity is measured exactly where the arrangement would see it.
1655        points = enforce_boundary_crossing_parity(
1656            points,
1657            &original_flags,
1658            &boundary_segments,
1659            arrangement_tolerance,
1660            env_read!("BREP_DEBUG_FRAG")
1661                .map(|value| value == face.id.to_string())
1662                .unwrap_or(false),
1663            face.id,
1664        );
1665        let start_point = index
1666            .vertex_points
1667            .get(&piece.start_vertex_id)
1668            .copied()
1669            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint start vertex"))?;
1670        let end_point = index
1671            .vertex_points
1672            .get(&piece.end_vertex_id)
1673            .copied()
1674            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint end vertex"))?;
1675        add_chain(
1676            points,
1677            ChainSource::Cut {
1678                piece_id,
1679                pcurve,
1680                lift,
1681                curve: trimmed_curve(&piece.curve, piece.t0, piece.t1)?,
1682                shared_ring: piece.shared_edge.filter(|_| {
1683                    piece
1684                        .curve
1685                        .evaluate(piece.t0)
1686                        .ok()
1687                        .zip(piece.curve.evaluate(piece.t1).ok())
1688                        .is_some_and(|(a, b)| a.sub(b).length() <= 1e-6)
1689                }),
1690            },
1691            format!("i:{}", piece.start_vertex_id),
1692            start_point,
1693            format!("i:{}", piece.end_vertex_id),
1694            end_point,
1695            false,
1696        )?;
1697    }
1698    drop(add_chain);
1699
1700    // POLE-GAP BRIDGE (single-loop periodic cap; corpus fixture 25 cube-pierce).
1701    // A face closed in one parameter direction can carry a DEGENERATE pole
1702    // iso-line — a whole domain-edge row of one parameter collapsing to a
1703    // single 3D point (the dome apex v2 at v=0 here). The imported trim
1704    // represents the pole with a partial arc plus a degenerate self-edge that
1705    // stop SHORT of the opposite seam foot, so the outer boundary is OPEN in
1706    // the flat UV chart at the pole: the two seam feet sit a FRACTION of a
1707    // period apart (never a whole period), so no covering-strip period-image
1708    // can ever join them — this case is structurally outside the seam-image
1709    // loops machinery above. When a section cut then splits the cap,
1710    // `arrange_segments` closes only the lens region that avoids the pole and
1711    // DROPS the seam-and-pole-spanning outside region: the cap fragments to 1
1712    // not 2, its section + outer-rim edges strand one-use (union/subtract fail
1713    // `S=1 genus=1`), while intersect keeps the lens and succeeds. Close the
1714    // boundary in-chart: pair the two dangling (odd-incidence) boundary
1715    // endpoints that are UV images of the SAME solid vertex (structural
1716    // identity via `vertex_images`, never proximity clustering), VERIFY the
1717    // straight UV connector between them is degenerate (every sample collapses
1718    // to one 3D point — a genuine pole, not a real seam that would cross
1719    // material), and add a bridge chain that REUSES an existing degenerate
1720    // pole edge as its source. The reused edge is 3D-zero-length, so the
1721    // minted coedge is s==e and exempt from the two-use rule — no new edge is
1722    // introduced (the zero-regression reuse pattern), and the outside fragment
1723    // reproduces the original cap loop's own pole/seam structure. A
1724    // cleanly-closing boundary has no odd node and is byte-identical untouched;
1725    // a genuine (non-degenerate) seam gap fails the degeneracy check and is
1726    // left alone (the safe direction). Escape hatch: BREP_POLE_GAP_BRIDGE=0.
1727    let pole_gap_closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1728    if (pole_gap_closed.0 || pole_gap_closed.1)
1729        && std::env::var("BREP_POLE_GAP_BRIDGE").as_deref() != Ok("0")
1730    {
1731        // A degenerate pole iso-line only exists on a surface closed in the
1732        // seam direction; a non-periodic face never reaches this block and is
1733        // byte-identical untouched.
1734        //
1735        // `add_chain` canonicalizes shared endpoints to a bit-identical `Vec2`,
1736        // so a TIGHT epsilon groups exactly the coincident nodes and never
1737        // over-merges two distinct nearby vertices (which would corrupt the
1738        // incidence parity on a small face).
1739        let node_tol = arrangement_tolerance * 10.0;
1740        // Incidence over BOUNDARY chain endpoints only — the pole gap is a
1741        // property of the trim boundary, and cut chains anchor to it elsewhere.
1742        let mut nodes: Vec<(Vec2, usize)> = Vec::new();
1743        for chain in &chains {
1744            if !matches!(chain.source, ChainSource::Boundary { .. }) {
1745                continue;
1746            }
1747            for point in [chain.start, chain.end] {
1748                if let Some(entry) = nodes.iter_mut().find(|(q, _)| q.sub(point).length() <= node_tol)
1749                {
1750                    entry.1 += 1;
1751                } else {
1752                    nodes.push((point, 1));
1753                }
1754            }
1755        }
1756        // Odd incidence => the boundary is UV-open at that endpoint.
1757        let odd: Vec<Vec2> = nodes
1758            .iter()
1759            .filter(|(_, count)| count % 2 == 1)
1760            .map(|(point, _)| *point)
1761            .collect();
1762        // Each odd node's owning solid vertex: the canonical image lists in
1763        // `vertex_images` are keyed "b:{operand}:{vertex_id}".
1764        let vertex_of = |point: Vec2| -> Option<u64> {
1765            vertex_images.iter().find_map(|(key, images)| {
1766                images
1767                    .iter()
1768                    .any(|image| image.sub(point).length() <= node_tol)
1769                    .then(|| key.rsplit(':').next().and_then(|id| id.parse::<u64>().ok()))
1770                    .flatten()
1771            })
1772        };
1773        let mut by_vertex: HashMap<u64, Vec<Vec2>> = HashMap::default();
1774        for point in &odd {
1775            if let Some(vertex_id) = vertex_of(*point) {
1776                by_vertex.entry(vertex_id).or_default().push(*point);
1777            }
1778        }
1779        // Forward-evaluate only (the projector is a poisoned oracle; evaluate
1780        // is exact). A degenerate 3D curve collapses to a point over its span.
1781        let curve_degenerate = |curve: &NurbsCurve| -> bool {
1782            let Ok(domain) = curve.domain() else {
1783                return false;
1784            };
1785            let Ok(base) = curve.evaluate(domain[0]) else {
1786                return false;
1787            };
1788            [0.5, 1.0].iter().all(|fraction| {
1789                curve
1790                    .evaluate(domain[0] + (domain[1] - domain[0]) * fraction)
1791                    .map(|point| point.sub(base).length() <= 1e-5)
1792                    .unwrap_or(false)
1793            })
1794        };
1795        for (vertex_id, images) in by_vertex {
1796            // A pole slit unclosed in exactly one place has EXACTLY two dangling
1797            // images of its apex vertex; anything else is not this class.
1798            if images.len() != 2 {
1799                continue;
1800            }
1801            let (a, b) = (images[0], images[1]);
1802            // The straight UV connector must be a degenerate iso-line: every
1803            // sample collapses to one 3D point. This is the gate that keeps a
1804            // real seam (whose connector crosses material) from being bridged.
1805            let mut base: Option<Vec3> = None;
1806            let mut degenerate = true;
1807            for step in 0..=8 {
1808                let fraction = step as f64 / 8.0;
1809                let uv = a.add(b.sub(a).scale(fraction));
1810                match face.surface.evaluate(uv.x, uv.y) {
1811                    Ok(point) => match base {
1812                        None => base = Some(point),
1813                        Some(reference) => {
1814                            if point.sub(reference).length() > 1e-5 {
1815                                degenerate = false;
1816                                break;
1817                            }
1818                        }
1819                    },
1820                    Err(_) => {
1821                        degenerate = false;
1822                        break;
1823                    }
1824                }
1825            }
1826            if !degenerate {
1827                continue;
1828            }
1829            // Reuse an existing degenerate pole edge's source (its 3D curve is a
1830            // point, so the minted coedge is s==e and validation-exempt).
1831            let Some(source) = chains.iter().find_map(|chain| match &chain.source {
1832                ChainSource::Boundary { coedge, curve }
1833                    if chain.start.sub(chain.end).length() <= node_tol
1834                        && chain.count <= 1
1835                        && (chain.start.sub(a).length() <= node_tol
1836                            || chain.start.sub(b).length() <= node_tol)
1837                        && curve_degenerate(curve) =>
1838                {
1839                    Some(ChainSource::Boundary {
1840                        coedge: coedge.clone(),
1841                        curve: curve.clone(),
1842                    })
1843                }
1844                _ => None,
1845            }) else {
1846                continue;
1847            };
1848            let chain_index = chains.len();
1849            segments.push(Segment2 {
1850                a,
1851                b,
1852                tag: segment_tag(chain_index, 0),
1853            });
1854            chains.push(Chain {
1855                source,
1856                count: 1,
1857                start: a,
1858                end: b,
1859                segments: vec![(a, b)],
1860            });
1861            boundary_segments.push((a, b));
1862            if env_read!("BREP_DEBUG_FRAG")
1863                .map(|value| value == face.id.to_string())
1864                .unwrap_or(false)
1865            {
1866                eprintln!(
1867                    "  pole-gap bridge: face {} vertex {vertex_id} joins \
1868                     ({:.6},{:.6})->({:.6},{:.6}) along a degenerate iso-line",
1869                    face.id, a.x, a.y, b.x, b.y
1870                );
1871            }
1872        }
1873    }
1874
1875    // A cut chain that coincides with a boundary chain cannot split the
1876    // interior — the face's own edge already bounds it there. Worse, the
1877    // duplicate overlapping segments corrupt arrangement cycle extraction
1878    // and silently swallow every region that touches the overlap (seen when
1879    // endpoint polishing snaps a face/face intersection line onto a
1880    // near-coincident boundary edge of the same face). Drop such cuts
1881    // before arranging.
1882    let coincidence_tolerance = arrangement_tolerance * 50.0;
1883    let point_segment_distance = |point: Vec2, a: Vec2, b: Vec2| -> f64 {
1884        let segment = b.sub(a);
1885        let length_squared = segment.dot(segment);
1886        if length_squared <= 1e-30 {
1887            return point.sub(a).length();
1888        }
1889        let parameter = (point.sub(a).dot(segment) / length_squared).clamp(0.0, 1.0);
1890        point.sub(a.add(segment.scale(parameter))).length()
1891    };
1892    let near_chain = |point: Vec2, chain: &Chain, tolerance: f64| {
1893        chain
1894            .segments
1895            .iter()
1896            .any(|(a, b)| point_segment_distance(point, *a, *b) <= tolerance)
1897    };
1898    // A cut coincides with a boundary only if its INTERIOR follows the same
1899    // path, not merely its endpoints. A single-segment straight cut whose two
1900    // endpoints happen to land on a CURVED boundary edge's endpoints (a
1901    // cap∩cap intersection chord spanning a curved rim arc — the missing
1902    // cone-cap split behind the curved-primitive open-edge booleans) shares
1903    // only its endpoints and cuts clean across the interior; dropping it as a
1904    // duplicate loses the region it carves. So also require the segment
1905    // MIDPOINTS to lie near the boundary. The midpoint test runs at a looser
1906    // threshold than the endpoint match: a genuinely-coincident curved cut's
1907    // polyline midpoints carry their own chord sag (order 1× tolerance), which
1908    // must still count as near, while a chord spanning a curved arc departs by
1909    // the arc's sagitta (orders of magnitude larger) and is correctly kept. On
1910    // the box path both edges are straight, so two shared endpoints force the
1911    // midpoint onto the boundary and the drop is unchanged.
1912    let midpoint_tolerance = coincidence_tolerance * 8.0;
1913    // CORNER-CHORD VETO. The endpoint match above admits a cut whose endpoint
1914    // sits up to `coincidence_tolerance` (50x arr_tol) from the boundary
1915    // chain's endpoint. When a section threads through a MODEL CORNER where two
1916    // boundary edges (legs) meet at a shared vertex, the section arm on the
1917    // sliver face between them is the HYPOTENUSE of a tiny right triangle whose
1918    // short leg can be well under that slack (t634: the torus crosses a 3-face
1919    // corner of 00000327; on the sliver face the arm's start is 31x arr_tol
1920    // from the matched leg's start, and the hypotenuse midpoint is ~15x arr_tol
1921    // off the leg — both under the 50x/400x tolerances). The old test dropped
1922    // that arm as a "duplicate" of one leg, so the tiny corner region was never
1923    // carved on the sliver face while the mate operand kept the arm -> the
1924    // shared section edge went one-use (invalid genus). A genuine corner chord
1925    // is distinguishable STRUCTURALLY, not by tolerance: its endpoint coincides
1926    // (at NODE scale = the arrangement's own find_node snap) with a real,
1927    // DISTINCT boundary vertex — proof it terminates at a 0-cell of its own,
1928    // spanning two legs, rather than retracing this one edge. A true retrace
1929    // (box duplicate, cap-rim chord) has endpoints AT the matched chain's ends
1930    // (gap ~0), so the veto never triggers for it. Hatch restores the old drop.
1931    profile.cuts += profile.lap(lap_start);
1932    let corner_veto_enabled = std::env::var("BREP_DUP_DROP_CORNER_VETO")
1933        .map(|value| value != "0")
1934        .unwrap_or(true);
1935    let node_tolerance = arrangement_tolerance;
1936    let terminates_at_distinct_boundary_vertex = |cut_end: Vec2, matched_end: Vec2| -> bool {
1937        cut_end.sub(matched_end).length() > node_tolerance
1938            && chains.iter().any(|other| {
1939                matches!(other.source, ChainSource::Boundary { .. })
1940                    && (other.start.sub(cut_end).length() <= node_tolerance
1941                        || other.end.sub(cut_end).length() <= node_tolerance)
1942            })
1943    };
1944    let debug_drop = env_read!("BREP_DEBUG_FRAG")
1945        .map(|value| value == face.id.to_string())
1946        .unwrap_or(false);
1947    // MICRO-BOUNDARY SKIP (t316). A boundary chain SHORTER than the coincidence
1948    // tolerance cannot serve as a duplication reference: its two endpoints are
1949    // indistinguishable at this tolerance, so the orientation-agnostic endpoint
1950    // match collapses and a cut that merely touches ONE of its ends spuriously
1951    // "matches" BOTH. That wrongly drops a junction-bridge micro-cut spanning a
1952    // weld-scale vertex cluster (t316: cut p38, the ~0.004mm bridge from a
1953    // section terminus C to the plate-rim node C', gets dropped against e99 — a
1954    // ~0.008mm rim segment shorter than the 0.07mm coincidence tolerance —
1955    // stranding the whole b-poke bottom-cap sliver one-use). The genuine target
1956    // (the tangent-wall cap section, coincident with a full-length box edge ≫
1957    // tolerance) is untouched. Independent of the corner-chord veto below: this
1958    // guard disqualifies a sub-tolerance BOUNDARY as a reference, that one spares
1959    // a corner-spanning CUT. Hatch `BREP_DUP_CUT_MICRO_BOUNDARY=0` restores the
1960    // old, length-agnostic reference test.
1961    let micro_boundary_skip = std::env::var("BREP_DUP_CUT_MICRO_BOUNDARY").as_deref() != Ok("0");
1962    let boundary_extent = |boundary: &Chain| -> f64 {
1963        boundary
1964            .segments
1965            .iter()
1966            .map(|(a, b)| b.sub(*a).length())
1967            .sum()
1968    };
1969    // POLE-COLLAPSED ENDS. A pole is a whole row of the chart at one 3D
1970    // point, so two chain ends on its degenerate boundary chain are one point
1971    // however far apart their u reads, and near the pole a chart distance says
1972    // nothing about the 3D one. The revolve_pole union's G2 end cap (a 93 deg
1973    // sector with its apex on the axis) is cut by the wedge's two side planes
1974    // along its own radius edges: the sections are those edges' sub-arcs to
1975    // 1e-15, ending 3.2e-6 short of the apex. Their pcurves follow u = 1 and
1976    // u = 0 and then swing to one u = 0.443 at the pole; evaluated on the cap
1977    // a chain stands 7.4e-4 off its radius at v = 0.99976. The endpoint test
1978    // read a gap of 0.557 and kept both cuts, and the arrangement carved two
1979    // slivers, each bounded by a radius edge and its own weld copy. One was
1980    // kept in the union and the coplanar merge refused its genus; the
1981    // intersection refused with one-use edges. So when a chain end and a
1982    // boundary end both lie on one degenerate boundary chain they coincide,
1983    // and the cut is held to the boundary in 3D, section curve against edge
1984    // curve, within the coincidence tolerance carried along the boundary by
1985    // its own stretch (3D length over chart length). Escape hatch
1986    // `BREP_DUP_DROP_POLE=0`.
1987    let pole_ends = std::env::var("BREP_DUP_DROP_POLE").as_deref() != Ok("0");
1988    let degenerate_chains: Vec<usize> = chains
1989        .iter()
1990        .enumerate()
1991        .filter(|(_, chain)| match &chain.source {
1992            ChainSource::Boundary { coedge, .. } => solid
1993                .edges
1994                .iter()
1995                .any(|edge| edge.id == coedge.edge_id && edge.degenerate),
1996            ChainSource::Cut { .. } => false,
1997        })
1998        .map(|(index, _)| index)
1999        .collect();
2000    let on_one_pole = |a: Vec2, b: Vec2| -> bool {
2001        degenerate_chains.iter().any(|&pole| {
2002            near_chain(a, &chains[pole], coincidence_tolerance)
2003                && near_chain(b, &chains[pole], coincidence_tolerance)
2004        })
2005    };
2006    let coincident_in_space = |cut: &Chain, boundary: &Chain, weld_scale: bool| -> bool {
2007        let ChainSource::Boundary { curve, coedge } = &boundary.source else {
2008            return false;
2009        };
2010        let ChainSource::Cut { curve: section, piece_id, .. } = &cut.source else {
2011            return false;
2012        };
2013        let Ok([start, end]) = section.domain() else {
2014            return false;
2015        };
2016        let mut chart_length = 0.0;
2017        let mut space_length = 0.0;
2018        for (a, b) in &boundary.segments {
2019            let (Ok(pa), Ok(pb)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else {
2020                return false;
2021            };
2022            chart_length += b.sub(*a).length();
2023            space_length += pb.sub(pa).length();
2024        }
2025        if chart_length <= 0.0 || space_length <= 0.0 {
2026            return false;
2027        }
2028        let copy_boundary = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2029            boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2030        });
2031        let bound = if weld_scale {
2032            if copy_boundary { crate::tolerance::WELD_FLOOR } else { 1e-7 }
2033        } else {
2034            coincidence_tolerance * space_length / chart_length
2035        };
2036        let stations = cut.segments.len().max(16);
2037        (0..=stations).all(|index| {
2038            section
2039                .evaluate(start + (end - start) * index as f64 / stations as f64)
2040                .ok()
2041                .and_then(|at| crate::project_point_to_curve(curve, at).ok())
2042                .is_some_and(|projection| projection.distance <= bound)
2043        })
2044    };
2045    let mut dropped_chains = HashSet::default();
2046    for (index, chain) in chains.iter().enumerate() {
2047        if !matches!(chain.source, ChainSource::Cut { .. }) {
2048            continue;
2049        }
2050        let mut matched_boundary: Option<usize> = None;
2051        for (boundary_index, boundary) in chains.iter().enumerate() {
2052            if !matches!(boundary.source, ChainSource::Boundary { .. }) {
2053                continue;
2054            }
2055            // t316: a sub-tolerance micro-boundary cannot be a duplication
2056            // reference — its endpoints collapse at this tolerance, so a cut that
2057            // merely touches one end spuriously matches both. Skip it as a
2058            // candidate (never selectable as `matched_boundary`).
2059            if micro_boundary_skip && boundary_extent(boundary) <= coincidence_tolerance {
2060                continue;
2061            }
2062            let forward = boundary.start.sub(chain.start).length() <= coincidence_tolerance
2063                && boundary.end.sub(chain.end).length() <= coincidence_tolerance;
2064            let reversed = boundary.start.sub(chain.end).length() <= coincidence_tolerance
2065                && boundary.end.sub(chain.start).length() <= coincidence_tolerance;
2066            let same_end = |a: Vec2, b: Vec2| a.sub(b).length() <= coincidence_tolerance || on_one_pole(a, b);
2067            let (forward, reversed, at_pole) = if forward || reversed || !pole_ends || degenerate_chains.is_empty() {
2068                (forward, reversed, false)
2069            } else {
2070                let forward = same_end(boundary.start, chain.start) && same_end(boundary.end, chain.end);
2071                let reversed = same_end(boundary.start, chain.end) && same_end(boundary.end, chain.start);
2072                (forward, reversed, true)
2073            };
2074            if !(forward || reversed) {
2075                continue;
2076            }
2077            let interior_coincident = if at_pole {
2078                coincident_in_space(chain, boundary, false)
2079            } else {
2080                chain.segments.iter().all(|(a, b)| {
2081                    near_chain(*a, boundary, coincidence_tolerance)
2082                        && near_chain(*b, boundary, coincidence_tolerance)
2083                        && near_chain(a.add(*b).scale(0.5), boundary, midpoint_tolerance)
2084                })
2085            };
2086            if !interior_coincident {
2087                continue;
2088            }
2089            // UV proximity only nominates a duplicate. A real cap lens can
2090            // be narrower than that chart-space search band while its two
2091            // arcs are distinct in 3D. Discard the cut only when the section
2092            // follows the boundary within model identity, not the repair band.
2093            // Endpoint anchoring can turn a very short cut and boundary into
2094            // the SAME chart segment even when their pre-anchor 3D curves
2095            // differ. Such identical constraints cannot enclose a region;
2096            // keeping both would corrupt arrangement cycle extraction.
2097            let identical_segment = chain.segments.len() == 1
2098                && boundary.segments.len() == 1
2099                && ((chain.start.sub(boundary.start).length() <= node_tolerance
2100                    && chain.end.sub(boundary.end).length() <= node_tolerance)
2101                    || (chain.start.sub(boundary.end).length() <= node_tolerance
2102                        && chain.end.sub(boundary.start).length() <= node_tolerance));
2103            if !identical_segment
2104                && std::env::var("BREP_DUP_CUT_GEOMETRY").as_deref() != Ok("0")
2105                && !coincident_in_space(chain, boundary, true)
2106            {
2107                continue;
2108            }
2109            if corner_veto_enabled {
2110                // Pair each cut endpoint with the boundary endpoint it matched.
2111                let (bnd_for_start, bnd_for_end) = if forward {
2112                    (boundary.start, boundary.end)
2113                } else {
2114                    (boundary.end, boundary.start)
2115                };
2116                if terminates_at_distinct_boundary_vertex(chain.start, bnd_for_start)
2117                    || terminates_at_distinct_boundary_vertex(chain.end, bnd_for_end)
2118                {
2119                    continue;
2120                }
2121            }
2122            matched_boundary = Some(boundary_index);
2123            break;
2124        }
2125        if let Some(boundary_index) = matched_boundary {
2126            if debug_drop {
2127                let boundary = &chains[boundary_index];
2128                eprintln!(
2129                    "  drop cut chain {} as duplicate of boundary chain {} (endpoint gaps {:.3e}/{:.3e})",
2130                    index,
2131                    boundary_index,
2132                    boundary.start.sub(chain.start).length(),
2133                    boundary.end.sub(chain.end).length(),
2134                );
2135            }
2136            dropped_chains.insert(index);
2137        }
2138    }
2139    if !dropped_chains.is_empty() {
2140        segments.retain(|segment| {
2141            tag_chain(&segment.tag)
2142                .map(|chain| !dropped_chains.contains(&(chain as usize)))
2143                .unwrap_or(true)
2144        });
2145    }
2146
2147    let debug = env_read!("BREP_DEBUG_FRAG")
2148        .map(|value| value == face.id.to_string())
2149        .unwrap_or(false);
2150    if debug {
2151        eprintln!(
2152            "fragment_face {}: domain u={:?} v={:?} arr_tol={:.3e} chains={} segments={}",
2153            face.id,
2154            u_domain,
2155            v_domain,
2156            arrangement_tolerance,
2157            chains.len(),
2158            segments.len()
2159        );
2160        for (index, chain) in chains.iter().enumerate() {
2161            let kind = match &chain.source {
2162                ChainSource::Boundary { coedge, .. } => format!("boundary e{}", coedge.edge_id),
2163                ChainSource::Cut { piece_id, .. } => format!("cut p{piece_id}"),
2164            };
2165            eprintln!(
2166                "  chain {index} {kind} count={} start=({:.9},{:.9}) end=({:.9},{:.9})",
2167                chain.count, chain.start.x, chain.start.y, chain.end.x, chain.end.y
2168            );
2169        }
2170    }
2171    // TRIPLE-POINT CUT-CHAIN BRIDGE (imported-geometry corner rescue).
2172    // Two SSI cut curves that meet at a triple point (two faces of one operand
2173    // both crossing a single face of the other) can be marched to endpoints that
2174    // DISAGREE by more than arr_tol when the operand's shared edge carries an
2175    // imported edge<->vertex gap — the imprint then mints TWO vertices for the
2176    // one corner, so the cut chain is BROKEN there. A broken cut cannot separate
2177    // the domain: the arrangement returns one region covering the whole face, the
2178    // face is classified by a single test point and wrongly dropped, and its
2179    // neighbours' shared SSI edges are stranded one-use (non-integral genus).
2180    // Reconnect a pair of cut-chain endpoints that BOTH dangle in the interior
2181    // (each neither on a domain boundary nor meeting any other chain endpoint)
2182    // and whose chains are EACH anchored at their other end, by snapping them to
2183    // their midpoint. Gated on the dangling-anchored-pair precondition, which
2184    // only a broken cut produces, so a face whose cuts already connect (every
2185    // currently-succeeding fragmentation) is never touched.
2186    if chains.iter().any(|c| matches!(c.source, ChainSource::Cut { .. })) {
2187        let endpoints: Vec<(usize, bool, Vec2)> = chains
2188            .iter()
2189            .enumerate()
2190            .flat_map(|(i, c)| [(i, false, c.start), (i, true, c.end)])
2191            .collect();
2192        let anchored = |chain: usize, point: Vec2| -> bool {
2193            boundary_side(point).is_some()
2194                || endpoints.iter().any(|(other_chain, _, other_point)| {
2195                    *other_chain != chain
2196                        && other_point.sub(point).length() <= junction_radius
2197                })
2198        };
2199        // Interior cut endpoints with an anchored far end are the loose ends of
2200        // an almost-through cut. Only these are bridge candidates.
2201        //
2202        // OVERSHOOT-STUB EXCLUSION (offset-shell triple junctions). A pairwise
2203        // section between offset carriers is clipped to the offset IMAGE of the
2204        // source trims, which can extend PAST the true junction with a third
2205        // carrier's section instead of stopping at it (O.S14: the plane×cylinder
2206        // line runs to the source cone∩cylinder circle image at y=100/13 while
2207        // the plane×cone section crosses it ~0.3 earlier at the real offset
2208        // junction). Such a chain is already CONNECTED into the cut graph:
2209        // arrange_segments splits both chains at the crossing node and its
2210        // degree-1 pruning drops the overshoot stub beyond it, and build_loop
2211        // emits the surviving partial runs as Derived sub-curves. The stub's
2212        // dangling endpoint is therefore NOT a broken-junction loose end —
2213        // bridging it would drag a chain end to a midpoint off the section
2214        // (a wrong patch) and the 3D gate would refuse a face the arrangement
2215        // handles exactly. Exclude an endpoint from bridge candidacy when its
2216        // chain intersects another CUT chain at a point interior to the chain
2217        // (beyond the junction radius of both its endpoints — an intersection
2218        // AT the far anchor is the ordinary shared-junction meeting and must
2219        // keep the endpoint eligible, which preserves the imported-geometry
2220        // broken-cut rescue: those chains stop SHORT of each other and have no
2221        // crossing at all).
2222        let cut_chain_has_interior_crossing = |i: usize| -> bool {
2223            let chain = &chains[i];
2224            chains.iter().enumerate().any(|(j, other)| {
2225                // A boundary-duplicate chain was dropped from the arrangement's
2226                // segment set; a crossing with it would not materialize a node.
2227                if j == i
2228                    || dropped_chains.contains(&j)
2229                    || !matches!(other.source, ChainSource::Cut { .. })
2230                {
2231                    return false;
2232                }
2233                chain.segments.iter().any(|&(a0, a1)| {
2234                    other.segments.iter().any(|&(b0, b1)| {
2235                        let Some([t, _]) = crate::arrangement::segment_intersection(
2236                            a0,
2237                            a1,
2238                            b0,
2239                            b1,
2240                            arrangement_tolerance,
2241                        ) else {
2242                            return false;
2243                        };
2244                        let crossing = a0.add(a1.sub(a0).scale(t));
2245                        crossing.sub(chain.start).length() > junction_radius
2246                            && crossing.sub(chain.end).length() > junction_radius
2247                    })
2248                })
2249            })
2250        };
2251        let boundary_anchor = bridge_boundary_t_junction_anchor_enabled();
2252        let lies_on_another_cut_run = |i: usize, point: Vec2| -> bool {
2253            bridge_t_junction_anchor_enabled()
2254                && chains.iter().enumerate().any(|(j, other)| {
2255                    j != i
2256                        && !dropped_chains.contains(&j)
2257                        && (boundary_anchor || matches!(other.source, ChainSource::Cut { .. }))
2258                        && other.segments.iter().any(|&(a, b)| {
2259                            let along = b.sub(a);
2260                            let span = along.dot(along);
2261                            let t = if span > 0.0 {
2262                                (point.sub(a).dot(along) / span).clamp(0.0, 1.0)
2263                            } else {
2264                                0.0
2265                            };
2266                            a.add(along.scale(t)).sub(point).length() <= arrangement_tolerance
2267                        })
2268                })
2269        };
2270        let mut loose: Vec<(usize, bool, Vec2)> = Vec::new();
2271        for (i, c) in chains.iter().enumerate() {
2272            if !matches!(c.source, ChainSource::Cut { .. }) {
2273                continue;
2274            }
2275            for (is_end, this, other) in [(false, c.start, c.end), (true, c.end, c.start)] {
2276                if !anchored(i, this) && anchored(i, other) {
2277                    if lies_on_another_cut_run(i, this) {
2278                        if debug {
2279                            eprintln!("  cut chain {i} end {} is a T-junction on another chain's run", if is_end { "end" } else { "start" });
2280                        }
2281                        continue;
2282                    }
2283                    if cut_chain_has_interior_crossing(i) {
2284                        if debug {
2285                            eprintln!(
2286                                "  cut chain {i} loose {} excluded from junction bridging — \
2287                                 the chain crosses another cut chain mid-run; arrangement \
2288                                 pruning owns the overshoot stub",
2289                                if is_end { "end" } else { "start" },
2290                            );
2291                        }
2292                        continue;
2293                    }
2294                    loose.push((i, is_end, this));
2295                }
2296            }
2297        }
2298        // A triple-point disagreement on imported geometry runs a few 1e-4 (the
2299        // edge<->vertex gap), well under a percent of the face diagonal; bound the
2300        // bridge span so two unrelated loose cuts across a face are never joined.
2301        let bridge_band = (diagonal * 0.02).max(junction_radius * 4.0);
2302        if debug && !loose.is_empty() {
2303            eprintln!("  junction_radius={junction_radius:.6} bridge_band={bridge_band:.6} loose={loose:?}");
2304        }
2305        let skip_crossing_pairs = bridge_skip_crossing_pairs_enabled();
2306        let chains_cross = |i: usize, j: usize| -> bool {
2307            chains[i].segments.iter().any(|&(a0, a1)| {
2308                chains[j].segments.iter().any(|&(b0, b1)| {
2309                    crate::arrangement::segment_intersection(a0, a1, b0, b1, arrangement_tolerance).is_some()
2310                })
2311            })
2312        };
2313        let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
2314        for a in 0..loose.len() {
2315            for b in (a + 1)..loose.len() {
2316                if loose[a].0 == loose[b].0 {
2317                    continue; // never bridge a chain to itself
2318                }
2319                if skip_crossing_pairs && chains_cross(loose[a].0, loose[b].0) {
2320                    if debug {
2321                        eprintln!("  loose ends of chains {} and {} are not bridged: the chains cross", loose[a].0, loose[b].0);
2322                    }
2323                    continue;
2324                }
2325                let gap = loose[a].2.sub(loose[b].2).length();
2326                if gap <= bridge_band {
2327                    pairs.push((gap, a, b));
2328                }
2329            }
2330        }
2331        pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
2332        // 3D-DISTANCE CORROBORATION (case 08:10-genus, secondary defect): the
2333        // 2% UV band is metric-blind — on a big-carrier face (full-sphere
2334        // domain [0,1]² spanning hundreds of mm) it silently bridged loose
2335        // ends 8-14 mm apart in 3D, manufacturing UV-closed but 3D-OPEN loops
2336        // ("loop open between coedges" at assembly). A legitimate bridge heals
2337        // a triple-point disagreement (imported edge<->vertex gap, a small
2338        // fraction of the face scale); an impossible one spans a real missing
2339        // piece. Corroborate every candidate pair in 3D: evaluate the surface
2340        // at both (wrapped-back) loose ends and REFUSE — loudly, as a
2341        // missing-piece error — when their 3D gap exceeds 1% of the face's 3D
2342        // diameter (estimated over a coarse full-domain grid; on a small trim
2343        // of a big carrier this overstates the diameter, i.e. errs LENIENT —
2344        // the safe direction). Any probe evaluation failure falls back to the
2345        // old silent bridging (a diagnostic must not fail the operation).
2346        // Escape hatch: BREP_BRIDGE_3D_GATE=0 restores unconditional bridging.
2347        let bridge_3d_gate = std::env::var("BREP_BRIDGE_3D_GATE").as_deref() != Ok("0");
2348        let face_diameter3 = if bridge_3d_gate && !pairs.is_empty() {
2349            let mut samples: Vec<Vec3> = Vec::new();
2350            'grid: for i in 0..3 {
2351                for j in 0..3 {
2352                    let u = u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 2.0;
2353                    let v = v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 2.0;
2354                    match face.surface.evaluate(u, v) {
2355                        Ok(point) => samples.push(point),
2356                        Err(_) => {
2357                            samples.clear();
2358                            break 'grid;
2359                        }
2360                    }
2361                }
2362            }
2363            let mut diameter = 0.0f64;
2364            for (index, a) in samples.iter().enumerate() {
2365                for b in samples.iter().skip(index + 1) {
2366                    diameter = diameter.max(a.sub(*b).length());
2367                }
2368            }
2369            (diameter > 0.0).then_some(diameter)
2370        } else {
2371            None
2372        };
2373        let mut consumed = vec![false; loose.len()];
2374        let mut bridged = 0usize;
2375        for (gap, a, b) in pairs {
2376            if consumed[a] || consumed[b] {
2377                continue;
2378            }
2379            consumed[a] = true;
2380            consumed[b] = true;
2381            let (chain_a, _, point_a) = loose[a];
2382            let (chain_b, _, point_b) = loose[b];
2383            if let Some(diameter) = face_diameter3 {
2384                let wrapped_a = wrap_back(point_a);
2385                let wrapped_b = wrap_back(point_b);
2386                if let (Ok(position_a), Ok(position_b)) = (
2387                    face.surface.evaluate(wrapped_a.x, wrapped_a.y),
2388                    face.surface.evaluate(wrapped_b.x, wrapped_b.y),
2389                ) {
2390                    let gap3 = position_a.sub(position_b).length();
2391                    let limit = 0.01 * diameter;
2392                    if gap3 > limit {
2393                        return Err(KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", format!(
2394                            "fragment_face {}: cut junction bridge refused — 3D gap \
2395                             {gap3:.4} exceeds {limit:.4} (1% of face diameter \
2396                             {diameter:.4}) across uv gap {gap:.6}; a section piece \
2397                             is missing between chains {chain_a} and {chain_b}",
2398                            face.id
2399                        )));
2400                    }
2401                }
2402            }
2403            let midpoint = point_a.add(point_b).scale(0.5);
2404            if debug {
2405                eprintln!(
2406                    "  bridging chain {chain_a} at ({:.9},{:.9}) and chain {chain_b} at ({:.9},{:.9}), uv gap {gap:.6}",
2407                    point_a.x, point_a.y, point_b.x, point_b.y
2408                );
2409            }
2410            for (chain, old) in [(chain_a, point_a), (chain_b, point_b)] {
2411                if chains[chain].start.sub(old).length() <= 1e-15 {
2412                    chains[chain].start = midpoint;
2413                }
2414                if chains[chain].end.sub(old).length() <= 1e-15 {
2415                    chains[chain].end = midpoint;
2416                }
2417                for seg in &mut chains[chain].segments {
2418                    if seg.0.sub(old).length() <= 1e-15 {
2419                        seg.0 = midpoint;
2420                    }
2421                    if seg.1.sub(old).length() <= 1e-15 {
2422                        seg.1 = midpoint;
2423                    }
2424                }
2425                for segment in segments.iter_mut() {
2426                    if tag_chain(&segment.tag) != Some(chain as u64) {
2427                        continue;
2428                    }
2429                    if segment.a.sub(old).length() <= 1e-15 {
2430                        segment.a = midpoint;
2431                    }
2432                    if segment.b.sub(old).length() <= 1e-15 {
2433                        segment.b = midpoint;
2434                    }
2435                }
2436            }
2437            bridged += 1;
2438        }
2439        if debug && bridged > 0 {
2440            eprintln!("  bridged {bridged} broken cut junction(s)");
2441        }
2442    }
2443    // GRAZE-BAND COMMON-BLOCK — near-tangent hook absorption (member t548,
2444    // fixture 28). fragment_face runs on the ALREADY edge-split solid, so
2445    // every imprint-minted section×boundary crossing is already a chain endpoint
2446    // by construction. A near-tangent SSI section ending at a shared junction
2447    // vertex can HOOK in its last span: its sampled pcurve overshoots and crosses
2448    // the boundary edge a graze before reaching the shared endpoint (the crossing
2449    // add_edge_split already REFUSED as sub-weld, so the imprint minted only the
2450    // shared vertex). arrange_segments, seeing the linearised hook, re-invents that
2451    // crossing as a distinct INTERIOR point Q, splits the boundary there, and
2452    // spawns a sub-band micro-stub that strands one-use at assembly (t548's
2453    // A→B→C needle). Absorb it deterministically: when a Cut chain and a Boundary
2454    // chain SHARE an endpoint node P, and the cut's polyline crosses that boundary
2455    // at an interior point Q within a MEASURED band of P (3D via surface.evaluate;
2456    // ceiling = the residual-merge sep_cap family, never grown, never the poisoned
2457    // projector), CLIP the cut's hooked tail — drop the samples between the
2458    // crossing and P and run straight into P. The cut's SOURCE curve is untouched,
2459    // so the complete-run path in build_loop still emits the full section edge to
2460    // P; only the spurious arrangement self-crossing is removed. This is the
2461    // arrangement sibling of BREP_SAG_CROSSING_GUARD ("sag refinement may REMOVE a
2462    // crossing but never ADD one"): the arrangement may not invent a boundary
2463    // crossing the imprint did not mint. The structural gate (shared endpoint +
2464    // strictly-interior sub-band crossing) keeps it off legitimate transversals —
2465    // an interior crossing BEYOND the band bails the chain untouched. Generalising
2466    // that gate to Cut×Cut pairs over a measured junction blob was tried and
2467    // falsified as a structural no-op: a crossing in the junction-ADJACENT first
2468    // segment leaves keep_lo=1 reconnecting an identical polyline, and two arms
2469    // that DIVERGE from a shared junction cannot be uncrossed by clipping — this
2470    // absorbs a multi-segment overshoot-and-return hook only. Escape hatch
2471    // BREP_GRAZE_HOOK_CLIP=0.
2472    if std::env::var("BREP_GRAZE_HOOK_CLIP").as_deref() != Ok("0") {
2473        let raw_extent = if solid.vertices.is_empty() {
2474            0.0
2475        } else {
2476            let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2477            let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2478            for v in &solid.vertices {
2479                lo.x = lo.x.min(v.point.x);
2480                lo.y = lo.y.min(v.point.y);
2481                lo.z = lo.z.min(v.point.z);
2482                hi.x = hi.x.max(v.point.x);
2483                hi.y = hi.y.max(v.point.y);
2484                hi.z = hi.z.max(v.point.z);
2485            }
2486            hi.sub(lo).length()
2487        };
2488        // Mirror imprint::residual_merge_bands' sep_cap (the measured junction-radius
2489        // family, 1.5e-3·extent, floored by the achieved weld band) — the largest
2490        // near-tangent hook a shared-junction section can plausibly span.
2491        let band = 2.0 * 1e-5 * raw_extent.max(1.0);
2492        let sep_cap = (1.5e-3 * raw_extent).max(band);
2493        let graze_debug = debug || std::env::var("BREP_DEBUG_GRAZE").as_deref() == Ok("1");
2494
2495        let mut plans: Vec<(usize, Vec<(Vec2, Vec2)>, f64)> = Vec::new();
2496        for ci in 0..chains.len() {
2497            if !matches!(chains[ci].source, ChainSource::Cut { .. }) {
2498                continue;
2499            }
2500            // A chain already dropped as a boundary duplicate has had its flat
2501            // `segments` removed; never re-materialise it below.
2502            if dropped_chains.contains(&ci) {
2503                continue;
2504            }
2505            if chains[ci].segments.is_empty() {
2506                continue;
2507            }
2508            let mut lo_cut: Option<usize> = None; // clip a start hook after this seg
2509            let mut hi_cut: Option<usize> = None; // clip an end hook from this seg on
2510            let mut measured = 0.0f64;
2511            let mut bail = false;
2512            for &at_end in &[false, true] {
2513                let p = if at_end {
2514                    chains[ci].end
2515                } else {
2516                    chains[ci].start
2517                };
2518                let Ok(p3) = face.surface.evaluate(p.x, p.y) else {
2519                    continue;
2520                };
2521                for bi in 0..chains.len() {
2522                    if bi == ci || !matches!(chains[bi].source, ChainSource::Boundary { .. }) {
2523                        continue;
2524                    }
2525                    let shares = chains[bi].start.sub(p).length() <= node_tolerance
2526                        || chains[bi].end.sub(p).length() <= node_tolerance;
2527                    if !shares {
2528                        continue;
2529                    }
2530                    for si in 0..chains[ci].segments.len() {
2531                        let (sa, sb) = chains[ci].segments[si];
2532                        for &(ba, bb) in &chains[bi].segments {
2533                            let Some([t1, t2]) = crate::arrangement::segment_intersection(
2534                                sa,
2535                                sb,
2536                                ba,
2537                                bb,
2538                                arrangement_tolerance,
2539                            ) else {
2540                                continue;
2541                            };
2542                            // Strictly interior on BOTH segments: not the shared-node
2543                            // touch (t≈0/1) and not a boundary-endpoint (imprint-minted)
2544                            // crossing (t2≈0/1) — an arrangement-invented self-crossing.
2545                            if !(t1 > 1e-3 && t1 < 1.0 - 1e-3 && t2 > 1e-3 && t2 < 1.0 - 1e-3) {
2546                                continue;
2547                            }
2548                            let q = Vec2 {
2549                                x: sa.x + (sb.x - sa.x) * t1,
2550                                y: sa.y + (sb.y - sa.y) * t1,
2551                            };
2552                            let Ok(q3) = face.surface.evaluate(q.x, q.y) else {
2553                                continue;
2554                            };
2555                            let dist = q3.sub(p3).length();
2556                            if dist > sep_cap {
2557                                // A genuine transversal far from the shared vertex —
2558                                // preserve current behaviour, touch nothing.
2559                                bail = true;
2560                                break;
2561                            }
2562                            measured = measured.max(dist);
2563                            if at_end {
2564                                hi_cut = Some(hi_cut.map_or(si, |m| m.min(si)));
2565                            } else {
2566                                lo_cut = Some(lo_cut.map_or(si, |m| m.max(si)));
2567                            }
2568                        }
2569                        if bail {
2570                            break;
2571                        }
2572                    }
2573                    if bail {
2574                        break;
2575                    }
2576                }
2577                if bail {
2578                    break;
2579                }
2580            }
2581            if bail || (lo_cut.is_none() && hi_cut.is_none()) {
2582                continue;
2583            }
2584            let segs = &chains[ci].segments;
2585            let keep_lo = lo_cut.map(|m| m + 1).unwrap_or(0);
2586            let keep_hi = hi_cut.unwrap_or(segs.len());
2587            if keep_lo >= keep_hi {
2588                continue;
2589            }
2590            let mut points: Vec<Vec2> = Vec::with_capacity(keep_hi - keep_lo + 3);
2591            if lo_cut.is_some() {
2592                points.push(chains[ci].start);
2593            }
2594            points.push(segs[keep_lo].0);
2595            for si in keep_lo..keep_hi {
2596                points.push(segs[si].1);
2597            }
2598            if hi_cut.is_some() {
2599                points.push(chains[ci].end);
2600            }
2601            let new_segments: Vec<(Vec2, Vec2)> = points
2602                .windows(2)
2603                .filter(|w| w[0].sub(w[1]).length() > 0.0)
2604                .map(|w| (w[0], w[1]))
2605                .collect();
2606            if new_segments.is_empty() {
2607                continue;
2608            }
2609            if graze_debug {
2610                eprintln!(
2611                    "graze-hook-clip: face {} cut chain {} measured_band={:.3e} sep_cap={:.3e} \
2612                     segs {} -> {} (lo_cut={:?} hi_cut={:?})",
2613                    face.id,
2614                    ci,
2615                    measured,
2616                    sep_cap,
2617                    chains[ci].segments.len(),
2618                    new_segments.len(),
2619                    lo_cut,
2620                    hi_cut
2621                );
2622            }
2623            plans.push((ci, new_segments, measured));
2624        }
2625        for (ci, new_segments, _) in plans {
2626            chains[ci].count = new_segments.len();
2627            chains[ci].segments = new_segments.clone();
2628            segments.retain(|s| tag_chain(&s.tag) != Some(ci as u64));
2629            for (segment_index, (a, b)) in new_segments.into_iter().enumerate() {
2630                segments.push(Segment2 {
2631                    a,
2632                    b,
2633                    tag: segment_tag(ci, segment_index),
2634                });
2635            }
2636        }
2637    }
2638    profile.dedup_bridge += profile.lap(lap_start);
2639    profile.arranged_faces += 1;
2640    let regions = arrange_segments(&segments, arrangement_tolerance).or_refuse(KernelStage::Fragment, "arrange_segments")?;
2641    profile.arrange += profile.lap(lap_start);
2642    profile.region_faces += 1;
2643    // Orient every rebuilt loop the way the SOURCE face's own loops are
2644    // oriented, rather than assuming `same_sense` predicts it. The two agree on
2645    // every face whose chart is right-handed against its normal, so this is a
2646    // no-op there; it differs only on a face the old assumption got wrong, and
2647    // getting it wrong reverses that face's whole fragment. Falls back to the
2648    // old rule whenever the source winding cannot be read (see the helper).
2649    // Escape hatch for A/B against the old behaviour.
2650    let source_winding = if std::env::var("BREP_FRAGMENT_SOURCE_WINDING").as_deref() == Ok("0") {
2651        None
2652    } else {
2653        source_loop_winding_negative(face)?
2654    };
2655    let reverse_loops = source_winding.unwrap_or(!face.same_sense);
2656    if debug && reverse_loops != !face.same_sense {
2657        eprintln!(
2658            "  face {}: source loop winds {} against same_sense={} — orienting fragments to the source",
2659            face.id,
2660            if reverse_loops { "CW" } else { "CCW" },
2661            face.same_sense
2662        );
2663    }
2664    // Section pieces the arrangement bounded no region with: a piece that ends
2665    // inside the face (the ruling along which a cylinder merely touches this
2666    // wall) splits nothing, and the region's points are found from the region's
2667    // boundary alone, so one can land on the piece itself, where the face
2668    // touches the other body and reads as lying ON it.
2669    let stray_pieces: Vec<Vec<Vec2>> = if stray_piece_clearance_enabled() {
2670        let used: HashSet<u64> = regions
2671            .iter()
2672            .flat_map(|region| region.outer.iter().chain(region.holes.iter().flatten()))
2673            .filter_map(|usage| tag_chain(&usage.piece.parent.tag))
2674            .collect();
2675        chains
2676            .iter()
2677            .enumerate()
2678            .filter(|(index, chain)| matches!(chain.source, ChainSource::Cut { .. }) && !chain.segments.is_empty() && !used.contains(&(*index as u64)))
2679            .map(|(_, chain)| {
2680                // There and back: a closed path of no area, read as a hole's boundary.
2681                let mut path: Vec<Vec2> = chain.segments.iter().map(|segment| segment.0).collect();
2682                path.push(chain.segments[chain.segments.len() - 1].1);
2683                let back: Vec<Vec2> = path[1..path.len() - 1].iter().rev().copied().collect();
2684                path.extend(back);
2685                path
2686            })
2687            .collect()
2688    } else {
2689        Vec::new()
2690    };
2691    let mut fragments = Vec::new();
2692    for mut region in regions {
2693        super::loops::detach_touched_closed_boundaries(&mut region, &chains, arrangement_tolerance)?;
2694        let order = FragmentOrder {
2695            area: region.outer_area,
2696            key: super::loops::region_topology_key(&region.outer, &region.holes),
2697        };
2698        let mut region_lap = profile.enabled.then(Instant::now);
2699        let arranged: Vec<Vec2> = if stray_pieces.is_empty() {
2700            interior_points(&region.outer, &region.holes, region.area, 3)
2701        } else {
2702            super::loops::interior_points_clear_of(&region.outer, &region.holes, &stray_pieces, region.area, 3)
2703        };
2704        let interior_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
2705        let candidates: Vec<Vec2> = arranged.iter().copied().map(wrap_back).collect();
2706        let Some(&test_uv) = candidates.first() else {
2707            if debug {
2708                eprintln!("  region area={:.6e}: no interior point", region.area);
2709            }
2710            continue;
2711        };
2712        let mut containment = parameter_point_in_face(face, test_uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
2713        // TRIM-FRAME CONTAINMENT. A face whose own pcurves run past its
2714        // carrier's domain (helmet Face_15: its trim spans u in
2715        // [-0.178, 0.298] on a carrier closed in u, drawn without a hop) is
2716        // arranged in that frame, and the region's point is on the face there.
2717        // Its wrapped image (u = 0.970 for -0.030) lies on no trim polygon,
2718        // and containment has no period image to try for a trim that never
2719        // hops the seam, so it reads Outside and the region was dropped: the
2720        // face's y >= 0 piece in `20_helmet_merge_stage` b - a, whose section
2721        // edges then stood one-use. With no band re-base the arrangement's
2722        // frame is the trim's own, so the region's point is asked there as
2723        // well. Escape hatch `BREP_REGION_TRIM_FRAME=0`.
2724        if containment != PolygonClass::Inside
2725            && band_rebase == [None, None]
2726            && (arranged[0].x != test_uv.x || arranged[0].y != test_uv.y)
2727            && std::env::var("BREP_REGION_TRIM_FRAME").as_deref() != Ok("0")
2728        {
2729            containment = parameter_point_in_face(face, arranged[0], 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
2730            if debug {
2731                eprintln!(
2732                    "  region area={:.6e} test=({:.9},{:.9}) asked in the trim's frame at ({:.9},{:.9}): {:?}",
2733                    region.area, test_uv.x, test_uv.y, arranged[0].x, arranged[0].y,
2734                    containment == PolygonClass::Inside
2735                );
2736            }
2737        }
2738        if containment != PolygonClass::Inside {
2739            if debug {
2740                eprintln!(
2741                    "  region area={:.6e} test=({:.9},{:.9}): outside trimmed face",
2742                    region.area, test_uv.x, test_uv.y
2743                );
2744            }
2745            continue;
2746        }
2747        if debug {
2748            eprintln!(
2749                "  region area={:.6e} test=({:.9},{:.9}): KEPT",
2750                region.area, test_uv.x, test_uv.y
2751            );
2752        }
2753        let containment_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
2754        let Some(outer_loop) = build_loop(
2755            &region.outer,
2756            reverse_loops,
2757            &chains,
2758            arrangement_tolerance,
2759            &face.surface,
2760        )?
2761        else {
2762            // Spurious zero-area antenna region (e.g. a seam-grazing fold on a
2763            // periodic band); it bounds no material, so drop it.
2764            if debug {
2765                eprintln!("  region area={:.6e}: dropped (degenerate antenna)", region.area);
2766            }
2767            continue;
2768        };
2769        let mut loops = vec![outer_loop];
2770        for hole in &region.holes {
2771            // Holes take the SAME flag as the outer loop: the arrangement
2772            // hands them back already wound against it, so reversing both
2773            // together keeps them opposite.
2774            if let Some(hole_loop) = build_loop(
2775                hole,
2776                reverse_loops,
2777                &chains,
2778                arrangement_tolerance,
2779                &face.surface,
2780            )? {
2781                loops.push(hole_loop);
2782            }
2783        }
2784        for loop_record in &mut loops {
2785            for coedge in &mut loop_record.coedges {
2786                if let FragmentEdgeSource::Boundary {
2787                    operand: source_operand,
2788                    ..
2789                } = &mut coedge.source
2790                {
2791                    *source_operand = operand;
2792                }
2793            }
2794        }
2795        let mut extra_test_points = Vec::new();
2796        for &candidate in candidates.iter().skip(1) {
2797            if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
2798                extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
2799            }
2800        }
2801        if profile.enabled {
2802            crate::imprint::profile_emit(format_args!("fragment.region face={} edges={} holes={} interior={interior_ms:.3} containment={containment_ms:.3} loops={:.3}",
2803                face.id, region.outer.len(), region.holes.len(), profile.lap(&mut region_lap).as_secs_f64() * 1000.0));
2804        }
2805        fragments.push(FaceFragmentRecord {
2806            operand,
2807            source_face_id: face.id,
2808            surface: face.surface.clone(),
2809            same_sense: face.same_sense,
2810            loops,
2811            test_point: face.surface.evaluate(test_uv.x, test_uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
2812            test_uv,
2813            extra_test_points,
2814            order: Some(order),
2815        });
2816    }
2817
2818    // Rescue an UNCUT face the flat 2D arrangement failed to reconstruct.
2819    // A seam-closed multi-loop face (a band on a surface of revolution, whose
2820    // param-space loops only close across the u/v seam, or a holed face whose
2821    // domain centre lands in the hole so the fast path above declined it)
2822    // collapses to zero-area lines in the [0,1]^2 arrangement and yields NO
2823    // region -> the face is dropped entirely, stranding its neighbours' shared
2824    // edges as one-use and knocking the assembly's genus off an integer. Since
2825    // the face is uncut, its loops already describe the exact trimmed boundary,
2826    // so pass the unchanged face through — we only need a valid interior test
2827    // point, found by gridding the ACTUAL knot domain. Gated on
2828    // `fragments.is_empty()`, this never touches a face the arrangement handled.
2829    profile.regions += profile.lap(lap_start);
2830    if fragments.is_empty() && piece_ids.is_empty() {
2831        const GRID: usize = 12;
2832        let mut test_uv: Option<Vec2> = None;
2833        let mut extra_test_points: Vec<Vec3> = Vec::new();
2834        'search: for iu in 1..GRID {
2835            for iv in 1..GRID {
2836                let candidate = Vec2 {
2837                    x: u_domain[0] + (u_domain[1] - u_domain[0]) * iu as f64 / GRID as f64,
2838                    y: v_domain[0] + (v_domain[1] - v_domain[0]) * iv as f64 / GRID as f64,
2839                };
2840                if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
2841                    if test_uv.is_none() {
2842                        test_uv = Some(candidate);
2843                    } else {
2844                        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
2845                        if extra_test_points.len() >= 2 {
2846                            break 'search;
2847                        }
2848                    }
2849                }
2850            }
2851        }
2852        // SEAM-STRADDLING BAND fallback (a SINGLY-periodic surface of
2853        // revolution whose trim loop closes only ACROSS the u/v seam — e.g. a
2854        // rounded imported cap grazed near-tangent, so it stays uncut). The
2855        // even-odd `parameter_point_in_face` reads Outside EVERYWHERE on such a
2856        // loop (the seam hop makes the [0,1]^2 polygon non-simple), so the knot
2857        // grid above finds nothing and the face would still drop. `seam_band_
2858        // point_in_face` only covers the DOUBLY-periodic (torus) case, so the
2859        // singly-periodic band has no seam-aware classifier. Unwrap the loop
2860        // onto the surface's covering plane (`loop_seam_offsets`, the same fold
2861        // the mass integrator and tessellator use), where it IS a simple
2862        // polygon, grid that unwrapped bbox with the plain even-odd test, and
2863        // map an interior hit back into the domain. Runs ONLY when the grid
2864        // already failed AND the offsets show the loop truly straddled a seam
2865        // (a full-wrap rim yields all-zero offsets and is left untouched), so it
2866        // never changes a face any earlier path handled.
2867        if test_uv.is_none() {
2868            let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2869            if closed_u || closed_v {
2870                let u_period = u_domain[1] - u_domain[0];
2871                let v_period = v_domain[1] - v_domain[0];
2872                let mut loop_polygons: Vec<Vec<Vec2>> = Vec::new();
2873                let mut straddled = false;
2874                let (mut umin, mut umax, mut vmin, mut vmax) = (
2875                    f64::INFINITY,
2876                    f64::NEG_INFINITY,
2877                    f64::INFINITY,
2878                    f64::NEG_INFINITY,
2879                );
2880                for loop_record in &face.loops {
2881                    let offsets = crate::topology::loop_seam_offsets(
2882                        &loop_record.coedges,
2883                        closed_u,
2884                        closed_v,
2885                        u_period,
2886                        v_period,
2887                    ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?;
2888                    if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
2889                        straddled = true;
2890                    }
2891                    let mut polygon = Vec::new();
2892                    for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
2893                        let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
2894                        let samples = 32usize;
2895                        for k in 0..samples {
2896                            let t = d0 + (d1 - d0) * k as f64 / samples as f64;
2897                            let p = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Fragment, "evaluate")?;
2898                            let uv = Vec2 {
2899                                x: p.x + offsets[coedge_index][0],
2900                                y: p.y + offsets[coedge_index][1],
2901                            };
2902                            umin = umin.min(uv.x);
2903                            umax = umax.max(uv.x);
2904                            vmin = vmin.min(uv.y);
2905                            vmax = vmax.max(uv.y);
2906                            polygon.push(uv);
2907                        }
2908                    }
2909                    loop_polygons.push(polygon);
2910                }
2911                if straddled && umax > umin && vmax > vmin {
2912                    let wrap = |value: f64, lo: f64, span: f64| {
2913                        if span > 0.0 {
2914                            lo + (value - lo).rem_euclid(span)
2915                        } else {
2916                            value
2917                        }
2918                    };
2919                    'seam: for iu in 1..GRID {
2920                        for iv in 1..GRID {
2921                            let cu = umin + (umax - umin) * iu as f64 / GRID as f64;
2922                            let cv = vmin + (vmax - vmin) * iv as f64 / GRID as f64;
2923                            let candidate = Vec2 { x: cu, y: cv };
2924                            // Even-odd fill across ALL unwrapped loops: interior
2925                            // of the trimmed region is where the winding is odd
2926                            // (outer loop minus any hole loops), independent of
2927                            // which loop is the outer one.
2928                            let winding = loop_polygons
2929                                .iter()
2930                                .filter(|polygon| point_in_polygon(candidate, polygon))
2931                                .count();
2932                            if winding % 2 == 0 {
2933                                continue;
2934                            }
2935                            let mapped = Vec2 {
2936                                x: if closed_u {
2937                                    wrap(cu, u_domain[0], u_period)
2938                                } else {
2939                                    cu
2940                                },
2941                                y: if closed_v {
2942                                    wrap(cv, v_domain[0], v_period)
2943                                } else {
2944                                    cv
2945                                },
2946                            };
2947                            if test_uv.is_none() {
2948                                test_uv = Some(mapped);
2949                            } else {
2950                                extra_test_points
2951                                    .push(face.surface.evaluate(mapped.x, mapped.y).or_refuse(KernelStage::Fragment, "evaluate")?);
2952                                if extra_test_points.len() >= 2 {
2953                                    break 'seam;
2954                                }
2955                            }
2956                        }
2957                    }
2958                }
2959            }
2960        }
2961        if let Some(uv) = test_uv {
2962            fragments.push(FaceFragmentRecord {
2963                operand,
2964                source_face_id: face.id,
2965                surface: face.surface.clone(),
2966                same_sense: face.same_sense,
2967                loops: face
2968                    .loops
2969                    .iter()
2970                    .map(|loop_record| FragmentLoop {
2971                        coedges: loop_record
2972                            .coedges
2973                            .iter()
2974                            .map(|coedge| FragmentCoedge {
2975                                source: FragmentEdgeSource::Boundary {
2976                                    operand,
2977                                    edge_id: coedge.edge_id,
2978                                },
2979                                forward: coedge.forward,
2980                                pcurve: coedge.pcurve.clone(),
2981                            })
2982                            .collect(),
2983                    })
2984                    .collect(),
2985                test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
2986                test_uv: uv,
2987                extra_test_points,
2988                order: None,
2989            });
2990        }
2991    }
2992    profile.rescue += profile.lap(lap_start);
2993    Ok(fragments)
2994}
2995
2996pub fn fragment_solid(
2997    solid: &BrepSolid,
2998    operand: u8,
2999    imprint: &ImprintResultRecord,
3000) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3001    fragment_solid_against(solid, operand, imprint, None)
3002}
3003
3004/// A positive rational carrier is enclosed by its control hull. Unknown or
3005/// non-finite weights/points cannot certify separation and keep the full path.
3006pub fn bounded_carriers(solid: &BrepSolid) -> bool {
3007    solid.shells.iter().flat_map(|s| &s.faces).all(|face| bounded_carrier(face))
3008}
3009
3010fn bounded_carrier(face: &FaceRecord) -> bool {
3011    let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return false };
3012    let positive_finite = |p: &crate::Vec4| {
3013        p.w > 0.0 && p.w.is_finite() && p.point().is_ok_and(|v|
3014            v.x.is_finite() && v.y.is_finite() && v.z.is_finite())
3015    };
3016    // Extended trims may live outside the carrier hull. Positive pcurve
3017    // controls within both knot domains certify the whole trim stays inside;
3018    // otherwise retain the existing extension/seam handling, without epsilon.
3019    // ROUNDING SLACK (`BREP_FRAGMENT_SCOPE_ULPS`, default on; `=0` restores the exact test): a trim that runs ALONG a domain
3020    // border carries controls a few ulps past it (a hole wall's seam at u = -7.8e-16 or
3021    // 1.0000000000000009, a bore's floor at 1.5200000000000002 of 1.52), and the exact test then
3022    // called every such carrier unbounded: on a part of countersunk seats and blind bores no face
3023    // was ever separated and each of 88 booleans arranged all ~500 faces to cut 6. A control within
3024    // `SCOPE_ULPS` ulps of the border moves the trim off the hull by that many ulps of the
3025    // carrier's size, orders below the separation band every caller adds.
3026    let slack = |d: [f64; 2]| if scope_ulps_on() { SCOPE_ULPS * f64::EPSILON * d[0].abs().max(d[1].abs()).max(d[1] - d[0]) } else { 0.0 };
3027    let (su, sv) = (slack(u), slack(v));
3028    face.surface.control_points.iter().flatten().all(positive_finite)
3029        && face.loops.iter().flat_map(|lp| &lp.coedges).all(|coedge| {
3030            coedge.pcurve.control_points.iter().all(|p| {
3031                positive_finite(p) && p.point().is_ok_and(|p|
3032                    p.x >= u[0] - su && p.x <= u[1] + su && p.y >= v[0] - sv && p.y <= v[1] + sv)
3033            })
3034        })
3035}
3036
3037/// The rounding slack of `bounded_carrier`'s trim test, in ulps of the domain.
3038const SCOPE_ULPS: f64 = 64.0;
3039
3040fn scope_ulps_on() -> bool {
3041    crate::switch!("BREP_FRAGMENT_SCOPE_ULPS", true)
3042}
3043
3044/// Exact control-hull separation, including the extended-trim guard.
3045pub fn face_separated(face: &FaceRecord, bounds: crate::Aabb, band: f64) -> bool {
3046    bounded_carrier(face) && crate::Aabb::from_surface_controls(&face.surface)
3047        .is_ok_and(|own| !own.intersects(bounds, band))
3048}
3049
3050/// A boundary witness suffices when the ENTIRE carrier is separated from the
3051/// other operand: every point of the face has the same Outside classification.
3052/// Keep the authored loops exactly; no interior-point search or arrangement
3053/// is needed to decide material against an operand outside this carrier box.
3054/// TRIM-SIDE PROBE for a face no section touches whose arrangement came back
3055/// EMPTY (hosted report 2026-11-02 "boolean fails", the shelf pin): the
3056/// bracket union's cylinder carried its cone on a 0.01-wide cap ring (the
3057/// cone's base rim 0.01 inside the cylinder's cap), no section on it. Its
3058/// domain centre is its hole, so it went to the arrangement for a test
3059/// point, which sampled a circle at 32 chords: the inner rim's chords sagged
3060/// 0.0115 into the hole, the only region's test point sat there, "outside
3061/// trimmed face", and the face was dropped without a word (open edges at
3062/// assembly, or a body that validated at the wrong volume). A face without
3063/// a cut that the arrangement does not split is one fragment, itself; all
3064/// it needs is a point of its own material, and that lies beside its trim: a
3065/// station on each loop's pcurve, stepped off along the pcurve's normal on
3066/// both sides over a ladder of distances, the first one the trim owns. The
3067/// arrangement's own answers stand where it gives any (a pinched loop it
3068/// splits in two). Escape hatch `BREP_FRAGMENT_TRIM_PROBE=0|off` leaves the
3069/// empty answer as it was.
3070fn trim_probe_enabled() -> bool {
3071    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3072    *ON.get_or_init(|| !matches!(std::env::var("BREP_FRAGMENT_TRIM_PROBE").as_deref(), Ok("0") | Ok("off")))
3073}
3074
3075/// The face itself as its one fragment, with the test point `uv`.
3076fn untouched_fragment(
3077    face: &FaceRecord,
3078    operand: u8,
3079    uv: Vec2,
3080    extra_test_points: Vec<Vec3>,
3081) -> Result<FaceFragmentRecord, KernelRefusal> {
3082    Ok(FaceFragmentRecord {
3083        operand,
3084        source_face_id: face.id,
3085        surface: face.surface.clone(),
3086        same_sense: face.same_sense,
3087        loops: face
3088            .loops
3089            .iter()
3090            .map(|loop_record| FragmentLoop {
3091                coedges: loop_record
3092                    .coedges
3093                    .iter()
3094                    .map(|coedge| FragmentCoedge {
3095                        source: FragmentEdgeSource::Boundary {
3096                            operand,
3097                            edge_id: coedge.edge_id,
3098                        },
3099                        forward: coedge.forward,
3100                        pcurve: coedge.pcurve.clone(),
3101                    })
3102                    .collect(),
3103            })
3104            .collect(),
3105        test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3106        test_uv: uv,
3107        extra_test_points,
3108        order: None,
3109    })
3110}
3111
3112/// A point of `face`'s material beside its trim, with up to two more as
3113/// extra test points, or `None` when no station of the ladder is owned.
3114/// Keep a region's test points clear of the section pieces that end inside it
3115/// (`BREP_FRAGMENT_STRAY_PIECE_CLEARANCE`, default on; `=0` reads the region's
3116/// boundary alone).
3117fn stray_piece_clearance_enabled() -> bool {
3118    switch!("BREP_FRAGMENT_STRAY_PIECE_CLEARANCE", true)
3119}
3120
3121fn trim_interior_probe(
3122    face: &FaceRecord,
3123    u: [f64; 2],
3124    v: [f64; 2],
3125) -> Result<Option<(Vec2, Vec<Vec3>)>, KernelRefusal> {
3126    let diagonal = ((u[1] - u[0]).powi(2) + (v[1] - v[0]).powi(2)).sqrt();
3127    if !(diagonal > 0.0) {
3128        return Ok(None);
3129    }
3130    let mut found: Vec<Vec2> = Vec::new();
3131    'loops: for loop_record in &face.loops {
3132        for coedge in &loop_record.coedges {
3133            let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3134            if !(b > a) {
3135                continue;
3136            }
3137            for fraction in [0.5, 0.25, 0.75] {
3138                let t = a + (b - a) * fraction;
3139                let derivatives = coedge.pcurve.derivatives(t, 1).or_refuse(KernelStage::Fragment, "derivatives")?;
3140                let (at, tangent) = (derivatives[0], derivatives[1]);
3141                let speed = (tangent.x * tangent.x + tangent.y * tangent.y).sqrt();
3142                if !(speed > 0.0) || !speed.is_finite() {
3143                    continue;
3144                }
3145                let normal = Vec2 { x: -tangent.y / speed, y: tangent.x / speed };
3146                for scale in [1e-2, 1e-3, 1e-4, 1e-5, 1e-6] {
3147                    let step = diagonal * scale;
3148                    for sign in [1.0, -1.0] {
3149                        let candidate = Vec2 { x: at.x + normal.x * step * sign, y: at.y + normal.y * step * sign };
3150                        if candidate.x < u[0] || candidate.x > u[1] || candidate.y < v[0] || candidate.y > v[1] {
3151                            continue;
3152                        }
3153                        if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3154                            found.push(candidate);
3155                            if found.len() >= 3 {
3156                                break 'loops;
3157                            }
3158                            continue 'loops;
3159                        }
3160                    }
3161                }
3162            }
3163        }
3164    }
3165    let Some(uv) = found.first().copied() else {
3166        return Ok(None);
3167    };
3168    let mut extra_test_points = Vec::new();
3169    for candidate in found.iter().skip(1) {
3170        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3171    }
3172    Ok(Some((uv, extra_test_points)))
3173}
3174
3175fn separated_fragment(face: &FaceRecord, operand: u8) -> Option<FaceFragmentRecord> {
3176    let coedge = face.loops.first()?.coedges.first()?;
3177    let [a, b] = coedge.pcurve.domain().ok()?;
3178    let point = coedge.pcurve.evaluate(a + (b - a) * 0.5).ok()?;
3179    let uv = Vec2 { x: point.x, y: point.y };
3180    let test_point = face.surface.evaluate(uv.x, uv.y).ok()?;
3181    Some(FaceFragmentRecord {
3182        operand, source_face_id: face.id, surface: face.surface.clone(),
3183        same_sense: face.same_sense,
3184        loops: face.loops.iter().map(|lp| FragmentLoop {
3185            coedges: lp.coedges.iter().map(|coedge| FragmentCoedge {
3186                source: FragmentEdgeSource::Boundary { operand, edge_id: coedge.edge_id },
3187                forward: coedge.forward, pcurve: coedge.pcurve.clone(),
3188            }).collect(),
3189        }).collect(),
3190        test_point, test_uv: uv, extra_test_points: Vec::new(), order: None,
3191    })
3192}
3193
3194pub fn fragment_solid_against(
3195    solid: &BrepSolid,
3196    operand: u8,
3197    imprint: &ImprintResultRecord,
3198    other: Option<(crate::Aabb, f64)>,
3199) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3200    let mut profile = FragmentProfile::new();
3201    if profile.enabled {
3202        crate::classification::containment_profile_begin();
3203    }
3204    let result = fragment_solid_profiled(solid, operand, imprint, other, &mut profile);
3205    profile.report(operand);
3206    if profile.enabled {
3207        crate::classification::containment_profile_report("fragment");
3208    }
3209    result
3210}
3211
3212pub fn fragment_solid_profiled(
3213    solid: &BrepSolid,
3214    operand: u8,
3215    imprint: &ImprintResultRecord,
3216    other: Option<(crate::Aabb, f64)>,
3217    profile: &mut FragmentProfile,
3218) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3219    let index = FragmentIndex::build(imprint);
3220    let mut fragments = Vec::new();
3221    for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
3222        let far = other.is_some_and(|(bounds, band)| face_separated(face, bounds, band));
3223        if !far { profile.box_candidates += 1; }
3224        let has_pieces = index.by_face.get(&(operand, face.id)).is_some_and(|ids| !ids.is_empty());
3225        let cosurface = index.cosurface_pairs.iter().any(|(key, _)| key.operand == operand && key.face_id == face.id);
3226        if far && !has_pieces && !cosurface && std::env::var("BREP_FRAGMENT_SCOPE").as_deref() != Ok("0") {
3227            if let Some(fragment) = separated_fragment(face, operand) {
3228                profile.separated_faces += 1;
3229                profile.face_done(face.id, None);
3230                fragments.push(fragment);
3231                continue;
3232            }
3233        }
3234        let before = (profile.arranged_faces, profile.region_faces);
3235        fragments.extend(fragment_face_indexed(solid, operand, face, &index, profile)?);
3236        if far {
3237            profile.far_arranged += profile.arranged_faces - before.0;
3238            profile.far_regions += profile.region_faces - before.1;
3239        }
3240    }
3241    Ok(fragments)
3242}
3243
3244
3245/// `BREP_RIM_BRIDGE` (default on, `=0` off): the fragment side of the imprint's rim
3246/// bridge (see RIM BRIDGE in `fragment_face_arranged`).
3247fn rim_bridge_enabled() -> bool {
3248    crate::switch!("BREP_RIM_BRIDGE", true)
3249}