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