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};
7fn boundary_vertex_hints_enabled() -> bool {
11 switch!("BREP_BOUNDARY_VERTEX_HINTS", true)
12}
13
14pub fn small_ring_enabled() -> bool {
23 switch!("BREP_FRAGMENT_SMALL_RING", true)
24}
25
26fn bridge_t_junction_anchor_enabled() -> bool {
32 switch!("BREP_BRIDGE_T_JUNCTION_ANCHOR", true)
33}
34
35fn bridge_boundary_t_junction_anchor_enabled() -> bool {
45 switch!("BREP_BRIDGE_BOUNDARY_T_JUNCTION_ANCHOR", true)
46}
47
48fn 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 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 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
103pub 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
118fn 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 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 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 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
228fn 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
248fn dup_cut_space_nomination_enabled() -> bool {
257 crate::switch!("BREP_DUP_CUT_SPACE_NOMINATION", true)
258}
259
260fn cosurface_corner_copy_on() -> bool {
261 crate::switch!("BREP_COSURFACE_CORNER_COPY", true)
262}
263
264fn boundary_is_cosurface_corner(
265 solid: &BrepSolid,
266 face: FaceKey,
267 boundary_edge: u64,
268 piece: &ImprintPieceRecord,
269 index: &FragmentIndex,
270) -> bool {
271 let Some(other) = piece.support_faces.iter().find(|other| other.operand != face.operand) else {
272 return false;
273 };
274 if !index.cosurface_pairs.contains(&(face, *other)) {
275 return false;
276 }
277 solid.shells.iter().flat_map(|shell| &shell.faces).any(|neighbour| {
278 neighbour.id != face.face_id
279 && neighbour.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| coedge.edge_id == boundary_edge)
280 && index.cosurface_pairs.iter().any(|(first, second)| {
281 first.operand == face.operand
285 && first.face_id == neighbour.id
286 && second.operand != face.operand
287 && index.by_face.get(&(second.operand, second.face_id)).is_some_and(|ids| ids.contains(&piece.id))
288 })
289 })
290}
291
292fn thin_boundary_resolution(
303 solid: &BrepSolid,
304 face: &FaceRecord,
305 face_key: FaceKey,
306 piece_ids: &[u64],
307 index: &FragmentIndex,
308 search: f64,
309) -> (Option<(f64, f64)>, bool, Option<(f64, f64)>, bool) {
310 let mut resolution: Option<(f64, f64)> = None;
311 let mut wedged: Option<(f64, f64)> = None;
315 let mut lens_found = false;
316 let mut take_wedge = |found: Option<(f64, f64, bool)>| {
317 if let Some((arrangement, sampling, lens)) = found {
318 lens_found |= lens;
319 wedged = Some(match wedged {
320 Some((a, s)) => (a.min(arrangement), s.min(sampling)),
321 None => (arrangement, sampling),
322 });
323 }
324 };
325 let mut feature_found = false;
328 let mut take = |strip: Option<(f64, f64)>| {
329 if let Some((arrangement, sampling)) = strip {
330 resolution = Some(match resolution {
331 Some((a, s)) => (a.min(arrangement), s.min(sampling)),
332 None => (arrangement, sampling),
333 });
334 }
335 };
336 let cuts: Vec<&NurbsCurve> = piece_ids
337 .iter()
338 .filter_map(|piece_id| index.pieces_by_id.get(piece_id).and_then(|piece| pcurve_for(piece, face_key).ok()))
339 .collect();
340 for piece_id in piece_ids {
341 let Some(piece) = index.pieces_by_id.get(piece_id) else { continue };
342 let Ok(cut) = pcurve_for(piece, face_key) else { continue };
343 for boundary in face.loops.iter().flat_map(|lp| &lp.coedges) {
344 if boundary_has_cosurface_partner(solid, face_key, boundary.edge_id, piece, index) {
345 continue;
346 }
347 let strip = strip_between(face, &cut, &boundary.pcurve, search);
348 take(match strip {
349 None if crate::feature_scale::fragment_enabled() => {
350 let touch = near_touch(face, &cut, &boundary.pcurve, search);
351 if touch.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
352 eprintln!("feature_scale: face {} near touch cut p{piece_id} / boundary e{} -> {touch:?}", face.id, boundary.edge_id);
353 }
354 feature_found |= touch.is_some();
355 touch
356 }
357 strip => strip,
358 });
359 if wedge_enabled() {
360 let found = wedge(face, &cut, &boundary.pcurve, search);
361 if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
362 eprintln!("feature_scale: face {} wedge cut p{piece_id} / boundary e{} -> {found:?}", face.id, boundary.edge_id);
363 }
364 take_wedge(found);
365 }
366 if end_gap_enabled() {
367 let gap = end_gap(face, &cut, &boundary.pcurve, search);
368 if gap.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
369 eprintln!("feature_scale: face {} end gap cut p{piece_id} / boundary e{} -> {gap:?}", face.id, boundary.edge_id);
370 }
371 feature_found |= gap.is_some();
372 take(gap);
373 }
374 }
375 }
376 if crate::feature_scale::fragment_enabled() {
377 for (i, cut) in cuts.iter().enumerate() {
378 for other in &cuts[i + 1..] {
379 let strip = strip_between(face, cut, other, search);
380 let found = strip.or_else(|| near_touch(face, cut, other, search));
381 if wedge_enabled() {
382 let found = match (wedge(face, cut, other, search), wedge(face, other, cut, search)) {
383 (Some(x), Some(y)) => Some((x.0.min(y.0), x.1.min(y.1), x.2 || y.2)),
384 (x, y) => x.or(y),
385 };
386 if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
387 eprintln!("feature_scale: face {} wedge cut pair {i} -> {found:?}", face.id);
388 }
389 take_wedge(found);
390 }
391 if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
392 eprintln!("feature_scale: face {} cut pair {i} {} -> {} {found:?}", face.id, if strip.is_some() { "strip" } else { "near touch" }, i);
393 }
394 feature_found |= found.is_some();
395 take(found);
396 }
397 }
398 }
399 if lens_enabled() {
404 let coedges: Vec<&NurbsCurve> = face.loops.iter().flat_map(|lp| &lp.coedges).map(|coedge| &coedge.pcurve).collect();
405 let ends = |curve: &NurbsCurve| -> Option<[Vec3; 2]> {
406 let [lo, hi] = curve.domain().ok()?;
407 Some([curve.evaluate(lo).ok()?, curve.evaluate(hi).ok()?])
408 };
409 let ends: Vec<Option<[Vec3; 2]>> = coedges.iter().map(|curve| ends(curve)).collect();
410 for i in 0..coedges.len() {
411 for j in (i + 1)..coedges.len() {
412 let (Some(a), Some(b)) = (ends[i], ends[j]) else { continue };
413 let near = |p: Vec3, q: Vec3| p.sub(q).length() <= search;
414 let shared = (near(a[0], b[0]) && near(a[1], b[1])) || (near(a[0], b[1]) && near(a[1], b[0]));
415 if !shared || near(a[0], a[1]) {
416 continue;
417 }
418 let found = match (wedge(face, coedges[i], coedges[j], search), wedge(face, coedges[j], coedges[i], search)) {
419 (Some(x), Some(y)) => Some((x.0.min(y.0), x.1.min(y.1), x.2 || y.2)),
420 (x, y) => x.or(y),
421 };
422 let found = found.filter(|found| found.2);
423 if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
424 eprintln!("feature_scale: face {} boundary lens {i}/{j} -> {found:?}", face.id);
425 }
426 take_wedge(found);
427 }
428 }
429 }
430 (resolution, feature_found, wedged, lens_found)
431}
432
433fn wedge_enabled() -> bool {
436 crate::switch!("BREP_FEATURE_SCALE_WEDGE", true)
437}
438
439fn wedge(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64, bool)> {
456 let [lo, hi] = cut.domain().ok()?;
457 let [other_lo, other_hi] = other.domain().ok()?;
458 let mut chart_length = 0.0;
461 let mut previous = cut.evaluate(lo).ok()?;
462 for step in 1..=16 {
463 let point = cut.evaluate(lo + (hi - lo) * step as f64 / 16.0).ok()?;
464 chart_length += point.sub(previous).length();
465 previous = point;
466 }
467 if !(chart_length > 0.0) || cut.evaluate(lo).ok()?.sub(cut.evaluate(hi).ok()?).length() <= search {
468 return None;
469 }
470 let mut found: Option<(f64, f64, bool)> = None;
471 for (end, inward) in [(lo, 1.0), (hi, -1.0)] {
472 let Ok(cut_sample) = cut.derivatives(end, 1) else { continue };
473 for (other_end, other_inward) in [(other_lo, 1.0), (other_hi, -1.0)] {
474 let Ok(other_sample) = other.derivatives(other_end, 1) else { continue };
475 if cut_sample[0].sub(other_sample[0]).length() > search {
476 continue;
477 }
478 let a = cut_sample[1].scale(inward);
479 let b = other_sample[1].scale(other_inward);
480 if !(a.length() * b.length() > 1e-30) {
481 continue;
482 }
483 let angle = a.cross(b).length().atan2(a.dot(b));
488 if !(angle.is_finite()) || angle > 0.2 {
489 continue;
490 }
491 let resolution = angle * chart_length * 1e-3;
492 if resolution >= search {
493 continue;
494 }
495 let parting = |fraction: f64| -> Option<(f64, f64)> {
501 let parameter = if inward > 0.0 { lo + fraction * (hi - lo) } else { hi - fraction * (hi - lo) };
502 let probe = cut.evaluate(parameter).ok()?;
503 let foot = project_point_to_curve(other, probe).ok()?;
504 let here = face.surface.evaluate(probe.x, probe.y).ok()?;
505 let there = face.surface.evaluate(foot.point.x, foot.point.y).ok()?;
506 Some((here.sub(there).length(), probe.sub(foot.point).length()))
507 };
508 let Some((space, _)) = parting(0.1) else { continue };
509 let Ok(probe) = cut.evaluate(if inward > 0.0 { lo + 0.1 * (hi - lo) } else { hi - 0.1 * (hi - lo) }) else { continue };
510 let Ok(derivatives) = face.surface.derivatives(probe.x, probe.y, 1) else { continue };
511 let stiff = derivatives[1][0].length().max(derivatives[0][1].length());
512 let identity = crate::tolerance::parametric_tolerance(1e-7, stiff);
513 let far_end = if inward > 0.0 { hi } else { lo };
516 let far_point = cut.evaluate(far_end).ok();
517 let far_partner = far_point.and_then(|far| {
518 [other_lo, other_hi]
519 .iter()
520 .filter_map(|&end| other.evaluate(end).ok())
521 .filter(|point| point.sub(far).length() <= search)
522 .min_by(|p, q| p.sub(far).length().total_cmp(&q.sub(far).length()))
523 .map(|point| (far, point))
524 });
525 let two_ended = far_partner.is_some();
526 let end_gaps = far_partner.and_then(|(far, partner)| {
532 let gap = |p: Vec3, q: Vec3| -> Option<f64> {
533 Some(face.surface.evaluate(p.x, p.y).ok()?.sub(face.surface.evaluate(q.x, q.y).ok()?).length())
534 };
535 Some(gap(cut_sample[0], other_sample[0])?.max(gap(far, partner)?))
536 });
537 let lens = if two_ended && lens_enabled() && (space <= 8e-7 || resolution < identity) {
541 parting(0.5).filter(|(space, _)| *space > 8e-7 && end_gaps.is_some_and(|ends| *space > 2.0 * ends))
542 } else {
543 None
544 };
545 if space <= 8e-7 && lens.is_none() {
546 continue;
547 }
548 let (resolution, sampling) = match lens {
551 Some((_, chart)) => (resolution.max(identity), Some(chart / 8.0)),
552 None if resolution < identity => continue,
553 None => (resolution, None),
554 };
555 let resolution = resolution.max(search / if lens.is_some() { 1024.0 } else { 64.0 });
561 if lens.is_some_and(|(_, chart)| chart < 8.0 * resolution) {
564 continue;
565 }
566 let wanted = (resolution, search.min(resolution * 16.0).min(sampling.unwrap_or(f64::INFINITY)), lens.is_some());
567 found = Some(match found {
568 Some((x, y, l)) => (x.min(wanted.0), y.min(wanted.1), l || wanted.2),
569 None => wanted,
570 });
571 }
572 }
573 found
574}
575
576fn lens_enabled() -> bool {
583 crate::switch!("BREP_FEATURE_SCALE_LENS", true)
584}
585
586fn exact_end_stays_on() -> bool {
589 crate::switch!("BREP_FRAGMENT_EXACT_END_STAYS", true)
590}
591
592pub fn end_gap_enabled() -> bool {
608 crate::switch!("BREP_FEATURE_SCALE_END_GAP", true)
609}
610
611fn end_gap(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
612 let straight = |curve: &NurbsCurve| curve.degree == 1 && curve.control_points.len() == 2;
616 if !face.surface.is_affine().ok()? || !straight(cut) || !straight(other) {
617 return None;
618 }
619 let [lo, hi] = cut.domain().ok()?;
620 let start = cut.evaluate(lo).ok()?;
621 let end = cut.evaluate(hi).ok()?;
622 if start.sub(end).length() <= search {
623 return None;
624 }
625 let u_domain = face.surface.domain_u().ok()?;
626 let v_domain = face.surface.domain_v().ok()?;
627 let diagonal = ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
628 let reach = (search * 100.0).max(diagonal * 1.5e-3);
629 let mut found: Option<(f64, f64)> = None;
630 for point in [start, end] {
631 let Ok(foot) = project_point_to_curve(other, point) else { continue };
632 if foot.distance > reach {
633 continue;
634 }
635 let (Ok(here), Ok(there)) = (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) else {
636 continue;
637 };
638 if here.sub(there).length() <= crate::tolerance::WELD_FLOOR {
639 continue;
640 }
641 let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
642 if foot.distance <= identity * 8.0 {
643 continue;
644 }
645 let resolution = (search.min((foot.distance / 128.0).max(identity)), search.min(foot.distance / 8.0));
646 found = Some(match found {
647 Some((a, s)) => (a.min(resolution.0), s.min(resolution.1)),
648 None => resolution,
649 });
650 }
651 found
652}
653
654fn near_touch(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
665 let hull = |curve: &NurbsCurve| crate::spatial::Aabb::from_curve_controls(curve).ok();
668 if !hull(cut)?.intersects(hull(other)?, search * 8.0) {
669 return None;
670 }
671 if !near_touch_held_enabled() {
672 return near_touch_search(face, cut, other, search, None);
673 }
674 let held = crate::projection::HeldCurve::new(other.clone());
675 let quick = NearTouchQuick { held: &held, spans: span_hulls(other) };
676 let found = near_touch_search(face, cut, other, search, Some(&quick));
677 if near_touch_held_check() {
678 let fresh = near_touch_search(face, cut, other, search, None);
679 let bits = |found: Option<(f64, f64)>| found.map(|(a, b)| (a.to_bits(), b.to_bits()));
680 assert_eq!(bits(found), bits(fresh), "near touch held check: held {found:?} vs fresh {fresh:?}");
681 }
682 found
683}
684
685fn near_touch_held_enabled() -> bool {
695 crate::switch!("BREP_NEAR_TOUCH_HELD", true)
696}
697
698fn near_touch_held_check() -> bool {
699 crate::switch!("BREP_NEAR_TOUCH_HELD_CHECK", false)
700}
701
702struct NearTouchQuick<'a> {
705 held: &'a crate::projection::HeldCurve,
706 spans: Option<Vec<crate::spatial::Aabb>>,
707}
708
709fn span_hulls(curve: &NurbsCurve) -> Option<Vec<crate::spatial::Aabb>> {
714 let degree = curve.degree;
715 let controls = &curve.control_points;
716 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())) {
717 return None;
718 }
719 let mut boxes = Vec::new();
720 for index in degree..controls.len() {
721 if index + 1 >= curve.knots.len() || curve.knots[index] >= curve.knots[index + 1] {
722 continue;
723 }
724 let points = controls[index - degree..=index].iter().map(|c| c.point()).collect::<Result<Vec<_>, _>>().ok()?;
725 boxes.push(crate::spatial::Aabb::from_points(points));
726 }
727 (!boxes.is_empty()).then_some(boxes)
728}
729
730fn distance_floor(point: Vec3, boxes: &[crate::spatial::Aabb]) -> f64 {
735 let single = crate::spatial::Aabb { minimum: point, maximum: point };
736 boxes
737 .iter()
738 .map(|bounds| {
739 let gap = single.separation(*bounds);
740 let cushion = 64.0 * f64::EPSILON * (point.length() + bounds.minimum.length() + bounds.maximum.length());
741 gap * (1.0 - 1e-9) - cushion
742 })
743 .fold(f64::INFINITY, f64::min)
744 .max(0.0)
745}
746
747fn near_touch_search(
748 face: &FaceRecord,
749 cut: &NurbsCurve,
750 other: &NurbsCurve,
751 search: f64,
752 quick: Option<&NearTouchQuick>,
753) -> Option<(f64, f64)> {
754 let project = |point: Vec3| match quick {
755 Some(quick) => quick.held.project(point),
756 None => project_point_to_curve(other, point),
757 };
758 let [lo, hi] = cut.domain().ok()?;
759 let [other_lo, other_hi] = other.domain().ok()?;
760 let ends_on_other = [lo, hi].into_iter().any(|t| {
773 let Ok(point) = cut.evaluate(t) else { return false };
774 let Ok(foot) = project(point) else { return false };
775 let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
776 if foot.distance > (search * 1e-3).min(identity) {
777 return false;
778 }
779 match (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) {
780 (Ok(here), Ok(there)) => here.sub(there).length() <= 1e-9,
781 _ => false,
782 }
783 });
784 if ends_on_other {
785 return None;
786 }
787 let gap = |parameter: f64| -> Option<(f64, Vec3, Vec3, f64)> {
788 let point = cut.evaluate(parameter).ok()?;
789 let projected = project(point).ok()?;
790 Some((projected.distance, point, projected.point, projected.u))
791 };
792 let closed = |curve: &NurbsCurve, a: f64, b: f64| -> bool {
795 match (curve.evaluate(a), curve.evaluate(b)) {
796 (Ok(start), Ok(end)) => start.sub(end).length() <= search,
797 _ => false,
798 }
799 };
800 let (cut_closed, other_closed) = (closed(cut, lo, hi), closed(other, other_lo, other_hi));
801 const SAMPLES: usize = 256;
802 let step = (hi - lo) / SAMPLES as f64;
803 let mut best: Option<(f64, f64)> = None;
804 match quick.and_then(|quick| quick.spans.as_deref()) {
805 None => {
806 for i in 0..=SAMPLES {
807 let parameter = lo + step * i as f64;
808 if let Some((distance, _, _, _)) = gap(parameter) {
809 if best.is_none_or(|(_, d)| distance < d) {
810 best = Some((parameter, distance));
811 }
812 }
813 }
814 }
815 Some(spans) => {
816 let mut order = Vec::with_capacity(SAMPLES + 1);
821 for i in 0..=SAMPLES {
822 let parameter = lo + step * i as f64;
823 let floor = cut.evaluate(parameter).map_or(0.0, |point| distance_floor(point, spans));
825 order.push((floor, i));
826 }
827 order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
828 let mut least: Option<(usize, f64)> = None;
829 for (floor, i) in order {
830 if least.is_some_and(|(_, d)| floor > d) {
831 break;
832 }
833 if let Some((distance, _, _, _)) = gap(lo + step * i as f64) {
834 if distance.is_nan() {
835 return near_touch_search(face, cut, other, search, None);
836 }
837 if least.is_none_or(|(j, d)| distance < d || (distance == d && i < j)) {
838 least = Some((i, distance));
839 }
840 }
841 }
842 best = least.map(|(i, distance)| (lo + step * i as f64, distance));
843 }
844 }
845 let (centre, _) = best?;
846 let (mut a, mut b) = ((centre - step).max(lo), (centre + step).min(hi));
847 let ratio = 0.5 * (5f64.sqrt() - 1.0);
848 for _ in 0..80 {
849 let c = b - ratio * (b - a);
850 let d = a + ratio * (b - a);
851 if gap(c)?.0 < gap(d)?.0 { b = d } else { a = c }
852 }
853 let parameter = 0.5 * (a + b);
854 let (low_gap, point, foot, foot_parameter) = gap(parameter)?;
855 if low_gap > search * 8.0 {
856 return None;
857 }
858 let at_end = |t: f64, a: f64, b: f64| (t - a).abs() <= 0.01 * (b - a) || (b - t).abs() <= 0.01 * (b - a);
863 if (!cut_closed && at_end(parameter, lo, hi)) || (!other_closed && at_end(foot_parameter, other_lo, other_hi)) {
864 return None;
865 }
866 let actual = face.surface.evaluate(point.x, point.y).ok()?;
867 let rim = face.surface.evaluate(foot.x, foot.y).ok()?;
868 if actual.sub(rim).length() <= 8e-7 {
869 return None;
870 }
871 let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
872 if low_gap <= identity * 8.0 {
873 return None;
874 }
875 Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
876}
877
878fn strip_between(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
885 let [lo, hi] = cut.domain().ok()?;
886 let middle = cut.evaluate((lo + hi) * 0.5).ok()?;
887 let nearest = project_point_to_curve(other, middle).ok()?;
888 if nearest.distance > search * 8.0 { return None; }
889 let mut low_gap = f64::INFINITY;
890 let mut high_gap = 0.0f64;
891 let mut identity = 0.0f64;
892 for fraction in [0.125, 0.25, 0.5, 0.75, 0.875] {
893 let parameter = lo + (hi - lo) * fraction;
894 let cut_sample = cut.derivatives(parameter, 1).ok()?;
895 let point = cut_sample[0];
896 let projected = project_point_to_curve(other, point).ok()?;
897 if projected.distance > search * 8.0 { return None; }
898 let other_sample = other.derivatives(projected.u, 1).ok()?;
899 let a = cut_sample[1];
900 let b = other_sample[1];
901 let lengths = a.length() * b.length();
902 if lengths <= 1e-30 || a.dot(b).abs() < 0.995 * lengths { return None; }
903 let actual = face.surface.evaluate(point.x, point.y).ok()?;
904 let rim = face.surface.evaluate(projected.point.x, projected.point.y).ok()?;
905 if actual.sub(rim).length() <= 8e-7 { return None; }
906 let floor = crate::classification::surface_uv_band(
907 &face.surface, point.x, point.y, 1e-7,
908 );
909 if projected.distance <= floor * 8.0 { return None; }
910 low_gap = low_gap.min(projected.distance);
911 high_gap = high_gap.max(projected.distance);
912 identity = identity.max(floor);
913 }
914 if high_gap > low_gap * 4.0 { return None; }
916 Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
917}
918
919fn fragment_face_indexed(
920 solid: &BrepSolid,
921 operand: u8,
922 face: &FaceRecord,
923 index: &FragmentIndex,
924 profile: &mut FragmentProfile,
925) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
926 let face_started = profile.enabled.then(Instant::now);
927 let mut lap_start = face_started;
928 let result = fragment_face_stages(solid, operand, face, index, profile, &mut lap_start);
929 profile.face_done(face.id, face_started);
930 result
931}
932
933fn fragment_face_stages(
934 solid: &BrepSolid,
935 operand: u8,
936 face: &FaceRecord,
937 index: &FragmentIndex,
938 profile: &mut FragmentProfile,
939 lap_start: &mut Option<Instant>,
940) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
941 let face_key = FaceKey {
942 operand,
943 face_id: face.id,
944 };
945 let piece_ids = index
946 .by_face
947 .get(&(operand, face.id))
948 .copied()
949 .unwrap_or(&[]);
950 if piece_ids.is_empty() {
951 profile.uncut_probe_faces += 1;
952 let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
953 let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
954 let uv = Vec2 {
955 x: (u[0] + u[1]) / 2.0,
956 y: (v[0] + v[1]) / 2.0,
957 };
958 let probe_started = profile.enabled.then(Instant::now);
959 let centre_inside = parameter_point_in_face(face, uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
960 if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
961 if !centre_inside {
962 } else {
965 let mut extra_test_points = Vec::new();
966 for (fu, fv) in [(0.35, 0.35), (0.65, 0.65)] {
967 let candidate = Vec2 {
968 x: u[0] + (u[1] - u[0]) * fu,
969 y: v[0] + (v[1] - v[0]) * fv,
970 };
971 let probe_started = profile.enabled.then(Instant::now);
972 let inside = parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
973 if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
974 if inside {
975 extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
976 }
977 }
978 let untouched = vec![untouched_fragment(face, operand, uv, extra_test_points)?];
979 profile.untouched += profile.lap(lap_start);
980 return Ok(untouched);
981 }
982 }
983 if !piece_ids.is_empty() {
984 profile.cut_faces += 1;
985 }
986 let mode = loop_split_mode();
990 let mut split_result: Option<Result<Vec<FaceFragmentRecord>, super::loop_split::Decline>> = None;
991 if mode != LoopSplitMode::Off && !piece_ids.is_empty() {
992 let started = profile.enabled.then(Instant::now);
993 let outcome = loop_split_face(solid, operand, face, face_key, piece_ids, index)?;
994 if let Some(started) = started {
995 profile.loop_split += started.elapsed();
996 }
997 match &outcome {
998 Ok(_) => profile.loop_split_faces += 1,
999 Err(_) => profile.loop_split_declined += 1,
1000 }
1001 if mode == LoopSplitMode::On {
1002 if let Ok(fragments) = outcome {
1003 if std::env::var("BREP_DEBUG_FRAG_COUNT").is_ok() {
1004 eprintln!("frag count: operand {operand} face {} pieces {:?} loop-split -> {} fragments", face.id, piece_ids, fragments.len());
1005 }
1006 *lap_start = profile.enabled.then(Instant::now);
1007 return Ok(fragments);
1008 }
1009 }
1010 split_result = Some(outcome);
1011 *lap_start = profile.enabled.then(Instant::now);
1012 }
1013 let arranged = fragment_face_arranged(solid, operand, face, face_key, piece_ids, index, profile, lap_start);
1014 if piece_ids.is_empty() && trim_probe_enabled() && matches!(&arranged, Ok(fragments) if fragments.is_empty()) {
1019 let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1020 let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1021 if let Some((uv, extra_test_points)) = trim_interior_probe(face, u, v)? {
1022 return Ok(vec![untouched_fragment(face, operand, uv, extra_test_points)?]);
1023 }
1024 }
1025 if let Some(split) = &split_result {
1026 let verdict = match (split, &arranged) {
1027 (Err(decline), _) => format!("declined {decline}"),
1028 (Ok(_), Err(refusal)) => format!("MISMATCH split built {} fragments, arrangement refused: {refusal}", split.as_ref().map_or(0, Vec::len)),
1029 (Ok(split), Ok(arranged)) => match fragments_agree(split, arranged) {
1030 Ok(agreement) => agreement.to_string(),
1031 Err(why) => format!("MISMATCH {why}"),
1032 },
1033 };
1034 loop_split_census(|| format!("operand {operand} face {} pieces {} loops {} {verdict}", face.id, piece_ids.len(), face.loops.len()));
1035 }
1036 if std::env::var("BREP_DEBUG_FRAG_COUNT").is_ok() && !piece_ids.is_empty() {
1037 match (&split_result, &arranged) {
1038 (Some(Err(decline)), Ok(fragments)) => eprintln!("frag count: operand {operand} face {} pieces {:?} loop split declined ({decline}); arrangement -> {} fragments", face.id, piece_ids, fragments.len()),
1039 (_, Ok(fragments)) => eprintln!("frag count: operand {operand} face {} pieces {:?} arrangement -> {} fragments", face.id, piece_ids, fragments.len()),
1040 (_, Err(refusal)) => eprintln!("frag count: operand {operand} face {} arrangement refused: {refusal}", face.id),
1041 }
1042 }
1043 arranged
1044}
1045
1046
1047#[allow(clippy::too_many_arguments)]
1048fn fragment_face_arranged(
1049 solid: &BrepSolid,
1050 operand: u8,
1051 face: &FaceRecord,
1052 face_key: FaceKey,
1053 piece_ids: &[u64],
1054 index: &FragmentIndex,
1055 profile: &mut FragmentProfile,
1056 lap_start: &mut Option<Instant>,
1057) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
1058
1059 let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1060 let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1061 let diagonal =
1062 ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
1063 let original_resolution = 1e-7f64.max(diagonal * 1e-6);
1064 let (strip_resolution, feature_strip, wedge_resolution, lens_face) = thin_boundary_resolution(solid, face, face_key, piece_ids, index, original_resolution);
1065 let (band_tolerance, band_sampling) = strip_resolution
1066 .unwrap_or((original_resolution, original_resolution));
1067 let (arrangement_tolerance, sampling_bound) = match wedge_resolution {
1072 Some((arrangement, sampling)) => (band_tolerance.min(arrangement), band_sampling.min(sampling)),
1073 None => (band_tolerance, band_sampling),
1074 };
1075 let strip_snap = feature_strip
1093 || (strip_resolution.is_some()
1094 && !index.operand_sliver_regions.is_empty()
1095 && crate::spatial::Aabb::from_surface_controls(&face.surface)
1096 .is_ok_and(|face_box| index.operand_sliver_regions.iter().any(|region| face_box.intersects(*region, original_resolution))));
1097 let (image_band, image_band_3d) = if strip_snap {
1098 (sampling_bound, 1e-7)
1099 } else {
1100 (band_tolerance * 100.0, 1e-5)
1101 };
1102 let snap_threshold = 0.1 * diagonal;
1103 let junction_radius = (band_tolerance * 50.0).max(diagonal * 1.5e-3);
1104 let band_rebase: [Option<(f64, f64)>; 2] = {
1119 let mut rebase = [None, None];
1120 let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1121 if (closed.0 || closed.1) && std::env::var("BREP_BAND_REBASE").as_deref() != Ok("0") {
1122 let mut coverage: [Vec<[f64; 2]>; 2] = [Vec::new(), Vec::new()];
1129 let mut edge_rim = [false, false];
1130 let mut hull = [
1131 [f64::INFINITY, f64::NEG_INFINITY],
1132 [f64::INFINITY, f64::NEG_INFINITY],
1133 ];
1134 for coedge in face
1135 .loops
1136 .iter()
1137 .flat_map(|loop_record| &loop_record.coedges)
1138 {
1139 let mut extent = [
1140 [f64::INFINITY, f64::NEG_INFINITY],
1141 [f64::INFINITY, f64::NEG_INFINITY],
1142 ];
1143 for control in &coedge.pcurve.control_points {
1144 if control.w.abs() <= 1e-300 {
1145 continue;
1146 }
1147 let point = [control.x / control.w, control.y / control.w];
1148 for axis in 0..2 {
1149 extent[axis][0] = extent[axis][0].min(point[axis]);
1150 extent[axis][1] = extent[axis][1].max(point[axis]);
1151 hull[axis][0] = hull[axis][0].min(point[axis]);
1152 hull[axis][1] = hull[axis][1].max(point[axis]);
1153 }
1154 }
1155 for axis in 0..2 {
1156 if !extent[axis][0].is_finite() {
1157 continue;
1158 }
1159 let domain = if axis == 0 { u_domain } else { v_domain };
1160 let span = domain[1] - domain[0];
1161 coverage[axis].push(extent[axis]);
1162 let flat = extent[axis][1] - extent[axis][0] <= 1e-3 * span;
1163 let at_edge = (extent[axis][0] - domain[0]).abs() <= 1e-6 * span
1164 || (extent[axis][1] - domain[1]).abs() <= 1e-6 * span;
1165 if flat && at_edge {
1166 edge_rim[axis] = true;
1167 }
1168 }
1169 }
1170 for axis in 0..2 {
1171 if !(if axis == 0 { closed.0 } else { closed.1 }) || !edge_rim[axis] {
1172 continue;
1173 }
1174 let domain = if axis == 0 { u_domain } else { v_domain };
1175 let span = domain[1] - domain[0];
1176 let mut intervals: Vec<[f64; 2]> = coverage[axis]
1182 .iter()
1183 .map(|window| {
1184 [window[0].max(domain[0]), window[1].min(domain[1])]
1185 })
1186 .filter(|window| window[1] >= window[0])
1187 .collect();
1188 intervals.sort_by(|a, b| a[0].total_cmp(&b[0]));
1189 let mut gaps: Vec<[f64; 2]> = Vec::new();
1190 let mut reach = domain[0];
1191 for window in &intervals {
1192 if window[0] > reach {
1193 gaps.push([reach, window[0]]);
1194 }
1195 reach = reach.max(window[1]);
1196 }
1197 if reach < domain[1] {
1198 gaps.push([reach, domain[1]]);
1199 }
1200 let other_mid = (hull[1 - axis][0].max(if axis == 0 {
1201 v_domain[0]
1202 } else {
1203 u_domain[0]
1204 }) + hull[1 - axis][1].min(if axis == 0 {
1205 v_domain[1]
1206 } else {
1207 u_domain[1]
1208 })) / 2.0;
1209 let mut void: Option<[f64; 2]> = None;
1210 for gap in gaps {
1211 if gap[1] - gap[0] <= 1e-6 * span {
1212 continue;
1213 }
1214 let mid = (gap[0] + gap[1]) / 2.0;
1215 let sample = if axis == 0 {
1216 Vec2 {
1217 x: mid,
1218 y: other_mid,
1219 }
1220 } else {
1221 Vec2 {
1222 x: other_mid,
1223 y: mid,
1224 }
1225 };
1226 if parameter_point_in_face(face, sample, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? != PolygonClass::Inside
1227 && void
1228 .map(|best| gap[1] - gap[0] > best[1] - best[0])
1229 .unwrap_or(true)
1230 {
1231 void = Some(gap);
1232 }
1233 }
1234 if let Some([g0, g1]) = void {
1235 let touches_low = intervals
1242 .iter()
1243 .any(|window| window[0] <= domain[0] + 1e-6 * span);
1244 let touches_high = intervals
1245 .iter()
1246 .any(|window| window[1] >= domain[1] - 1e-6 * span);
1247 if touches_low && touches_high {
1248 rebase[axis] = Some(((g0 + g1) / 2.0, span));
1252 }
1253 }
1254 }
1255 }
1256 rebase
1257 };
1258 let rebase_point = |mut point: Vec2| -> Vec2 {
1259 if let Some((cutoff, period)) = band_rebase[0] {
1260 if point.x < cutoff {
1261 point.x += period;
1262 }
1263 }
1264 if let Some((cutoff, period)) = band_rebase[1] {
1265 if point.y < cutoff {
1266 point.y += period;
1267 }
1268 }
1269 point
1270 };
1271 let wrap_back = {
1276 let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1277 move |mut point: Vec2| -> Vec2 {
1278 if closed.0 {
1279 let span = u_domain[1] - u_domain[0];
1280 if point.x < u_domain[0] || point.x > u_domain[1] {
1281 point.x = u_domain[0] + (point.x - u_domain[0]).rem_euclid(span);
1282 }
1283 }
1284 if closed.1 {
1285 let span = v_domain[1] - v_domain[0];
1286 if point.y < v_domain[0] || point.y > v_domain[1] {
1287 point.y = v_domain[0] + (point.y - v_domain[0]).rem_euclid(span);
1288 }
1289 }
1290 point
1291 }
1292 };
1293 profile.setup += profile.lap(lap_start);
1294 let pieces_by_id = &index.pieces_by_id;
1295 let mut cut_hints = Vec::new();
1296 let mut active_pieces = Vec::new();
1297 let mut cut_keys = HashMap::default();
1298 for piece_id in piece_ids {
1299 let piece = pieces_by_id
1300 .get(piece_id)
1301 .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint piece"))?;
1302 let pcurve = pcurve_for(piece, face_key)?;
1303 let [start, end] = pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1304 let a = pcurve.evaluate(start).or_refuse(KernelStage::Fragment, "evaluate")?;
1305 let b = pcurve.evaluate(end).or_refuse(KernelStage::Fragment, "evaluate")?;
1306 let middle = pcurve.evaluate((start + end) / 2.0).or_refuse(KernelStage::Fragment, "evaluate")?;
1307 for point in [a, b] {
1308 cut_hints.push(Vec2 {
1309 x: point.x,
1310 y: point.y,
1311 });
1312 }
1313 let quantize = |point: Vec3| {
1314 (
1315 (point.x / arrangement_tolerance).round() as i64,
1316 (point.y / arrangement_tolerance).round() as i64,
1317 )
1318 };
1319 let mut endpoints = [quantize(a), quantize(b)];
1320 endpoints.sort();
1321 let key = (endpoints[0], quantize(middle), endpoints[1]);
1322 if cut_keys.insert(key, *piece_id).is_none() {
1323 active_pieces.push(*piece_id);
1324 }
1325 }
1326
1327 let mut segments = Vec::new();
1328 let mut chains = Vec::new();
1329 let mut vertex_images: std::collections::HashMap<String, Vec<Vec2>> =
1330 std::collections::HashMap::new();
1331 let mut endpoint_images: Vec<(Vec3, Vec2)> = Vec::new();
1332 let mut boundary_images: Vec<(Vec2, Vec3)> = Vec::new();
1335 let boundary_vertex_anchor_off =
1349 std::env::var("BREP_BOUNDARY_VERTEX_ANCHOR").as_deref() == Ok("0");
1350 let boundary_side = |point: Vec2| {
1351 let distances = [
1352 (point.x - u_domain[0]).abs(),
1353 (point.x - u_domain[1]).abs(),
1354 (point.y - v_domain[0]).abs(),
1355 (point.y - v_domain[1]).abs(),
1356 ];
1357 let index = distances
1358 .iter()
1359 .enumerate()
1360 .min_by(|a, b| a.1.total_cmp(b.1))
1361 .map(|entry| entry.0)
1362 .unwrap();
1363 (distances[index] <= arrangement_tolerance * 50.0).then_some(index)
1364 };
1365
1366 let bridge_keys: HashSet<String> = if rim_bridge_enabled() {
1374 let weld = crate::tolerance::assembler_weld(1e-7);
1375 let mut rim_points = Vec::new();
1377 for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1378 if let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) {
1379 for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
1380 rim_points.push(vertex_point(solid, vertex_id)?);
1381 }
1382 }
1383 }
1384 let on_rim = |point: &Vec3| rim_points.iter().any(|rim| rim.sub(*point).length() <= weld);
1385 piece_ids
1386 .iter()
1387 .filter_map(|piece_id| pieces_by_id.get(piece_id))
1388 .filter(|piece| {
1389 piece.start_vertex_id != piece.end_vertex_id
1390 && piece.curve.degree == 1
1391 && piece.curve.control_points.len() == 2
1392 && match (index.vertex_points.get(&piece.start_vertex_id), index.vertex_points.get(&piece.end_vertex_id)) {
1393 (Some(a), Some(b)) => {
1394 let gap = a.sub(*b).length();
1395 gap > weld && gap <= 1e-3 && (on_rim(a) || on_rim(b))
1396 }
1397 _ => false,
1398 }
1399 })
1400 .flat_map(|piece| [format!("i:{}", piece.start_vertex_id), format!("i:{}", piece.end_vertex_id)])
1401 .collect()
1402 } else {
1403 HashSet::default()
1404 };
1405 let junction_keys: HashSet<String> = if crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) {
1408 let mut seen: HashMap<u64, usize> = HashMap::default();
1409 for piece in active_pieces.iter().filter_map(|piece_id| pieces_by_id.get(piece_id)) {
1410 if piece.start_vertex_id != piece.end_vertex_id {
1411 *seen.entry(piece.start_vertex_id).or_default() += 1;
1412 *seen.entry(piece.end_vertex_id).or_default() += 1;
1413 }
1414 }
1415 seen.into_iter().filter(|(_, uses)| *uses >= 2).map(|(id, _)| format!("i:{id}")).collect()
1416 } else {
1417 HashSet::default()
1418 };
1419 let mut add_chain = |mut points: Vec<Vec2>,
1420 source: ChainSource,
1421 vertex_start_key: String,
1422 vertex_start_point: Vec3,
1423 vertex_end_key: String,
1424 vertex_end_point: Vec3,
1425 is_boundary: bool|
1426 -> Result<(), KernelRefusal> {
1427 for (at, key, point3) in [
1428 (0usize, vertex_start_key, vertex_start_point),
1429 (points.len() - 1, vertex_end_key, vertex_end_point),
1430 ] {
1431 let point = points[at];
1432 let bridged = bridge_keys.contains(&key);
1433 let junction = junction_keys.contains(&key);
1434 let images = vertex_images.entry(key).or_default();
1435 let canonical = images
1436 .iter()
1437 .copied()
1438 .find(|image| image.sub(point).length() <= snap_threshold)
1439 .or_else(|| {
1440 endpoint_images
1441 .iter()
1442 .find(|(candidate3, candidate)| {
1443 candidate3.sub(point3).length() <= image_band_3d
1444 && candidate.sub(point).length() <= image_band
1445 })
1446 .map(|candidate| candidate.1)
1447 })
1448 .or_else(|| {
1449 if bridged {
1450 return None;
1451 }
1452 boundary_side(point).and_then(|side| {
1453 boundary_images
1454 .iter()
1455 .find(|(candidate, candidate3)| {
1456 boundary_side(*candidate) == Some(side)
1457 && candidate.sub(point).length()
1458 <= image_band
1459 && (boundary_vertex_anchor_off
1463 || (!is_boundary && !junction)
1464 || candidate3.sub(point3).length() <= 1e-5)
1465 })
1466 .map(|(candidate, _)| *candidate)
1467 })
1468 });
1469 if let Some(canonical) = canonical {
1470 points[at] = canonical;
1471 images.push(canonical);
1472 } else {
1473 images.push(point);
1474 endpoint_images.push((point3, point));
1475 if is_boundary && boundary_side(point).is_some() {
1476 boundary_images.push((point, point3));
1477 }
1478 }
1479 }
1480 if points.len() > 2 {
1481 let start = points[0];
1482 let end = points[points.len() - 1];
1483 let thin = |radius: f64| {
1484 let mut kept = vec![start];
1485 kept.extend(points[1..points.len() - 1].iter().copied().filter(|point| {
1486 point.sub(start).length() > radius && point.sub(end).length() > radius
1487 }));
1488 kept.push(end);
1489 kept
1490 };
1491 let mut kept = thin(junction_radius);
1492 let closed = start.sub(end).length() <= arrangement_tolerance;
1501 if kept.len() < if closed { 4 } else { 3 } && small_ring_enabled() {
1502 let chord = end.sub(start);
1503 let span = chord.length();
1504 let bulge = points
1505 .iter()
1506 .map(|point| {
1507 let offset = point.sub(start);
1508 if closed || span <= arrangement_tolerance {
1509 offset.length()
1510 } else {
1511 (offset.x * chord.y - offset.y * chord.x).abs() / span
1512 }
1513 })
1514 .fold(0.0, f64::max);
1515 if bulge > arrangement_tolerance * if lens_face { 4.0 } else { 10.0 } {
1518 kept = thin(bulge * 0.1);
1519 }
1520 }
1521 points = kept;
1522 }
1523 let chain_index = chains.len();
1524 let chain_segments = points
1525 .windows(2)
1526 .map(|pair| (pair[0], pair[1]))
1527 .collect::<Vec<_>>();
1528 for (segment_index, pair) in points.windows(2).enumerate() {
1529 segments.push(Segment2 {
1530 a: pair[0],
1531 b: pair[1],
1532 tag: segment_tag(chain_index, segment_index),
1533 });
1534 }
1535 chains.push(Chain {
1536 source,
1537 count: points.len() - 1,
1538 start: points[0],
1539 end: points[points.len() - 1],
1540 segments: chain_segments,
1541 });
1542 Ok(())
1543 };
1544
1545 profile.hints += profile.lap(lap_start);
1546 let loop_hull_u: Vec<[f64; 2]> = face
1550 .loops
1551 .iter()
1552 .map(|loop_record| {
1553 let mut hull = [f64::INFINITY, f64::NEG_INFINITY];
1554 for coedge in &loop_record.coedges {
1555 for control in &coedge.pcurve.control_points {
1556 if control.w.abs() <= 1e-300 {
1557 continue;
1558 }
1559 hull[0] = hull[0].min(control.x / control.w);
1560 hull[1] = hull[1].max(control.x / control.w);
1561 }
1562 }
1563 hull
1564 })
1565 .collect();
1566 let mut full_span_loop_area: Option<f64> = None;
1571 let mut boundary_segments: Vec<(Vec2, Vec2)> = Vec::new();
1574 let mut band_hull = [[f64::INFINITY, f64::NEG_INFINITY]; 2];
1579 let boundary_vertex_hints: Vec<Vec2> = if boundary_vertex_hints_enabled() {
1596 let mut hints = Vec::new();
1597 for loop_record in &face.loops {
1598 for coedge in &loop_record.coedges {
1599 let [start, end] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1600 for parameter in [start, end] {
1601 let point = coedge.pcurve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
1602 hints.push(Vec2 { x: point.x, y: point.y });
1603 }
1604 }
1605 }
1606 hints
1607 } else {
1608 Vec::new()
1609 };
1610 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1611 let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1626 let offsets = if (closed.0 || closed.1)
1627 && std::env::var("BREP_LOOP_UNWRAP").as_deref() != Ok("0")
1628 {
1629 crate::topology::loop_seam_offsets(
1630 &loop_record.coedges,
1631 closed.0,
1632 closed.1,
1633 u_domain[1] - u_domain[0],
1634 v_domain[1] - v_domain[0],
1635 ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?
1636 } else {
1637 vec![[0.0, 0.0]; loop_record.coedges.len()]
1638 };
1639 let mut sampled: Vec<(usize, Vec<Vec2>, NurbsCurve, u64, u64)> =
1640 Vec::with_capacity(loop_record.coedges.len());
1641 for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1642 let edge = edge_for(solid, coedge.edge_id)?;
1643 let (start_vertex, end_vertex) = if coedge.forward {
1644 (edge.start_vertex_id, edge.end_vertex_id)
1645 } else {
1646 (edge.end_vertex_id, edge.start_vertex_id)
1647 };
1648 let offset = offsets
1649 .get(coedge_index)
1650 .copied()
1651 .unwrap_or([0.0, 0.0]);
1652 let boundary_points = if strip_resolution.is_some() || wedge_resolution.is_some() {
1655 let initial = sample_chain(&coedge.pcurve)?;
1656 sag_refine_chain(&coedge.pcurve, initial, sampling_bound)?.0
1657 } else {
1658 let initial = sample_boundary_chain(&coedge.pcurve, (diagonal * 1e-4).max(sampling_bound), 1024)?;
1662 if boundary_vertex_hints.is_empty() || initial.len() < 3 {
1663 refine_near_hints(&initial, &coedge.pcurve, &cut_hints)?
1664 } else {
1665 let own = [initial[0], initial[initial.len() - 1]];
1666 let hints: Vec<Vec2> = cut_hints
1667 .iter()
1668 .copied()
1669 .chain(boundary_vertex_hints.iter().copied().filter(|hint| {
1670 own.iter().all(|end| hint.sub(*end).length() > arrangement_tolerance)
1671 }))
1672 .collect();
1673 refine_near_hints(&initial, &coedge.pcurve, &hints)?
1674 }
1675 };
1676 let points: Vec<Vec2> = boundary_points
1677 .into_iter()
1678 .map(|point| {
1679 rebase_point(Vec2 {
1680 x: point.x + offset[0],
1681 y: point.y + offset[1],
1682 })
1683 })
1684 .collect();
1685 let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1686 let curve = if coedge.forward {
1687 curve
1688 } else {
1689 curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?
1690 };
1691 sampled.push((coedge_index, points, curve, start_vertex, end_vertex));
1692 }
1693 let image_shift: Option<f64> = {
1714 let span = u_domain[1] - u_domain[0];
1715 let slack = arrangement_tolerance * 50.0;
1716 if !closed.0
1717 || face.loops.len() < 2
1718 || span <= 0.0
1719 || std::env::var("BREP_SEAM_IMAGE_LOOPS").as_deref() == Ok("0")
1720 {
1721 None
1722 } else {
1723 let mut min_u = f64::INFINITY;
1724 let mut max_u = f64::NEG_INFINITY;
1725 let mut area = 0.0;
1726 let mut flat: Vec<Vec2> = sampled
1727 .iter()
1728 .flat_map(|(_, points, ..)| points.iter().copied())
1729 .collect();
1730 if flat.len() < 3 {
1731 flat.clear();
1732 }
1733 for (index, point) in flat.iter().enumerate() {
1734 min_u = min_u.min(point.x);
1735 max_u = max_u.max(point.x);
1736 let next = flat[(index + 1) % flat.len()];
1737 area += crate::polygon::area_term([point.x, point.y], [next.x, next.y]);
1738 }
1739 let spans_full_domain =
1745 !flat.is_empty() && max_u - min_u >= span * (1.0 - 1e-6);
1746 if spans_full_domain && full_span_loop_area.is_none() {
1747 full_span_loop_area = Some(area);
1748 }
1749 let straddles_low = min_u < u_domain[0] - slack;
1750 let straddles_high = max_u > u_domain[1] + slack;
1751 let compact = max_u - min_u <= 0.5 * span;
1752 let is_hole = full_span_loop_area
1753 .map(|outer| !spans_full_domain && area * outer < 0.0)
1754 .unwrap_or(false);
1755 let has_full_span_other = loop_hull_u.iter().enumerate().any(|(other, hull)| {
1756 other != loop_index
1757 && hull[0] <= u_domain[0] + 1e-6 * span
1758 && hull[1] >= u_domain[1] - 1e-6 * span
1759 });
1760 if compact && is_hole && has_full_span_other && (straddles_low ^ straddles_high) {
1761 if env_read!("BREP_DEBUG_FRAG")
1762 .map(|value| value == face.id.to_string())
1763 .unwrap_or(false)
1764 {
1765 eprintln!(
1766 " seam-image: face {} loop {loop_index} straddles u-wall (u=[{min_u:.6},{max_u:.6}]) — inserting {} period image",
1767 face.id,
1768 if straddles_low { "+1" } else { "-1" }
1769 );
1770 }
1771 Some(if straddles_low { span } else { -span })
1772 } else {
1773 None
1774 }
1775 }
1776 };
1777 for (coedge_index, points, curve, start_vertex, end_vertex) in sampled {
1778 let coedge = &loop_record.coedges[coedge_index];
1779 for point in &points {
1780 band_hull[0] = [band_hull[0][0].min(point.x), band_hull[0][1].max(point.x)];
1781 band_hull[1] = [band_hull[1][0].min(point.y), band_hull[1][1].max(point.y)];
1782 }
1783 boundary_segments.extend(points.windows(2).map(|pair| (pair[0], pair[1])));
1784 add_chain(
1785 points.clone(),
1786 ChainSource::Boundary {
1787 coedge: coedge.clone(),
1788 curve: curve.clone(),
1789 },
1790 format!("b:{operand}:{start_vertex}"),
1791 vertex_point(solid, start_vertex)?,
1792 format!("b:{operand}:{end_vertex}"),
1793 vertex_point(solid, end_vertex)?,
1794 true,
1795 )?;
1796 if let Some(shift) = image_shift {
1797 let shifted: Vec<Vec2> = points
1798 .iter()
1799 .map(|point| Vec2 {
1800 x: point.x + shift,
1801 y: point.y,
1802 })
1803 .collect();
1804 boundary_segments
1805 .extend(shifted.windows(2).map(|pair| (pair[0], pair[1])));
1806 add_chain(
1807 shifted,
1808 ChainSource::Boundary {
1809 coedge: coedge.clone(),
1810 curve,
1811 },
1812 format!("b:{operand}:{start_vertex}"),
1813 vertex_point(solid, start_vertex)?,
1814 format!("b:{operand}:{end_vertex}"),
1815 vertex_point(solid, end_vertex)?,
1816 true,
1817 )?;
1818 }
1819 }
1820 }
1821 let (clamp_u, clamp_v) = {
1832 let mut clamp_u = u_domain;
1833 let mut clamp_v = v_domain;
1834 let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1835 if (closed_u || closed_v) && std::env::var("BREP_FRAG_ENV_CLAMP").as_deref() != Ok("0") {
1841 for loop_record in &face.loops {
1842 for coedge in &loop_record.coedges {
1843 for point in &coedge.pcurve.control_points {
1844 if point.w.abs() <= 1e-300 {
1845 continue;
1846 }
1847 if closed_u {
1848 clamp_u[0] = clamp_u[0].min(point.x / point.w);
1849 clamp_u[1] = clamp_u[1].max(point.x / point.w);
1850 }
1851 if closed_v {
1852 clamp_v[0] = clamp_v[0].min(point.y / point.w);
1853 clamp_v[1] = clamp_v[1].max(point.y / point.w);
1854 }
1855 }
1856 }
1857 }
1858 }
1859 (clamp_u, clamp_v)
1860 };
1861 profile.boundary += profile.lap(lap_start);
1862 for piece_id in active_pieces {
1863 let piece = pieces_by_id[&piece_id];
1864 let pcurve = pcurve_for(piece, face_key)?.clone();
1865 let (mut points, original_flags) = sag_refine_chain(
1882 &pcurve,
1883 sample_chain(&pcurve)?,
1884 sampling_bound,
1885 )?;
1886 for point in &mut points {
1887 if point.x < clamp_u[0] {
1888 point.x = clamp_u[0] + arrangement_tolerance * 10.0;
1889 } else if point.x > clamp_u[1] {
1890 point.x = clamp_u[1] - arrangement_tolerance * 10.0;
1891 }
1892 if point.y < clamp_v[0] {
1893 point.y = clamp_v[0] + arrangement_tolerance * 10.0;
1894 } else if point.y > clamp_v[1] {
1895 point.y = clamp_v[1] - arrangement_tolerance * 10.0;
1896 }
1897 }
1898 let snap_endpoint_to_domain = |point: Vec2| {
1899 let candidates = [
1900 (
1901 (point.x - u_domain[0]).abs(),
1902 Vec2 {
1903 x: u_domain[0],
1904 y: point.y,
1905 },
1906 ),
1907 (
1908 (point.x - u_domain[1]).abs(),
1909 Vec2 {
1910 x: u_domain[1],
1911 y: point.y,
1912 },
1913 ),
1914 (
1915 (point.y - v_domain[0]).abs(),
1916 Vec2 {
1917 x: point.x,
1918 y: v_domain[0],
1919 },
1920 ),
1921 (
1922 (point.y - v_domain[1]).abs(),
1923 Vec2 {
1924 x: point.x,
1925 y: v_domain[1],
1926 },
1927 ),
1928 ];
1929 let nearest = candidates
1930 .into_iter()
1931 .min_by(|first, second| first.0.total_cmp(&second.0))
1932 .unwrap();
1933 if nearest.0 <= arrangement_tolerance * 50.0 {
1934 nearest.1
1935 } else {
1936 point
1937 }
1938 };
1939 let last = points.len() - 1;
1940 let closed_axes = face.surface.closed_directions().unwrap_or((false, false));
1956 let keeps_vertex = |snapped: Vec2, original: Vec2, _vertex_id: u64| -> bool {
1957 let onto_seam = (closed_axes.0 && snapped.x != original.x) || (closed_axes.1 && snapped.y != original.y);
1958 if !crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) || !onto_seam {
1959 return true;
1960 }
1961 let (Ok(at), Ok(moved)) = (face.surface.evaluate(original.x, original.y), face.surface.evaluate(snapped.x, snapped.y)) else {
1962 return true;
1963 };
1964 let own = [piece.start_vertex_id, piece.end_vertex_id]
1965 .iter()
1966 .filter_map(|id| index.vertex_points.get(id))
1967 .min_by(|a, b| a.sub(at).length().total_cmp(&b.sub(at).length()));
1968 let keep = own.is_none_or(|vertex| moved.sub(*vertex).length() <= at.sub(*vertex).length());
1969 keep
1970 };
1971 let straight_on_plane = exact_end_stays_on()
1982 && !index.cosurface_pairs.iter().any(|(first, _)| *first == face_key)
1983 && face.surface.is_affine().unwrap_or(false)
1984 && piece.curve.degree == 1
1985 && piece.curve.control_points.len() == 2;
1986 let exact_end_off_edge = |snapped: Vec2, original: Vec2, vertex_id: u64| -> bool {
1987 if !straight_on_plane || (snapped.x == original.x && snapped.y == original.y) {
1988 return false;
1989 }
1990 let (Some(vertex), Ok(moved)) = (index.vertex_points.get(&vertex_id), face.surface.evaluate(snapped.x, snapped.y)) else {
1991 return false;
1992 };
1993 let identity = crate::classification::surface_uv_band(&face.surface, original.x, original.y, 1e-7);
1994 let off = original.sub(snapped).length();
1995 off > identity * 8.0 && moved.sub(*vertex).length() > 8e-7
1996 };
1997 if !bridge_keys.contains(&format!("i:{}", piece.start_vertex_id)) {
1998 let snapped = snap_endpoint_to_domain(points[0]);
1999 if keeps_vertex(snapped, points[0], piece.start_vertex_id)
2000 && !exact_end_off_edge(snapped, points[0], piece.start_vertex_id)
2001 {
2002 points[0] = snapped;
2003 }
2004 }
2005 if !bridge_keys.contains(&format!("i:{}", piece.end_vertex_id)) {
2006 let snapped = snap_endpoint_to_domain(points[last]);
2007 if keeps_vertex(snapped, points[last], piece.end_vertex_id)
2008 && !exact_end_off_edge(snapped, points[last], piece.end_vertex_id)
2009 {
2010 points[last] = snapped;
2011 }
2012 }
2013 for point in &mut points {
2014 *point = rebase_point(*point);
2015 }
2016 let mut lift = Vec2 { x: 0.0, y: 0.0 };
2039 if std::env::var("BREP_CUT_PERIOD_LIFT").as_deref() != Ok("0") {
2040 let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2041 for axis in 0..2 {
2042 let (is_closed, domain) = if axis == 0 { (closed.0, u_domain) } else { (closed.1, v_domain) };
2043 let [low, high] = band_hull[axis];
2044 let span = domain[1] - domain[0];
2045 if !is_closed || !(span > 0.0) || !(low < domain[0] || high > domain[1]) {
2046 continue;
2047 }
2048 let coordinate = |point: &Vec2| if axis == 0 { point.x } else { point.y };
2049 let middle = coordinate(&points[points.len() / 2]);
2050 let inside = |value: f64| value > low && value < high;
2051 if inside(middle) {
2052 continue;
2053 }
2054 let images: Vec<f64> = [-2.0, -1.0, 1.0, 2.0]
2055 .into_iter()
2056 .map(|periods| periods * span)
2057 .filter(|shift| inside(middle + shift))
2058 .collect();
2059 let [shift] = images[..] else {
2060 continue;
2061 };
2062 let slack = arrangement_tolerance * 50.0;
2063 let (reach_low, reach_high) = points.iter().map(coordinate).fold(
2064 (f64::INFINITY, f64::NEG_INFINITY),
2065 |(lo, hi), value| (lo.min(value), hi.max(value)),
2066 );
2067 if reach_low + shift < low - slack || reach_high + shift > high + slack {
2068 let [first, second] = piece.support_faces;
2069 return Err(KernelRefusal::internal(
2070 KernelStage::Fragment,
2071 "fragment.face_split",
2072 format!(
2073 "fragment_face: section piece {piece_id} of faces {}:{} x {}:{} crosses \
2074 the seam wall of face {}:{}'s unwrapped band ({} in [{low:.9}, {high:.9}], \
2075 the section's period image [{:.9}, {:.9}]) without a vertex there",
2076 first.operand,
2077 first.face_id,
2078 second.operand,
2079 second.face_id,
2080 operand,
2081 face.id,
2082 if axis == 0 { "u" } else { "v" },
2083 reach_low + shift,
2084 reach_high + shift,
2085 ),
2086 ));
2087 }
2088 for point in &mut points {
2089 if axis == 0 {
2090 point.x += shift;
2091 } else {
2092 point.y += shift;
2093 }
2094 }
2095 if axis == 0 {
2096 lift.x = shift;
2097 } else {
2098 lift.y = shift;
2099 }
2100 if env_read!("BREP_DEBUG_FRAG")
2101 .map(|value| value == face.id.to_string())
2102 .unwrap_or(false)
2103 {
2104 eprintln!(
2105 " period lift: face {} cut p{piece_id} {} {shift:+} into the band [{low:.6},{high:.6}]",
2106 face.id,
2107 if axis == 0 { "u" } else { "v" }
2108 );
2109 }
2110 }
2111 }
2112 points = enforce_boundary_crossing_parity(
2116 points,
2117 &original_flags,
2118 &boundary_segments,
2119 arrangement_tolerance,
2120 env_read!("BREP_DEBUG_FRAG")
2121 .map(|value| value == face.id.to_string())
2122 .unwrap_or(false),
2123 face.id,
2124 );
2125 let start_point = index
2126 .vertex_points
2127 .get(&piece.start_vertex_id)
2128 .copied()
2129 .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint start vertex"))?;
2130 let end_point = index
2131 .vertex_points
2132 .get(&piece.end_vertex_id)
2133 .copied()
2134 .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint end vertex"))?;
2135 add_chain(
2136 points,
2137 ChainSource::Cut {
2138 piece_id,
2139 pcurve,
2140 lift,
2141 curve: trimmed_curve(&piece.curve, piece.t0, piece.t1)?,
2142 shared_ring: piece.shared_edge.filter(|_| {
2143 piece
2144 .curve
2145 .evaluate(piece.t0)
2146 .ok()
2147 .zip(piece.curve.evaluate(piece.t1).ok())
2148 .is_some_and(|(a, b)| a.sub(b).length() <= 1e-6)
2149 }),
2150 },
2151 format!("i:{}", piece.start_vertex_id),
2152 start_point,
2153 format!("i:{}", piece.end_vertex_id),
2154 end_point,
2155 false,
2156 )?;
2157 }
2158 drop(add_chain);
2159
2160 let pole_gap_closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2188 if (pole_gap_closed.0 || pole_gap_closed.1)
2189 && std::env::var("BREP_POLE_GAP_BRIDGE").as_deref() != Ok("0")
2190 {
2191 let node_tol = arrangement_tolerance * 10.0;
2200 let mut nodes: Vec<(Vec2, usize)> = Vec::new();
2203 for chain in &chains {
2204 if !matches!(chain.source, ChainSource::Boundary { .. }) {
2205 continue;
2206 }
2207 for point in [chain.start, chain.end] {
2208 if let Some(entry) = nodes.iter_mut().find(|(q, _)| q.sub(point).length() <= node_tol)
2209 {
2210 entry.1 += 1;
2211 } else {
2212 nodes.push((point, 1));
2213 }
2214 }
2215 }
2216 let odd: Vec<Vec2> = nodes
2218 .iter()
2219 .filter(|(_, count)| count % 2 == 1)
2220 .map(|(point, _)| *point)
2221 .collect();
2222 let vertex_of = |point: Vec2| -> Option<u64> {
2225 vertex_images.iter().find_map(|(key, images)| {
2226 images
2227 .iter()
2228 .any(|image| image.sub(point).length() <= node_tol)
2229 .then(|| key.rsplit(':').next().and_then(|id| id.parse::<u64>().ok()))
2230 .flatten()
2231 })
2232 };
2233 let mut by_vertex: HashMap<u64, Vec<Vec2>> = HashMap::default();
2234 for point in &odd {
2235 if let Some(vertex_id) = vertex_of(*point) {
2236 by_vertex.entry(vertex_id).or_default().push(*point);
2237 }
2238 }
2239 let curve_degenerate = |curve: &NurbsCurve| -> bool {
2242 let Ok(domain) = curve.domain() else {
2243 return false;
2244 };
2245 let Ok(base) = curve.evaluate(domain[0]) else {
2246 return false;
2247 };
2248 [0.5, 1.0].iter().all(|fraction| {
2249 curve
2250 .evaluate(domain[0] + (domain[1] - domain[0]) * fraction)
2251 .map(|point| point.sub(base).length() <= 1e-5)
2252 .unwrap_or(false)
2253 })
2254 };
2255 for (vertex_id, images) in by_vertex {
2256 if images.len() != 2 {
2259 continue;
2260 }
2261 let (a, b) = (images[0], images[1]);
2262 let mut base: Option<Vec3> = None;
2266 let mut degenerate = true;
2267 for step in 0..=8 {
2268 let fraction = step as f64 / 8.0;
2269 let uv = a.add(b.sub(a).scale(fraction));
2270 match face.surface.evaluate(uv.x, uv.y) {
2271 Ok(point) => match base {
2272 None => base = Some(point),
2273 Some(reference) => {
2274 if point.sub(reference).length() > 1e-5 {
2275 degenerate = false;
2276 break;
2277 }
2278 }
2279 },
2280 Err(_) => {
2281 degenerate = false;
2282 break;
2283 }
2284 }
2285 }
2286 if !degenerate {
2287 continue;
2288 }
2289 let Some(source) = chains.iter().find_map(|chain| match &chain.source {
2292 ChainSource::Boundary { coedge, curve }
2293 if chain.start.sub(chain.end).length() <= node_tol
2294 && chain.count <= 1
2295 && (chain.start.sub(a).length() <= node_tol
2296 || chain.start.sub(b).length() <= node_tol)
2297 && curve_degenerate(curve) =>
2298 {
2299 Some(ChainSource::Boundary {
2300 coedge: coedge.clone(),
2301 curve: curve.clone(),
2302 })
2303 }
2304 _ => None,
2305 }) else {
2306 continue;
2307 };
2308 let chain_index = chains.len();
2309 segments.push(Segment2 {
2310 a,
2311 b,
2312 tag: segment_tag(chain_index, 0),
2313 });
2314 chains.push(Chain {
2315 source,
2316 count: 1,
2317 start: a,
2318 end: b,
2319 segments: vec![(a, b)],
2320 });
2321 boundary_segments.push((a, b));
2322 if env_read!("BREP_DEBUG_FRAG")
2323 .map(|value| value == face.id.to_string())
2324 .unwrap_or(false)
2325 {
2326 eprintln!(
2327 " pole-gap bridge: face {} vertex {vertex_id} joins \
2328 ({:.6},{:.6})->({:.6},{:.6}) along a degenerate iso-line",
2329 face.id, a.x, a.y, b.x, b.y
2330 );
2331 }
2332 }
2333 }
2334
2335 let coincidence_tolerance = arrangement_tolerance * 50.0;
2343 let point_segment_distance = |point: Vec2, a: Vec2, b: Vec2| -> f64 {
2344 let segment = b.sub(a);
2345 let length_squared = segment.dot(segment);
2346 if length_squared <= 1e-30 {
2347 return point.sub(a).length();
2348 }
2349 let parameter = (point.sub(a).dot(segment) / length_squared).clamp(0.0, 1.0);
2350 point.sub(a.add(segment.scale(parameter))).length()
2351 };
2352 let near_chain = |point: Vec2, chain: &Chain, tolerance: f64| {
2353 chain
2354 .segments
2355 .iter()
2356 .any(|(a, b)| point_segment_distance(point, *a, *b) <= tolerance)
2357 };
2358 let midpoint_tolerance = coincidence_tolerance * 8.0;
2373 profile.cuts += profile.lap(lap_start);
2392 let corner_veto_enabled = std::env::var("BREP_DUP_DROP_CORNER_VETO")
2393 .map(|value| value != "0")
2394 .unwrap_or(true);
2395 let node_tolerance = arrangement_tolerance;
2396 let terminates_at_distinct_boundary_vertex = |cut_end: Vec2, matched_end: Vec2| -> bool {
2397 cut_end.sub(matched_end).length() > node_tolerance
2398 && chains.iter().any(|other| {
2399 matches!(other.source, ChainSource::Boundary { .. })
2400 && (other.start.sub(cut_end).length() <= node_tolerance
2401 || other.end.sub(cut_end).length() <= node_tolerance)
2402 })
2403 };
2404 let debug_drop = env_read!("BREP_DEBUG_FRAG")
2405 .map(|value| value == face.id.to_string())
2406 .unwrap_or(false);
2407 let micro_boundary_skip = std::env::var("BREP_DUP_CUT_MICRO_BOUNDARY").as_deref() != Ok("0");
2422 let boundary_extent = |boundary: &Chain| -> f64 {
2423 boundary
2424 .segments
2425 .iter()
2426 .map(|(a, b)| b.sub(*a).length())
2427 .sum()
2428 };
2429 let pole_ends = std::env::var("BREP_DUP_DROP_POLE").as_deref() != Ok("0");
2448 let degenerate_chains: Vec<usize> = chains
2449 .iter()
2450 .enumerate()
2451 .filter(|(_, chain)| match &chain.source {
2452 ChainSource::Boundary { coedge, .. } => solid
2453 .edges
2454 .iter()
2455 .any(|edge| edge.id == coedge.edge_id && edge.degenerate),
2456 ChainSource::Cut { .. } => false,
2457 })
2458 .map(|(index, _)| index)
2459 .collect();
2460 let on_one_pole = |a: Vec2, b: Vec2| -> bool {
2461 degenerate_chains.iter().any(|&pole| {
2462 near_chain(a, &chains[pole], coincidence_tolerance)
2463 && near_chain(b, &chains[pole], coincidence_tolerance)
2464 })
2465 };
2466 let coincident_in_space = |cut: &Chain, boundary: &Chain, weld_scale: bool| -> bool {
2467 let ChainSource::Boundary { curve, coedge } = &boundary.source else {
2468 return false;
2469 };
2470 let ChainSource::Cut { curve: section, piece_id, .. } = &cut.source else {
2471 return false;
2472 };
2473 let Ok([start, end]) = section.domain() else {
2474 return false;
2475 };
2476 let mut chart_length = 0.0;
2477 let mut space_length = 0.0;
2478 for (a, b) in &boundary.segments {
2479 let (Ok(pa), Ok(pb)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else {
2480 return false;
2481 };
2482 chart_length += b.sub(*a).length();
2483 space_length += pb.sub(pa).length();
2484 }
2485 if chart_length <= 0.0 || space_length <= 0.0 {
2486 return false;
2487 }
2488 let copy_boundary = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2489 boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2490 || (cosurface_corner_copy_on()
2491 && boundary_is_cosurface_corner(solid, face_key, coedge.edge_id, piece, index))
2492 });
2493 let bound = if weld_scale {
2494 if copy_boundary { crate::tolerance::WELD_FLOOR } else { 1e-7 }
2495 } else {
2496 coincidence_tolerance * space_length / chart_length
2497 };
2498 let stations = cut.segments.len().max(16);
2499 (0..=stations).all(|index| {
2500 section
2501 .evaluate(start + (end - start) * index as f64 / stations as f64)
2502 .ok()
2503 .and_then(|at| crate::project_point_to_curve(curve, at).ok())
2504 .is_some_and(|projection| projection.distance <= bound)
2505 })
2506 };
2507 let follows_copy_both_ways = |cut: &Chain, boundary: &Chain| -> bool {
2513 let (ChainSource::Boundary { curve, coedge }, ChainSource::Cut { curve: section, piece_id, .. }) = (&boundary.source, &cut.source) else {
2514 return false;
2515 };
2516 let copy = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2517 boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2518 });
2519 if !copy || !coincident_in_space(cut, boundary, true) {
2520 return false;
2521 }
2522 let Ok([start, end]) = curve.domain() else {
2523 return false;
2524 };
2525 let stations = boundary.segments.len().max(16);
2526 let mut distances = Vec::with_capacity(stations + 1);
2527 for station in 0..=stations {
2528 let Some(distance) = curve
2529 .evaluate(start + (end - start) * station as f64 / stations as f64)
2530 .ok()
2531 .and_then(|at| crate::project_point_to_curve(section, at).ok())
2532 .map(|projection| projection.distance)
2533 else {
2534 return false;
2535 };
2536 if distance > crate::tolerance::WELD_FLOOR {
2537 return false;
2538 }
2539 distances.push(distance);
2540 }
2541 let interior = &distances[stations / 20 + 1..stations - stations / 20];
2546 let (nearest, farthest) = interior
2547 .iter()
2548 .fold((f64::INFINITY, 0.0f64), |(low, high), &distance| (low.min(distance), high.max(distance)));
2549 farthest <= 1e-7 || nearest <= 0.1 * farthest
2550 };
2551 let mut dropped_chains = HashSet::default();
2552 for (index, chain) in chains.iter().enumerate() {
2553 if !matches!(chain.source, ChainSource::Cut { .. }) {
2554 continue;
2555 }
2556 let mut matched_boundary: Option<usize> = None;
2557 for (boundary_index, boundary) in chains.iter().enumerate() {
2558 if !matches!(boundary.source, ChainSource::Boundary { .. }) {
2559 continue;
2560 }
2561 if micro_boundary_skip && boundary_extent(boundary) <= coincidence_tolerance {
2566 continue;
2567 }
2568 let forward = boundary.start.sub(chain.start).length() <= coincidence_tolerance
2569 && boundary.end.sub(chain.end).length() <= coincidence_tolerance;
2570 let reversed = boundary.start.sub(chain.end).length() <= coincidence_tolerance
2571 && boundary.end.sub(chain.start).length() <= coincidence_tolerance;
2572 let same_end = |a: Vec2, b: Vec2| a.sub(b).length() <= coincidence_tolerance || on_one_pole(a, b);
2573 let (forward, reversed, at_pole) = if forward || reversed || !pole_ends || degenerate_chains.is_empty() {
2574 (forward, reversed, false)
2575 } else {
2576 let forward = same_end(boundary.start, chain.start) && same_end(boundary.end, chain.end);
2577 let reversed = same_end(boundary.start, chain.end) && same_end(boundary.end, chain.start);
2578 (forward, reversed, true)
2579 };
2580 if !(forward || reversed) {
2581 continue;
2582 }
2583 let interior_coincident = if at_pole {
2584 coincident_in_space(chain, boundary, false)
2585 } else {
2586 chain.segments.iter().all(|(a, b)| {
2587 near_chain(*a, boundary, coincidence_tolerance)
2588 && near_chain(*b, boundary, coincidence_tolerance)
2589 && near_chain(a.add(*b).scale(0.5), boundary, midpoint_tolerance)
2590 })
2591 };
2592 let interior_coincident = interior_coincident
2606 || (dup_cut_space_nomination_enabled() && follows_copy_both_ways(chain, boundary));
2607 if !interior_coincident {
2608 continue;
2609 }
2610 let identical_segment = chain.segments.len() == 1
2619 && boundary.segments.len() == 1
2620 && ((chain.start.sub(boundary.start).length() <= node_tolerance
2621 && chain.end.sub(boundary.end).length() <= node_tolerance)
2622 || (chain.start.sub(boundary.end).length() <= node_tolerance
2623 && chain.end.sub(boundary.start).length() <= node_tolerance));
2624 if !identical_segment
2625 && std::env::var("BREP_DUP_CUT_GEOMETRY").as_deref() != Ok("0")
2626 && !coincident_in_space(chain, boundary, true)
2627 {
2628 continue;
2629 }
2630 if corner_veto_enabled {
2631 let (bnd_for_start, bnd_for_end) = if forward {
2633 (boundary.start, boundary.end)
2634 } else {
2635 (boundary.end, boundary.start)
2636 };
2637 if terminates_at_distinct_boundary_vertex(chain.start, bnd_for_start)
2638 || terminates_at_distinct_boundary_vertex(chain.end, bnd_for_end)
2639 {
2640 continue;
2641 }
2642 }
2643 matched_boundary = Some(boundary_index);
2644 break;
2645 }
2646 if let Some(boundary_index) = matched_boundary {
2647 if debug_drop {
2648 let boundary = &chains[boundary_index];
2649 eprintln!(
2650 " drop cut chain {} as duplicate of boundary chain {} (endpoint gaps {:.3e}/{:.3e})",
2651 index,
2652 boundary_index,
2653 boundary.start.sub(chain.start).length(),
2654 boundary.end.sub(chain.end).length(),
2655 );
2656 }
2657 dropped_chains.insert(index);
2658 }
2659 }
2660 if !dropped_chains.is_empty() {
2661 segments.retain(|segment| {
2662 tag_chain(&segment.tag)
2663 .map(|chain| !dropped_chains.contains(&(chain as usize)))
2664 .unwrap_or(true)
2665 });
2666 }
2667
2668 let debug = env_read!("BREP_DEBUG_FRAG")
2669 .map(|value| value == face.id.to_string())
2670 .unwrap_or(false);
2671 if debug {
2672 eprintln!(
2673 "fragment_face {}: domain u={:?} v={:?} arr_tol={:.3e} chains={} segments={}",
2674 face.id,
2675 u_domain,
2676 v_domain,
2677 arrangement_tolerance,
2678 chains.len(),
2679 segments.len()
2680 );
2681 for (index, chain) in chains.iter().enumerate() {
2682 let kind = match &chain.source {
2683 ChainSource::Boundary { coedge, .. } => format!("boundary e{}", coedge.edge_id),
2684 ChainSource::Cut { piece_id, .. } => format!("cut p{piece_id}"),
2685 };
2686 eprintln!(
2687 " chain {index} {kind} count={} start=({:.9},{:.9}) end=({:.9},{:.9})",
2688 chain.count, chain.start.x, chain.start.y, chain.end.x, chain.end.y
2689 );
2690 }
2691 }
2692 if chains.iter().any(|c| matches!(c.source, ChainSource::Cut { .. })) {
2708 let endpoints: Vec<(usize, bool, Vec2)> = chains
2709 .iter()
2710 .enumerate()
2711 .flat_map(|(i, c)| [(i, false, c.start), (i, true, c.end)])
2712 .collect();
2713 let anchored = |chain: usize, point: Vec2| -> bool {
2714 boundary_side(point).is_some()
2715 || endpoints.iter().any(|(other_chain, _, other_point)| {
2716 *other_chain != chain
2717 && other_point.sub(point).length() <= junction_radius
2718 })
2719 };
2720 let cut_chain_has_interior_crossing = |i: usize| -> bool {
2744 let chain = &chains[i];
2745 chains.iter().enumerate().any(|(j, other)| {
2746 if j == i
2749 || dropped_chains.contains(&j)
2750 || !matches!(other.source, ChainSource::Cut { .. })
2751 {
2752 return false;
2753 }
2754 chain.segments.iter().any(|&(a0, a1)| {
2755 other.segments.iter().any(|&(b0, b1)| {
2756 let Some([t, _]) = crate::arrangement::segment_intersection(
2757 a0,
2758 a1,
2759 b0,
2760 b1,
2761 arrangement_tolerance,
2762 ) else {
2763 return false;
2764 };
2765 let crossing = a0.add(a1.sub(a0).scale(t));
2766 crossing.sub(chain.start).length() > junction_radius
2767 && crossing.sub(chain.end).length() > junction_radius
2768 })
2769 })
2770 })
2771 };
2772 let boundary_anchor = bridge_boundary_t_junction_anchor_enabled();
2773 let lies_on_another_cut_run = |i: usize, point: Vec2| -> bool {
2774 bridge_t_junction_anchor_enabled()
2775 && chains.iter().enumerate().any(|(j, other)| {
2776 j != i
2777 && !dropped_chains.contains(&j)
2778 && (boundary_anchor || matches!(other.source, ChainSource::Cut { .. }))
2779 && other.segments.iter().any(|&(a, b)| {
2780 let along = b.sub(a);
2781 let span = along.dot(along);
2782 let t = if span > 0.0 {
2783 (point.sub(a).dot(along) / span).clamp(0.0, 1.0)
2784 } else {
2785 0.0
2786 };
2787 a.add(along.scale(t)).sub(point).length() <= arrangement_tolerance
2788 })
2789 })
2790 };
2791 let mut loose: Vec<(usize, bool, Vec2)> = Vec::new();
2792 for (i, c) in chains.iter().enumerate() {
2793 if !matches!(c.source, ChainSource::Cut { .. }) {
2794 continue;
2795 }
2796 for (is_end, this, other) in [(false, c.start, c.end), (true, c.end, c.start)] {
2797 if !anchored(i, this) && anchored(i, other) {
2798 if lies_on_another_cut_run(i, this) {
2799 if debug {
2800 eprintln!(" cut chain {i} end {} is a T-junction on another chain's run", if is_end { "end" } else { "start" });
2801 }
2802 continue;
2803 }
2804 if cut_chain_has_interior_crossing(i) {
2805 if debug {
2806 eprintln!(
2807 " cut chain {i} loose {} excluded from junction bridging — \
2808 the chain crosses another cut chain mid-run; arrangement \
2809 pruning owns the overshoot stub",
2810 if is_end { "end" } else { "start" },
2811 );
2812 }
2813 continue;
2814 }
2815 loose.push((i, is_end, this));
2816 }
2817 }
2818 }
2819 let bridge_band = (diagonal * 0.02).max(junction_radius * 4.0);
2823 if debug && !loose.is_empty() {
2824 eprintln!(" junction_radius={junction_radius:.6} bridge_band={bridge_band:.6} loose={loose:?}");
2825 }
2826 let skip_crossing_pairs = bridge_skip_crossing_pairs_enabled();
2827 let chains_cross = |i: usize, j: usize| -> bool {
2828 chains[i].segments.iter().any(|&(a0, a1)| {
2829 chains[j].segments.iter().any(|&(b0, b1)| {
2830 crate::arrangement::segment_intersection(a0, a1, b0, b1, arrangement_tolerance).is_some()
2831 })
2832 })
2833 };
2834 let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
2835 for a in 0..loose.len() {
2836 for b in (a + 1)..loose.len() {
2837 if loose[a].0 == loose[b].0 {
2838 continue; }
2840 if skip_crossing_pairs && chains_cross(loose[a].0, loose[b].0) {
2841 if debug {
2842 eprintln!(" loose ends of chains {} and {} are not bridged: the chains cross", loose[a].0, loose[b].0);
2843 }
2844 continue;
2845 }
2846 let gap = loose[a].2.sub(loose[b].2).length();
2847 if gap <= bridge_band {
2848 pairs.push((gap, a, b));
2849 }
2850 }
2851 }
2852 pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
2853 let bridge_3d_gate = std::env::var("BREP_BRIDGE_3D_GATE").as_deref() != Ok("0");
2869 let face_diameter3 = if bridge_3d_gate && !pairs.is_empty() {
2870 let mut samples: Vec<Vec3> = Vec::new();
2871 'grid: for i in 0..3 {
2872 for j in 0..3 {
2873 let u = u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 2.0;
2874 let v = v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 2.0;
2875 match face.surface.evaluate(u, v) {
2876 Ok(point) => samples.push(point),
2877 Err(_) => {
2878 samples.clear();
2879 break 'grid;
2880 }
2881 }
2882 }
2883 }
2884 let mut diameter = 0.0f64;
2885 for (index, a) in samples.iter().enumerate() {
2886 for b in samples.iter().skip(index + 1) {
2887 diameter = diameter.max(a.sub(*b).length());
2888 }
2889 }
2890 (diameter > 0.0).then_some(diameter)
2891 } else {
2892 None
2893 };
2894 let mut consumed = vec![false; loose.len()];
2895 let mut bridged = 0usize;
2896 for (gap, a, b) in pairs {
2897 if consumed[a] || consumed[b] {
2898 continue;
2899 }
2900 consumed[a] = true;
2901 consumed[b] = true;
2902 let (chain_a, _, point_a) = loose[a];
2903 let (chain_b, _, point_b) = loose[b];
2904 if let Some(diameter) = face_diameter3 {
2905 let wrapped_a = wrap_back(point_a);
2906 let wrapped_b = wrap_back(point_b);
2907 if let (Ok(position_a), Ok(position_b)) = (
2908 face.surface.evaluate(wrapped_a.x, wrapped_a.y),
2909 face.surface.evaluate(wrapped_b.x, wrapped_b.y),
2910 ) {
2911 let gap3 = position_a.sub(position_b).length();
2912 let limit = 0.01 * diameter;
2913 if gap3 > limit {
2914 return Err(KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", format!(
2915 "fragment_face {}: cut junction bridge refused — 3D gap \
2916 {gap3:.4} exceeds {limit:.4} (1% of face diameter \
2917 {diameter:.4}) across uv gap {gap:.6}; a section piece \
2918 is missing between chains {chain_a} and {chain_b}",
2919 face.id
2920 )));
2921 }
2922 }
2923 }
2924 let midpoint = point_a.add(point_b).scale(0.5);
2925 if debug {
2926 eprintln!(
2927 " bridging chain {chain_a} at ({:.9},{:.9}) and chain {chain_b} at ({:.9},{:.9}), uv gap {gap:.6}",
2928 point_a.x, point_a.y, point_b.x, point_b.y
2929 );
2930 }
2931 for (chain, old) in [(chain_a, point_a), (chain_b, point_b)] {
2932 if chains[chain].start.sub(old).length() <= 1e-15 {
2933 chains[chain].start = midpoint;
2934 }
2935 if chains[chain].end.sub(old).length() <= 1e-15 {
2936 chains[chain].end = midpoint;
2937 }
2938 for seg in &mut chains[chain].segments {
2939 if seg.0.sub(old).length() <= 1e-15 {
2940 seg.0 = midpoint;
2941 }
2942 if seg.1.sub(old).length() <= 1e-15 {
2943 seg.1 = midpoint;
2944 }
2945 }
2946 for segment in segments.iter_mut() {
2947 if tag_chain(&segment.tag) != Some(chain as u64) {
2948 continue;
2949 }
2950 if segment.a.sub(old).length() <= 1e-15 {
2951 segment.a = midpoint;
2952 }
2953 if segment.b.sub(old).length() <= 1e-15 {
2954 segment.b = midpoint;
2955 }
2956 }
2957 }
2958 bridged += 1;
2959 }
2960 if debug && bridged > 0 {
2961 eprintln!(" bridged {bridged} broken cut junction(s)");
2962 }
2963 }
2964 if std::env::var("BREP_GRAZE_HOOK_CLIP").as_deref() != Ok("0") {
2994 let raw_extent = if solid.vertices.is_empty() {
2995 0.0
2996 } else {
2997 let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2998 let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2999 for v in &solid.vertices {
3000 lo.x = lo.x.min(v.point.x);
3001 lo.y = lo.y.min(v.point.y);
3002 lo.z = lo.z.min(v.point.z);
3003 hi.x = hi.x.max(v.point.x);
3004 hi.y = hi.y.max(v.point.y);
3005 hi.z = hi.z.max(v.point.z);
3006 }
3007 hi.sub(lo).length()
3008 };
3009 let band = 2.0 * 1e-5 * raw_extent.max(1.0);
3013 let sep_cap = (1.5e-3 * raw_extent).max(band);
3014 let graze_debug = debug || std::env::var("BREP_DEBUG_GRAZE").as_deref() == Ok("1");
3015
3016 let mut plans: Vec<(usize, Vec<(Vec2, Vec2)>, f64)> = Vec::new();
3017 for ci in 0..chains.len() {
3018 if !matches!(chains[ci].source, ChainSource::Cut { .. }) {
3019 continue;
3020 }
3021 if dropped_chains.contains(&ci) {
3024 continue;
3025 }
3026 if chains[ci].segments.is_empty() {
3027 continue;
3028 }
3029 let mut lo_cut: Option<usize> = None; let mut hi_cut: Option<usize> = None; let mut measured = 0.0f64;
3032 let mut bail = false;
3033 for &at_end in &[false, true] {
3034 let p = if at_end {
3035 chains[ci].end
3036 } else {
3037 chains[ci].start
3038 };
3039 let Ok(p3) = face.surface.evaluate(p.x, p.y) else {
3040 continue;
3041 };
3042 for bi in 0..chains.len() {
3043 if bi == ci || !matches!(chains[bi].source, ChainSource::Boundary { .. }) {
3044 continue;
3045 }
3046 let shares = chains[bi].start.sub(p).length() <= node_tolerance
3047 || chains[bi].end.sub(p).length() <= node_tolerance;
3048 if !shares {
3049 continue;
3050 }
3051 for si in 0..chains[ci].segments.len() {
3052 let (sa, sb) = chains[ci].segments[si];
3053 for &(ba, bb) in &chains[bi].segments {
3054 let Some([t1, t2]) = crate::arrangement::segment_intersection(
3055 sa,
3056 sb,
3057 ba,
3058 bb,
3059 arrangement_tolerance,
3060 ) else {
3061 continue;
3062 };
3063 if !(t1 > 1e-3 && t1 < 1.0 - 1e-3 && t2 > 1e-3 && t2 < 1.0 - 1e-3) {
3067 continue;
3068 }
3069 let q = Vec2 {
3070 x: sa.x + (sb.x - sa.x) * t1,
3071 y: sa.y + (sb.y - sa.y) * t1,
3072 };
3073 let Ok(q3) = face.surface.evaluate(q.x, q.y) else {
3074 continue;
3075 };
3076 let dist = q3.sub(p3).length();
3077 if dist > sep_cap {
3078 bail = true;
3081 break;
3082 }
3083 measured = measured.max(dist);
3084 if at_end {
3085 hi_cut = Some(hi_cut.map_or(si, |m| m.min(si)));
3086 } else {
3087 lo_cut = Some(lo_cut.map_or(si, |m| m.max(si)));
3088 }
3089 }
3090 if bail {
3091 break;
3092 }
3093 }
3094 if bail {
3095 break;
3096 }
3097 }
3098 if bail {
3099 break;
3100 }
3101 }
3102 if bail || (lo_cut.is_none() && hi_cut.is_none()) {
3103 continue;
3104 }
3105 let segs = &chains[ci].segments;
3106 let keep_lo = lo_cut.map(|m| m + 1).unwrap_or(0);
3107 let keep_hi = hi_cut.unwrap_or(segs.len());
3108 if keep_lo >= keep_hi {
3109 continue;
3110 }
3111 let mut points: Vec<Vec2> = Vec::with_capacity(keep_hi - keep_lo + 3);
3112 if lo_cut.is_some() {
3113 points.push(chains[ci].start);
3114 }
3115 points.push(segs[keep_lo].0);
3116 for si in keep_lo..keep_hi {
3117 points.push(segs[si].1);
3118 }
3119 if hi_cut.is_some() {
3120 points.push(chains[ci].end);
3121 }
3122 let new_segments: Vec<(Vec2, Vec2)> = points
3123 .windows(2)
3124 .filter(|w| w[0].sub(w[1]).length() > 0.0)
3125 .map(|w| (w[0], w[1]))
3126 .collect();
3127 if new_segments.is_empty() {
3128 continue;
3129 }
3130 if graze_debug {
3131 eprintln!(
3132 "graze-hook-clip: face {} cut chain {} measured_band={:.3e} sep_cap={:.3e} \
3133 segs {} -> {} (lo_cut={:?} hi_cut={:?})",
3134 face.id,
3135 ci,
3136 measured,
3137 sep_cap,
3138 chains[ci].segments.len(),
3139 new_segments.len(),
3140 lo_cut,
3141 hi_cut
3142 );
3143 }
3144 plans.push((ci, new_segments, measured));
3145 }
3146 for (ci, new_segments, _) in plans {
3147 chains[ci].count = new_segments.len();
3148 chains[ci].segments = new_segments.clone();
3149 segments.retain(|s| tag_chain(&s.tag) != Some(ci as u64));
3150 for (segment_index, (a, b)) in new_segments.into_iter().enumerate() {
3151 segments.push(Segment2 {
3152 a,
3153 b,
3154 tag: segment_tag(ci, segment_index),
3155 });
3156 }
3157 }
3158 }
3159 profile.dedup_bridge += profile.lap(lap_start);
3160 profile.arranged_faces += 1;
3161 let lens_apart_on = lens_face && crate::switch!("BREP_LENS_PAIR_APART", true);
3173 let lens_apart_check = lens_face && crate::switch!("BREP_LENS_PAIR_APART_CHECK", false);
3174 let lens_pairs: Vec<crate::LensPair> = if lens_apart_on || lens_apart_check {
3175 let shapes: Vec<(Vec2, Vec2, &[(Vec2, Vec2)])> = chains.iter().map(|chain| (chain.start, chain.end, chain.segments.as_slice())).collect();
3176 let pairs = lens_pairs(&shapes, arrangement_tolerance);
3177 if lens_apart_check && !pairs.is_empty() {
3178 let shown: Vec<(u64, u64, f64, f64)> = pairs.iter().map(|pair| (pair.first, pair.second, pair.ends[0].2, pair.ends[1].2)).collect();
3179 eprintln!("lens pairs apart: face {} pairs (first, second, start zone, end zone) {shown:?}", face.id);
3180 }
3181 pairs
3182 } else {
3183 Vec::new()
3184 };
3185 let regions = if lens_apart_on && !lens_pairs.is_empty() {
3186 let chain_of: Vec<u64> = segments.iter().map(|segment| tag_chain(&segment.tag).unwrap_or(u64::MAX)).collect();
3187 let apart = crate::LensApart { chain_of: &chain_of, pairs: &lens_pairs };
3188 crate::arrange_segments_lens_apart(&segments, arrangement_tolerance, &apart).or_refuse(KernelStage::Fragment, "arrange_segments")?
3189 } else {
3190 arrange_segments(&segments, arrangement_tolerance).or_refuse(KernelStage::Fragment, "arrange_segments")?
3191 };
3192 profile.arrange += profile.lap(lap_start);
3193 profile.region_faces += 1;
3194 let source_winding = if std::env::var("BREP_FRAGMENT_SOURCE_WINDING").as_deref() == Ok("0") {
3202 None
3203 } else {
3204 source_loop_winding_negative(face)?
3205 };
3206 let reverse_loops = source_winding.unwrap_or(!face.same_sense);
3207 if debug && reverse_loops != !face.same_sense {
3208 eprintln!(
3209 " face {}: source loop winds {} against same_sense={} — orienting fragments to the source",
3210 face.id,
3211 if reverse_loops { "CW" } else { "CCW" },
3212 face.same_sense
3213 );
3214 }
3215 let stray_pieces: Vec<Vec<Vec2>> = if stray_piece_clearance_enabled() {
3221 let used: HashSet<u64> = regions
3222 .iter()
3223 .flat_map(|region| region.outer.iter().chain(region.holes.iter().flatten()))
3224 .filter_map(|usage| tag_chain(&usage.piece.parent.tag))
3225 .collect();
3226 chains
3227 .iter()
3228 .enumerate()
3229 .filter(|(index, chain)| matches!(chain.source, ChainSource::Cut { .. }) && !chain.segments.is_empty() && !used.contains(&(*index as u64)))
3230 .map(|(_, chain)| {
3231 let mut path: Vec<Vec2> = chain.segments.iter().map(|segment| segment.0).collect();
3233 path.push(chain.segments[chain.segments.len() - 1].1);
3234 let back: Vec<Vec2> = path[1..path.len() - 1].iter().rev().copied().collect();
3235 path.extend(back);
3236 path
3237 })
3238 .collect()
3239 } else {
3240 Vec::new()
3241 };
3242 let mut fragments = Vec::new();
3243 for mut region in regions {
3244 super::loops::detach_touched_closed_boundaries(&mut region, &chains, arrangement_tolerance)?;
3245 let order = FragmentOrder {
3246 area: region.outer_area,
3247 key: super::loops::region_topology_key(®ion.outer, ®ion.holes),
3248 };
3249 let mut region_lap = profile.enabled.then(Instant::now);
3250 let arranged: Vec<Vec2> = if stray_pieces.is_empty() {
3251 interior_points(®ion.outer, ®ion.holes, region.area, 3)
3252 } else {
3253 super::loops::interior_points_clear_of(®ion.outer, ®ion.holes, &stray_pieces, region.area, 3)
3254 };
3255 let interior_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3256 let candidates: Vec<Vec2> = arranged.iter().copied().map(wrap_back).collect();
3257 let Some(&test_uv) = candidates.first() else {
3258 if debug {
3259 eprintln!(" region area={:.6e}: no interior point", region.area);
3260 }
3261 continue;
3262 };
3263 let mut containment = parameter_point_in_face(face, test_uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3264 if containment != PolygonClass::Inside
3276 && band_rebase == [None, None]
3277 && (arranged[0].x != test_uv.x || arranged[0].y != test_uv.y)
3278 && std::env::var("BREP_REGION_TRIM_FRAME").as_deref() != Ok("0")
3279 {
3280 containment = parameter_point_in_face(face, arranged[0], 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3281 if debug {
3282 eprintln!(
3283 " region area={:.6e} test=({:.9},{:.9}) asked in the trim's frame at ({:.9},{:.9}): {:?}",
3284 region.area, test_uv.x, test_uv.y, arranged[0].x, arranged[0].y,
3285 containment == PolygonClass::Inside
3286 );
3287 }
3288 }
3289 if containment != PolygonClass::Inside {
3290 if debug {
3291 eprintln!(
3292 " region area={:.6e} test=({:.9},{:.9}): outside trimmed face",
3293 region.area, test_uv.x, test_uv.y
3294 );
3295 }
3296 continue;
3297 }
3298 if debug {
3299 eprintln!(
3300 " region area={:.6e} test=({:.9},{:.9}): KEPT",
3301 region.area, test_uv.x, test_uv.y
3302 );
3303 }
3304 let containment_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3305 let Some(outer_loop) = build_loop(
3306 ®ion.outer,
3307 reverse_loops,
3308 &chains,
3309 arrangement_tolerance,
3310 &face.surface,
3311 )?
3312 else {
3313 if debug {
3316 eprintln!(" region area={:.6e}: dropped (degenerate antenna)", region.area);
3317 }
3318 continue;
3319 };
3320 let mut loops = vec![outer_loop];
3321 for hole in ®ion.holes {
3322 if let Some(hole_loop) = build_loop(
3326 hole,
3327 reverse_loops,
3328 &chains,
3329 arrangement_tolerance,
3330 &face.surface,
3331 )? {
3332 loops.push(hole_loop);
3333 }
3334 }
3335 for loop_record in &mut loops {
3336 for coedge in &mut loop_record.coedges {
3337 if let FragmentEdgeSource::Boundary {
3338 operand: source_operand,
3339 ..
3340 } = &mut coedge.source
3341 {
3342 *source_operand = operand;
3343 }
3344 }
3345 }
3346 let mut extra_test_points = Vec::new();
3347 for &candidate in candidates.iter().skip(1) {
3348 if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3349 extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3350 }
3351 }
3352 if profile.enabled {
3353 crate::imprint::profile_emit(format_args!("fragment.region face={} edges={} holes={} interior={interior_ms:.3} containment={containment_ms:.3} loops={:.3}",
3354 face.id, region.outer.len(), region.holes.len(), profile.lap(&mut region_lap).as_secs_f64() * 1000.0));
3355 }
3356 fragments.push(FaceFragmentRecord {
3357 operand,
3358 source_face_id: face.id,
3359 surface: face.surface.clone(),
3360 same_sense: face.same_sense,
3361 loops,
3362 test_point: face.surface.evaluate(test_uv.x, test_uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3363 test_uv,
3364 extra_test_points,
3365 order: Some(order),
3366 });
3367 }
3368
3369 profile.regions += profile.lap(lap_start);
3381 if fragments.is_empty() && piece_ids.is_empty() {
3382 const GRID: usize = 12;
3383 let mut test_uv: Option<Vec2> = None;
3384 let mut extra_test_points: Vec<Vec3> = Vec::new();
3385 'search: for iu in 1..GRID {
3386 for iv in 1..GRID {
3387 let candidate = Vec2 {
3388 x: u_domain[0] + (u_domain[1] - u_domain[0]) * iu as f64 / GRID as f64,
3389 y: v_domain[0] + (v_domain[1] - v_domain[0]) * iv as f64 / GRID as f64,
3390 };
3391 if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3392 if test_uv.is_none() {
3393 test_uv = Some(candidate);
3394 } else {
3395 extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3396 if extra_test_points.len() >= 2 {
3397 break 'search;
3398 }
3399 }
3400 }
3401 }
3402 }
3403 if test_uv.is_none() {
3419 let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
3420 if closed_u || closed_v {
3421 let u_period = u_domain[1] - u_domain[0];
3422 let v_period = v_domain[1] - v_domain[0];
3423 let mut loop_polygons: Vec<Vec<Vec2>> = Vec::new();
3424 let mut straddled = false;
3425 let (mut umin, mut umax, mut vmin, mut vmax) = (
3426 f64::INFINITY,
3427 f64::NEG_INFINITY,
3428 f64::INFINITY,
3429 f64::NEG_INFINITY,
3430 );
3431 for loop_record in &face.loops {
3432 let offsets = crate::topology::loop_seam_offsets(
3433 &loop_record.coedges,
3434 closed_u,
3435 closed_v,
3436 u_period,
3437 v_period,
3438 ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?;
3439 if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
3440 straddled = true;
3441 }
3442 let mut polygon = Vec::new();
3443 for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
3444 let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3445 let samples = 32usize;
3446 for k in 0..samples {
3447 let t = d0 + (d1 - d0) * k as f64 / samples as f64;
3448 let p = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Fragment, "evaluate")?;
3449 let uv = Vec2 {
3450 x: p.x + offsets[coedge_index][0],
3451 y: p.y + offsets[coedge_index][1],
3452 };
3453 umin = umin.min(uv.x);
3454 umax = umax.max(uv.x);
3455 vmin = vmin.min(uv.y);
3456 vmax = vmax.max(uv.y);
3457 polygon.push(uv);
3458 }
3459 }
3460 loop_polygons.push(polygon);
3461 }
3462 if straddled && umax > umin && vmax > vmin {
3463 let wrap = |value: f64, lo: f64, span: f64| {
3464 if span > 0.0 {
3465 lo + (value - lo).rem_euclid(span)
3466 } else {
3467 value
3468 }
3469 };
3470 'seam: for iu in 1..GRID {
3471 for iv in 1..GRID {
3472 let cu = umin + (umax - umin) * iu as f64 / GRID as f64;
3473 let cv = vmin + (vmax - vmin) * iv as f64 / GRID as f64;
3474 let candidate = Vec2 { x: cu, y: cv };
3475 let winding = loop_polygons
3480 .iter()
3481 .filter(|polygon| point_in_polygon(candidate, polygon))
3482 .count();
3483 if winding % 2 == 0 {
3484 continue;
3485 }
3486 let mapped = Vec2 {
3487 x: if closed_u {
3488 wrap(cu, u_domain[0], u_period)
3489 } else {
3490 cu
3491 },
3492 y: if closed_v {
3493 wrap(cv, v_domain[0], v_period)
3494 } else {
3495 cv
3496 },
3497 };
3498 if test_uv.is_none() {
3499 test_uv = Some(mapped);
3500 } else {
3501 extra_test_points
3502 .push(face.surface.evaluate(mapped.x, mapped.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3503 if extra_test_points.len() >= 2 {
3504 break 'seam;
3505 }
3506 }
3507 }
3508 }
3509 }
3510 }
3511 }
3512 if let Some(uv) = test_uv {
3513 fragments.push(FaceFragmentRecord {
3514 operand,
3515 source_face_id: face.id,
3516 surface: face.surface.clone(),
3517 same_sense: face.same_sense,
3518 loops: face
3519 .loops
3520 .iter()
3521 .map(|loop_record| FragmentLoop {
3522 coedges: loop_record
3523 .coedges
3524 .iter()
3525 .map(|coedge| FragmentCoedge {
3526 source: FragmentEdgeSource::Boundary {
3527 operand,
3528 edge_id: coedge.edge_id,
3529 },
3530 forward: coedge.forward,
3531 pcurve: coedge.pcurve.clone(),
3532 })
3533 .collect(),
3534 })
3535 .collect(),
3536 test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3537 test_uv: uv,
3538 extra_test_points,
3539 order: None,
3540 });
3541 }
3542 }
3543 profile.rescue += profile.lap(lap_start);
3544 Ok(fragments)
3545}
3546
3547pub fn fragment_solid(
3548 solid: &BrepSolid,
3549 operand: u8,
3550 imprint: &ImprintResultRecord,
3551) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3552 fragment_solid_against(solid, operand, imprint, None)
3553}
3554
3555pub fn bounded_carriers(solid: &BrepSolid) -> bool {
3558 solid.shells.iter().flat_map(|s| &s.faces).all(|face| bounded_carrier(face))
3559}
3560
3561fn bounded_carrier(face: &FaceRecord) -> bool {
3562 let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return false };
3563 let positive_finite = |p: &crate::Vec4| {
3564 p.w > 0.0 && p.w.is_finite() && p.point().is_ok_and(|v|
3565 v.x.is_finite() && v.y.is_finite() && v.z.is_finite())
3566 };
3567 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 };
3578 let (su, sv) = (slack(u), slack(v));
3579 face.surface.control_points.iter().flatten().all(positive_finite)
3580 && face.loops.iter().flat_map(|lp| &lp.coedges).all(|coedge| {
3581 coedge.pcurve.control_points.iter().all(|p| {
3582 positive_finite(p) && p.point().is_ok_and(|p|
3583 p.x >= u[0] - su && p.x <= u[1] + su && p.y >= v[0] - sv && p.y <= v[1] + sv)
3584 })
3585 })
3586}
3587
3588const SCOPE_ULPS: f64 = 64.0;
3590
3591fn scope_ulps_on() -> bool {
3592 crate::switch!("BREP_FRAGMENT_SCOPE_ULPS", true)
3593}
3594
3595pub fn face_separated(face: &FaceRecord, bounds: crate::Aabb, band: f64) -> bool {
3597 bounded_carrier(face) && crate::Aabb::from_surface_controls(&face.surface)
3598 .is_ok_and(|own| !own.intersects(bounds, band))
3599}
3600
3601fn trim_probe_enabled() -> bool {
3622 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3623 *ON.get_or_init(|| !matches!(std::env::var("BREP_FRAGMENT_TRIM_PROBE").as_deref(), Ok("0") | Ok("off")))
3624}
3625
3626fn untouched_fragment(
3628 face: &FaceRecord,
3629 operand: u8,
3630 uv: Vec2,
3631 extra_test_points: Vec<Vec3>,
3632) -> Result<FaceFragmentRecord, KernelRefusal> {
3633 Ok(FaceFragmentRecord {
3634 operand,
3635 source_face_id: face.id,
3636 surface: face.surface.clone(),
3637 same_sense: face.same_sense,
3638 loops: face
3639 .loops
3640 .iter()
3641 .map(|loop_record| FragmentLoop {
3642 coedges: loop_record
3643 .coedges
3644 .iter()
3645 .map(|coedge| FragmentCoedge {
3646 source: FragmentEdgeSource::Boundary {
3647 operand,
3648 edge_id: coedge.edge_id,
3649 },
3650 forward: coedge.forward,
3651 pcurve: coedge.pcurve.clone(),
3652 })
3653 .collect(),
3654 })
3655 .collect(),
3656 test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3657 test_uv: uv,
3658 extra_test_points,
3659 order: None,
3660 })
3661}
3662
3663fn stray_piece_clearance_enabled() -> bool {
3669 switch!("BREP_FRAGMENT_STRAY_PIECE_CLEARANCE", true)
3670}
3671
3672fn trim_interior_probe(
3673 face: &FaceRecord,
3674 u: [f64; 2],
3675 v: [f64; 2],
3676) -> Result<Option<(Vec2, Vec<Vec3>)>, KernelRefusal> {
3677 let diagonal = ((u[1] - u[0]).powi(2) + (v[1] - v[0]).powi(2)).sqrt();
3678 if !(diagonal > 0.0) {
3679 return Ok(None);
3680 }
3681 let mut found: Vec<Vec2> = Vec::new();
3682 'loops: for loop_record in &face.loops {
3683 for coedge in &loop_record.coedges {
3684 let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3685 if !(b > a) {
3686 continue;
3687 }
3688 for fraction in [0.5, 0.25, 0.75] {
3689 let t = a + (b - a) * fraction;
3690 let derivatives = coedge.pcurve.derivatives(t, 1).or_refuse(KernelStage::Fragment, "derivatives")?;
3691 let (at, tangent) = (derivatives[0], derivatives[1]);
3692 let speed = (tangent.x * tangent.x + tangent.y * tangent.y).sqrt();
3693 if !(speed > 0.0) || !speed.is_finite() {
3694 continue;
3695 }
3696 let normal = Vec2 { x: -tangent.y / speed, y: tangent.x / speed };
3697 for scale in [1e-2, 1e-3, 1e-4, 1e-5, 1e-6] {
3698 let step = diagonal * scale;
3699 for sign in [1.0, -1.0] {
3700 let candidate = Vec2 { x: at.x + normal.x * step * sign, y: at.y + normal.y * step * sign };
3701 if candidate.x < u[0] || candidate.x > u[1] || candidate.y < v[0] || candidate.y > v[1] {
3702 continue;
3703 }
3704 if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3705 found.push(candidate);
3706 if found.len() >= 3 {
3707 break 'loops;
3708 }
3709 continue 'loops;
3710 }
3711 }
3712 }
3713 }
3714 }
3715 }
3716 let Some(uv) = found.first().copied() else {
3717 return Ok(None);
3718 };
3719 let mut extra_test_points = Vec::new();
3720 for candidate in found.iter().skip(1) {
3721 extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3722 }
3723 Ok(Some((uv, extra_test_points)))
3724}
3725
3726fn separated_fragment(face: &FaceRecord, operand: u8) -> Option<FaceFragmentRecord> {
3727 let coedge = face.loops.first()?.coedges.first()?;
3728 let [a, b] = coedge.pcurve.domain().ok()?;
3729 let point = coedge.pcurve.evaluate(a + (b - a) * 0.5).ok()?;
3730 let uv = Vec2 { x: point.x, y: point.y };
3731 let test_point = face.surface.evaluate(uv.x, uv.y).ok()?;
3732 Some(FaceFragmentRecord {
3733 operand, source_face_id: face.id, surface: face.surface.clone(),
3734 same_sense: face.same_sense,
3735 loops: face.loops.iter().map(|lp| FragmentLoop {
3736 coedges: lp.coedges.iter().map(|coedge| FragmentCoedge {
3737 source: FragmentEdgeSource::Boundary { operand, edge_id: coedge.edge_id },
3738 forward: coedge.forward, pcurve: coedge.pcurve.clone(),
3739 }).collect(),
3740 }).collect(),
3741 test_point, test_uv: uv, extra_test_points: Vec::new(), order: None,
3742 })
3743}
3744
3745pub fn fragment_solid_against(
3746 solid: &BrepSolid,
3747 operand: u8,
3748 imprint: &ImprintResultRecord,
3749 other: Option<(crate::Aabb, f64)>,
3750) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3751 let mut profile = FragmentProfile::new();
3752 if profile.enabled {
3753 crate::classification::containment_profile_begin();
3754 }
3755 let result = fragment_solid_profiled(solid, operand, imprint, other, &mut profile);
3756 profile.report(operand);
3757 if profile.enabled {
3758 crate::classification::containment_profile_report("fragment");
3759 }
3760 result
3761}
3762
3763pub fn fragment_solid_profiled(
3764 solid: &BrepSolid,
3765 operand: u8,
3766 imprint: &ImprintResultRecord,
3767 other: Option<(crate::Aabb, f64)>,
3768 profile: &mut FragmentProfile,
3769) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3770 let index = FragmentIndex::build(imprint);
3771 let mut fragments = Vec::new();
3772 for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
3773 let far = other.is_some_and(|(bounds, band)| face_separated(face, bounds, band));
3774 if !far { profile.box_candidates += 1; }
3775 let has_pieces = index.by_face.get(&(operand, face.id)).is_some_and(|ids| !ids.is_empty());
3776 let cosurface = index.cosurface_pairs.iter().any(|(key, _)| key.operand == operand && key.face_id == face.id);
3777 if far && !has_pieces && !cosurface && std::env::var("BREP_FRAGMENT_SCOPE").as_deref() != Ok("0") {
3778 if let Some(fragment) = separated_fragment(face, operand) {
3779 profile.separated_faces += 1;
3780 profile.face_done(face.id, None);
3781 fragments.push(fragment);
3782 continue;
3783 }
3784 }
3785 let before = (profile.arranged_faces, profile.region_faces);
3786 fragments.extend(fragment_face_indexed(solid, operand, face, &index, profile)?);
3787 if far {
3788 profile.far_arranged += profile.arranged_faces - before.0;
3789 profile.far_regions += profile.region_faces - before.1;
3790 }
3791 }
3792 Ok(fragments)
3793}
3794
3795
3796fn rim_bridge_enabled() -> bool {
3799 crate::switch!("BREP_RIM_BRIDGE", true)
3800}
3801
3802pub(crate) fn lens_pairs(chains: &[(Vec2, Vec2, &[(Vec2, Vec2)])], tolerance: f64) -> Vec<crate::LensPair> {
3810 let (meet, zone_band) = (10.0 * tolerance, 4.0 * tolerance);
3811 let signed_to = |point: Vec2, segments: &[(Vec2, Vec2)]| -> (f64, f64) {
3814 let mut best = (f64::INFINITY, 0.0);
3815 for (a, b) in segments {
3816 let span = b.sub(*a);
3817 let squared = span.dot(span);
3818 let t = if squared > 0.0 { (point.sub(*a).dot(span) / squared).clamp(0.0, 1.0) } else { 0.0 };
3819 let foot = Vec2 { x: a.x + span.x * t, y: a.y + span.y * t };
3820 let distance = point.sub(foot).length();
3821 if distance < best.0 {
3822 let side = span.x * (point.y - a.y) - span.y * (point.x - a.x);
3823 best = (distance, side.signum());
3824 }
3825 }
3826 best
3827 };
3828 let points_of = |segments: &[(Vec2, Vec2)]| -> Vec<Vec2> { segments.iter().map(|(a, _)| *a).chain(segments.last().map(|(_, b)| *b)).collect() };
3829 let zone_from = |points: &[Vec2], other: &[(Vec2, Vec2)]| -> Option<f64> {
3832 let end = points[0];
3833 points.iter().skip(1).find(|point| signed_to(**point, other).0 > zone_band).map(|point| point.sub(end).length())
3834 };
3835 let one_side = |segments: &[(Vec2, Vec2)], other: &[(Vec2, Vec2)]| -> bool {
3836 let readings: Vec<(f64, f64)> = points_of(segments).iter().map(|point| signed_to(*point, other)).collect();
3837 let close = |reading: &(f64, f64)| reading.0 <= tolerance;
3838 let head = readings.iter().take_while(|reading| close(reading)).count();
3839 let tail = readings.iter().rev().take_while(|reading| close(reading)).count();
3840 if head + tail >= readings.len() {
3841 return false;
3842 }
3843 let middle = &readings[head..readings.len() - tail];
3844 let sign = middle[0].1;
3845 sign != 0.0 && middle.iter().all(|reading| !close(reading) && reading.1 == sign)
3846 };
3847 let mut pairs = Vec::new();
3848 for i in 0..chains.len() {
3849 for j in (i + 1)..chains.len() {
3850 let ((a_start, a_end, a), (b_start, b_end, b)) = (chains[i], chains[j]);
3851 if a.len() < 2 || b.len() < 2 {
3852 continue;
3853 }
3854 let open = |start: Vec2, end: Vec2| start.sub(end).length() > meet;
3855 let same = a_start.sub(b_start).length() <= meet && a_end.sub(b_end).length() <= meet;
3856 let reversed = a_start.sub(b_end).length() <= meet && a_end.sub(b_start).length() <= meet;
3857 if !(open(a_start, a_end) && open(b_start, b_end) && (same || reversed)) {
3858 continue;
3859 }
3860 if !(one_side(a, b) && one_side(b, a)) {
3866 continue;
3867 }
3868 let (a_points, b_points) = (points_of(a), points_of(b));
3869 let reversed_points = |points: &[Vec2]| -> Vec<Vec2> { points.iter().rev().copied().collect() };
3870 let (b_from_a_start, b_from_a_end) = if same { (b_points.clone(), reversed_points(&b_points)) } else { (reversed_points(&b_points), b_points.clone()) };
3871 let zone = |a_points: &[Vec2], b_points: &[Vec2]| -> Option<f64> { Some(zone_from(a_points, b)?.max(zone_from(b_points, a)?)) };
3872 let (Some(start_zone), Some(end_zone)) = (zone(&a_points, &b_from_a_start), zone(&reversed_points(&a_points), &b_from_a_end)) else { continue };
3873 pairs.push(crate::LensPair { first: i as u64, second: j as u64, ends: [(a_start, meet, start_zone), (a_end, meet, end_zone)] });
3874 }
3875 }
3876 pairs
3877}