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