1use crate::curve::interior_knot_count;
2use crate::topology::LoopRecord;
3pub use super::*;
4
5pub fn trim_sample_count(curve: &NurbsCurve) -> usize {
26 2usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4)
27}
28
29pub fn trim_station(start: f64, end: f64, index: usize, count: usize) -> f64 {
37 start + (end - start) * index as f64 / count as f64
38}
39
40pub const SEAM_BAND_MERGED_SWITCH: &str = "BREP_SEAM_BAND_MERGED";
45
46pub const HORIZON_CONTAINMENT_SWITCH: &str = "BREP_HORIZON_CONTAINMENT";
49
50pub const HORIZON_SINGLE_LOOP_SWITCH: &str = "BREP_HORIZON_SINGLE_LOOP";
54
55pub const HORIZON_CROSS_FRAME_SWITCH: &str = "BREP_HORIZON_CROSS_FRAME";
60
61pub const COVERING_RIM_STRIP_SWITCH: &str = "BREP_COVERING_RIM_STRIP";
64
65pub const NO_SPHERE_CHART_TRIM_SWITCH: &str = "BREP_NO_SPHERE_CHART_TRIM";
70
71pub fn horizon_cross_frame() -> bool {
84 switch!(HORIZON_CROSS_FRAME_SWITCH, true)
85}
86
87fn sphere_chart_trim_enabled() -> bool {
91 env_read!("BREP_NO_SPHERE_CHARTS").is_none()
92 && std::env::var(NO_SPHERE_CHART_TRIM_SWITCH).is_err()
93}
94
95fn point_segment_distance(point: Vec2, start: Vec2, end: Vec2) -> f64 {
96 point.distance_to_segment(start, end, 1e-30)
97}
98
99pub use crate::polygon::PolygonClass;
100
101pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
102 crate::polygon::classify(point, polygon, tolerance, 1e-30)
103}
104
105fn polygon_parity_inside(point: Vec2, polygon: &[Vec2]) -> bool {
108 crate::polygon::parity_inside([point.x, point.y], polygon.len(), |i| [polygon[i].x, polygon[i].y])
109}
110
111
112#[derive(Clone, Copy)]
117struct SegmentPrep {
118 coedge_index: usize,
119 parameter_start: f64,
120 parameter_end: f64,
121}
122
123pub fn lane_switches() -> f64 {
127 let mut bits = 0u32;
128 if !switch!(SEAM_BAND_MERGED_SWITCH, true) {
129 bits |= 1;
130 }
131 if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
132 bits |= 2;
133 }
134 if !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
135 bits |= 4;
136 }
137 if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
138 bits |= 8;
139 }
140 bits as f64
141}
142
143enum SeamBandPrep {
145 NotApplicable,
147 AlwaysInside,
149 Merged { polygon: Vec<Vec2>, u_span: f64, v_span: f64 },
151 Analyzed { polygon: Vec<Vec2> },
153 Rings { p_is_u: bool, q_lo: f64, q_hi: f64, complement: bool },
155 Declined,
157}
158
159struct SphereCapPrep {
161 rim: Vec<Vec2>,
162 pole_v: f64,
163 period: f64,
164}
165
166struct HorizonPrep {
168 loops: Vec<Vec<Vec2>>,
169 u_period: f64,
170 index: std::cell::OnceCell<Option<ChordIndex>>,
172}
173
174struct RimStripPrep {
176 lower: Vec<Vec2>,
177 upper: Vec<Vec2>,
178 period: f64,
179}
180
181pub struct GenericPrep {
184 pub loops: Vec<LoopSamples>,
185 segments: Vec<Vec<SegmentPrep>>,
186 chord_count: usize,
188 index: std::cell::OnceCell<Option<ChordIndex>>,
191}
192
193const CHORD_INDEX_MIN_CHORDS: usize = 64;
197
198const CHORD_INDEX_LEAF: usize = 6;
200
201const CHORD_INDEX_MAX_COORDINATE: f64 = 1e100;
206
207#[derive(Clone, Copy)]
213struct ChordNode {
214 low: Vec2,
215 high: Vec2,
216 loop_index: u32,
217 first: u32,
218 last: u32,
219 children: Option<(u32, u32)>,
220}
221
222struct ChordIndex {
255 nodes: Vec<ChordNode>,
256 roots: Vec<u32>,
258 slack: f64,
260}
261
262trait ChordLoops {
265 fn loop_count(&self) -> usize;
266 fn polygon(&self, index: usize) -> &[Vec2];
267}
268
269impl ChordLoops for [LoopSamples] {
270 fn loop_count(&self) -> usize {
271 self.len()
272 }
273
274 fn polygon(&self, index: usize) -> &[Vec2] {
275 &self[index].polygon
276 }
277}
278
279impl ChordLoops for [Vec<Vec2>] {
280 fn loop_count(&self) -> usize {
281 self.len()
282 }
283
284 fn polygon(&self, index: usize) -> &[Vec2] {
285 &self[index]
286 }
287}
288
289impl ChordIndex {
290 fn build<L: ChordLoops + ?Sized>(loops: &L) -> Option<ChordIndex> {
294 let mut nodes: Vec<ChordNode> = Vec::new();
295 let mut roots = Vec::new();
296 let mut largest: f64 = 0.0;
297 for loop_index in 0..loops.loop_count() {
298 let polygon = loops.polygon(loop_index);
299 let len = polygon.len();
300 if len == 0 {
301 continue;
302 }
303 u32::try_from(len).ok()?;
304 for sample in polygon {
305 if !(sample.x.abs() <= CHORD_INDEX_MAX_COORDINATE && sample.y.abs() <= CHORD_INDEX_MAX_COORDINATE) {
306 return None;
307 }
308 largest = largest.max(sample.x.abs()).max(sample.y.abs());
309 }
310 let loop_index = u32::try_from(loop_index).ok()?;
311 let mut level: Vec<u32> = Vec::with_capacity(len / CHORD_INDEX_LEAF + 1);
312 for first in (0..len).step_by(CHORD_INDEX_LEAF) {
313 let last = (first + CHORD_INDEX_LEAF).min(len);
314 let (mut low, mut high) = (polygon[first], polygon[first]);
315 for index in first..last {
316 let end = polygon[(index + 1) % len];
317 low = Vec2 { x: low.x.min(end.x), y: low.y.min(end.y) };
318 high = Vec2 { x: high.x.max(end.x), y: high.y.max(end.y) };
319 let start = polygon[index];
320 low = Vec2 { x: low.x.min(start.x), y: low.y.min(start.y) };
321 high = Vec2 { x: high.x.max(start.x), y: high.y.max(start.y) };
322 }
323 level.push(u32::try_from(nodes.len()).ok()?);
324 nodes.push(ChordNode {
325 low,
326 high,
327 loop_index,
328 first: first as u32,
329 last: last as u32,
330 children: None,
331 });
332 }
333 while level.len() > 1 {
334 let mut next = Vec::with_capacity(level.len() / 2 + 1);
335 for pair in level.chunks(2) {
336 let &[left, right] = pair else {
337 next.push(pair[0]);
338 continue;
339 };
340 let (a, b) = (nodes[left as usize], nodes[right as usize]);
341 next.push(u32::try_from(nodes.len()).ok()?);
342 nodes.push(ChordNode {
343 low: Vec2 { x: a.low.x.min(b.low.x), y: a.low.y.min(b.low.y) },
344 high: Vec2 { x: a.high.x.max(b.high.x), y: a.high.y.max(b.high.y) },
345 loop_index,
346 first: a.first,
347 last: b.last,
348 children: Some((left, right)),
349 });
350 }
351 level = next;
352 }
353 roots.push(level[0]);
354 }
355 if roots.is_empty() {
356 return None;
357 }
358 Some(ChordIndex {
359 nodes,
360 roots,
361 slack: 1e-12 * (1.0 + largest),
362 })
363 }
364
365 fn slack_at(&self, point: Vec2) -> f64 {
368 self.slack + 1e-12 * point.x.abs().max(point.y.abs())
369 }
370
371 fn box_distance(node: &ChordNode, point: Vec2) -> f64 {
372 let dx = (node.low.x - point.x).max(point.x - node.high.x).max(0.0);
373 let dy = (node.low.y - point.y).max(point.y - node.high.y).max(0.0);
374 (dx * dx + dy * dy).sqrt()
375 }
376
377 fn nearest<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2) -> Option<(usize, usize, f64)> {
381 let slack = self.slack_at(point);
382 let mut best: Option<(f64, u32, u32)> = None;
383 let mut stack: Vec<(u32, f64)> = Vec::with_capacity(64);
384 for &root in &self.roots {
385 stack.push((root, Self::box_distance(&self.nodes[root as usize], point)));
386 }
387 while let Some((node_index, bound)) = stack.pop() {
388 if best.is_some_and(|(distance, _, _)| bound > distance + slack + 1e-12 * distance) {
389 continue;
390 }
391 let node = self.nodes[node_index as usize];
392 match node.children {
393 None => {
394 let polygon = loops.polygon(node.loop_index as usize);
395 for index in node.first..node.last {
396 let start = polygon[index as usize];
397 let end = polygon[(index as usize + 1) % polygon.len()];
398 let distance = point_segment_distance(point, start, end);
399 let better = best.is_none_or(|(least, loop_index, chord_index)| {
400 distance < least
401 || (distance == least && (node.loop_index, index) < (loop_index, chord_index))
402 });
403 if better {
404 best = Some((distance, node.loop_index, index));
405 }
406 }
407 }
408 Some((left, right)) => {
409 let left_bound = Self::box_distance(&self.nodes[left as usize], point);
410 let right_bound = Self::box_distance(&self.nodes[right as usize], point);
411 if left_bound <= right_bound {
413 stack.push((right, right_bound));
414 stack.push((left, left_bound));
415 } else {
416 stack.push((left, left_bound));
417 stack.push((right, right_bound));
418 }
419 }
420 }
421 }
422 best.map(|(distance, loop_index, chord_index)| {
423 (loop_index as usize, chord_index as usize, distance)
424 })
425 }
426
427 fn any_within<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, tolerance: f64) -> bool {
430 let reach = tolerance + self.slack_at(point) + 1e-12 * tolerance.abs();
431 let mut stack: Vec<u32> = self.roots.clone();
432 while let Some(node_index) = stack.pop() {
433 let node = self.nodes[node_index as usize];
434 if Self::box_distance(&node, point) > reach {
435 continue;
436 }
437 match node.children {
438 None => {
439 let polygon = loops.polygon(node.loop_index as usize);
440 for index in node.first as usize..node.last as usize {
441 let (start, end) = (polygon[index], polygon[(index + 1) % polygon.len()]);
442 if point_segment_distance(point, start, end) <= tolerance {
443 return true;
444 }
445 }
446 }
447 Some((left, right)) => {
448 stack.push(right);
449 stack.push(left);
450 }
451 }
452 }
453 false
454 }
455
456 fn flip_crossings<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, odd: &mut [bool]) {
459 let slack = self.slack_at(point);
460 let mut stack: Vec<u32> = self.roots.clone();
461 while let Some(node_index) = stack.pop() {
462 let node = self.nodes[node_index as usize];
463 if !(node.low.y <= point.y && node.high.y > point.y) || node.high.x + slack < point.x {
464 continue;
465 }
466 match node.children {
467 None => {
468 let polygon = loops.polygon(node.loop_index as usize);
469 for index in node.first as usize..node.last as usize {
470 let a = polygon[index];
471 let b = polygon[(index + 1) % polygon.len()];
472 if crate::polygon::crosses_ray([point.x, point.y], [a.x, a.y], [b.x, b.y]) {
473 let parity = &mut odd[node.loop_index as usize];
474 *parity = !*parity;
475 }
476 }
477 }
478 Some((left, right)) => {
479 stack.push(right);
480 stack.push(left);
481 }
482 }
483 }
484 }
485}
486
487#[derive(Clone, Copy, PartialEq, Eq)]
490enum ChordScan {
491 Auto,
493 Indexed,
495 Linear,
497}
498
499impl ChordScan {
500 fn indexes(self, chords: usize) -> bool {
502 match self {
503 ChordScan::Linear => false,
504 ChordScan::Indexed => true,
505 ChordScan::Auto => chords >= CHORD_INDEX_MIN_CHORDS,
506 }
507 }
508}
509
510fn in_index_range(point: Vec2) -> bool {
513 point.x.abs() <= CHORD_INDEX_MAX_COORDINATE && point.y.abs() <= CHORD_INDEX_MAX_COORDINATE
514}
515
516fn linear_scan(
519 generic: &GenericPrep,
520 point: Vec2,
521 tolerance: f64,
522) -> (usize, bool, Option<(usize, usize, f64)>) {
523 let mut crossings = 0;
524 let mut boundary = false;
525 let mut nearest: Option<(usize, usize, f64)> = None;
528 let fused = fused_scan_enabled();
529 for (loop_index, (samples, chords)) in generic.loops.iter().zip(&generic.segments).enumerate() {
530 let polygon = &samples.polygon;
531 if fused {
532 let mut on_boundary = false;
535 for index in 0..polygon.len() {
536 let distance = point_segment_distance(point, polygon[index], polygon[(index + 1) % polygon.len()]);
537 if distance <= tolerance {
538 on_boundary = true;
539 }
540 if index < chords.len()
541 && nearest
542 .as_ref()
543 .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
544 {
545 nearest = Some((loop_index, index, distance));
546 }
547 }
548 if on_boundary {
549 boundary = true;
550 } else if polygon_parity_inside(point, polygon) {
551 crossings += 1;
552 }
553 continue;
554 }
555 match point_in_polygon(point, polygon, tolerance) {
556 PolygonClass::Boundary => boundary = true,
557 PolygonClass::Inside => crossings += 1,
558 PolygonClass::Outside => {}
559 }
560 for index in 0..chords.len() {
561 let start = polygon[index];
562 let end = polygon[(index + 1) % polygon.len()];
563 let distance = point_segment_distance(point, start, end);
564 if nearest
565 .as_ref()
566 .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
567 {
568 nearest = Some((loop_index, index, distance));
569 }
570 }
571 }
572 (crossings, boundary, nearest)
573}
574
575fn fused_scan_enabled() -> bool {
582 switch!("BREP_CONTAINMENT_FUSED_SCAN", true)
583}
584
585
586fn generic_scan(
590 generic: &GenericPrep,
591 point: Vec2,
592 tolerance: f64,
593 scan: ChordScan,
594) -> (usize, bool, Option<(usize, usize, f64)>) {
595 if scan.indexes(generic.chord_count) && in_index_range(point) {
596 if let Some(index) = generic.index.get_or_init(|| {
597 let started = containment_profile_started();
598 let built = ChordIndex::build(generic.loops.as_slice());
599 let ms = containment_elapsed_ms(started);
600 containment_profile(|p| {
601 p.index_builds += 1;
602 p.index_ms += ms;
603 });
604 built
605 }) {
606 let loops = generic.loops.as_slice();
607 let nearest = index.nearest(loops, point);
608 let boundary = nearest.is_some_and(|(_, _, distance)| distance <= tolerance);
609 let crossings = if boundary {
610 0
611 } else {
612 let mut odd = vec![false; loops.len()];
613 index.flip_crossings(loops, point, &mut odd);
614 odd.into_iter().filter(|&parity| parity).count()
615 };
616 return (crossings, boundary, nearest);
617 }
618 }
619 linear_scan(generic, point, tolerance)
620}
621
622pub struct PreparedFace {
629 seam_band: std::cell::OnceCell<Result<SeamBandPrep, String>>,
630 sphere_cap: std::cell::OnceCell<Result<Option<SphereCapPrep>, String>>,
631 horizon: std::cell::OnceCell<Result<Option<HorizonPrep>, String>>,
632 rim_strip: std::cell::OnceCell<Result<Option<RimStripPrep>, String>>,
633 generic: std::cell::OnceCell<Result<GenericPrep, String>>,
634 sphere_region: std::cell::OnceCell<Result<crate::sphere_chart::SphericalRegion, String>>,
636 sphere_region_reduced: std::cell::OnceCell<Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String>>,
640 loop_samples: std::cell::RefCell<Vec<Option<Result<std::rc::Rc<Vec<Vec2>>, String>>>>,
645}
646
647impl PreparedFace {
648 fn new() -> Self {
649 Self {
650 seam_band: std::cell::OnceCell::new(),
651 sphere_cap: std::cell::OnceCell::new(),
652 horizon: std::cell::OnceCell::new(),
653 rim_strip: std::cell::OnceCell::new(),
654 generic: std::cell::OnceCell::new(),
655 sphere_region: std::cell::OnceCell::new(),
656 sphere_region_reduced: std::cell::OnceCell::new(),
657 loop_samples: std::cell::RefCell::new(Vec::new()),
658 }
659 }
660}
661
662fn loop_samples(prepared: &PreparedFace, face: &FaceRecord, loop_index: usize) -> Result<std::rc::Rc<Vec<Vec2>>, String> {
672 if let Some(Some(sampled)) = prepared.loop_samples.borrow().get(loop_index) {
673 return sampled.clone();
674 }
675 let sampled = shared_loop_samples(&face.loops[loop_index]);
676 let mut cells = prepared.loop_samples.borrow_mut();
677 if cells.len() < face.loops.len() {
678 cells.resize(face.loops.len(), None);
679 }
680 cells[loop_index] = Some(sampled.clone());
681 sampled
682}
683
684pub const LOOP_SAMPLE_MEMO_SWITCH: &str = "BREP_LOOP_SAMPLE_MEMO";
688
689struct LoopSampleMemo {
698 entries: Vec<(u64, Vec<f64>, std::rc::Rc<Vec<Vec2>>)>,
700 points: usize,
702}
703
704const LOOP_SAMPLE_MEMO_ENTRIES: usize = 256;
706const LOOP_SAMPLE_MEMO_POINTS: usize = 1 << 21;
709
710thread_local! {
711 static LOOP_SAMPLE_MEMO: std::cell::RefCell<LoopSampleMemo> =
712 const { std::cell::RefCell::new(LoopSampleMemo { entries: Vec::new(), points: 0 }) };
713}
714
715fn walk_loop_signature<F: FnMut(f64) -> bool>(record: &LoopRecord, visit: &mut F) -> bool {
719 if !visit(record.coedges.len() as f64) {
720 return false;
721 }
722 for coedge in &record.coedges {
723 let curve = &coedge.pcurve;
724 if !(visit(curve.degree as f64) && visit(curve.knots.len() as f64)) {
725 return false;
726 }
727 if !(curve.knots.iter().all(|&knot| visit(knot)) && visit(curve.control_points.len() as f64)) {
728 return false;
729 }
730 if !curve.control_points.iter().all(|p| visit(p.x) && visit(p.y) && visit(p.z) && visit(p.w)) {
731 return false;
732 }
733 }
734 true
735}
736
737fn sample_loop(record: &LoopRecord) -> Result<Vec<Vec2>, String> {
740 let mut points: Vec<Vec2> = Vec::new();
741 for coedge in &record.coedges {
742 let curve = &coedge.pcurve;
743 let [start, end] = curve.domain()?;
744 let sample_count = trim_sample_count(curve);
745 for index in 0..sample_count {
746 let parameter = trim_station(start, end, index, sample_count);
747 let evaluated = curve.evaluate(parameter)?;
748 points.push(Vec2 {
749 x: evaluated.x,
750 y: evaluated.y,
751 });
752 }
753 }
754 Ok(points)
755}
756
757fn shared_loop_samples(record: &LoopRecord) -> Result<std::rc::Rc<Vec<Vec2>>, String> {
761 if !switch!(LOOP_SAMPLE_MEMO_SWITCH, true) {
762 return sample_loop(record).map(std::rc::Rc::new);
763 }
764 use std::hash::Hasher;
765 let mut hasher = rustc_hash::FxHasher::default();
766 walk_loop_signature(record, &mut |value: f64| {
767 hasher.write_u64(value.to_bits());
768 true
769 });
770 let hash = hasher.finish();
771 let found = LOOP_SAMPLE_MEMO.with(|memo| {
772 let mut memo = memo.borrow_mut();
773 let at = memo.entries.iter().position(|(entry_hash, signature, _)| {
774 if *entry_hash != hash {
775 return false;
776 }
777 let mut index = 0;
778 let walked = walk_loop_signature(record, &mut |value: f64| {
779 let same = signature
780 .get(index)
781 .is_some_and(|stored| stored.to_bits() == value.to_bits() && !value.is_nan());
782 index += 1;
783 same
784 });
785 walked && index == signature.len()
786 })?;
787 let entry = memo.entries.remove(at);
788 let samples = entry.2.clone();
789 memo.entries.insert(0, entry);
790 Some(samples)
791 });
792 if let Some(samples) = found {
793 for coedge in &record.coedges {
800 coedge.pcurve.domain()?;
801 }
802 containment_profile(|p| p.loop_sample_hits += 1);
803 return Ok(samples);
804 }
805 let samples = std::rc::Rc::new(sample_loop(record)?);
806 containment_profile(|p| p.loop_sample_misses += 1);
807 if samples.len() > LOOP_SAMPLE_MEMO_POINTS {
808 return Ok(samples);
809 }
810 let mut signature = Vec::new();
811 walk_loop_signature(record, &mut |value: f64| {
812 signature.push(value);
813 true
814 });
815 LOOP_SAMPLE_MEMO.with(|memo| {
816 let mut memo = memo.borrow_mut();
817 memo.points += samples.len();
818 memo.entries.insert(0, (hash, signature, samples.clone()));
819 while memo.entries.len() > LOOP_SAMPLE_MEMO_ENTRIES || memo.points > LOOP_SAMPLE_MEMO_POINTS {
820 let Some((_, _, dropped)) = memo.entries.pop() else { break };
821 memo.points -= dropped.len();
822 }
823 });
824 Ok(samples)
825}
826
827#[derive(Default, Clone, Copy)]
837struct ContainmentProfile {
838 enabled: bool,
839 cache_misses: u64,
840 seam_band_preps: u64,
841 seam_band_ms: f64,
842 sphere_cap_preps: u64,
843 sphere_cap_ms: f64,
844 horizon_preps: u64,
845 horizon_ms: f64,
846 rim_strip_preps: u64,
847 rim_strip_ms: f64,
848 generic_preps: u64,
849 generic_ms: f64,
850 generic_chords: u64,
851 index_builds: u64,
852 index_ms: f64,
853 region_builds: u64,
854 region_evaluate_ms: f64,
855 region_canonical_ms: f64,
856 region_segments_ms: f64,
857 loop_sample_hits: u64,
858 loop_sample_misses: u64,
859}
860
861thread_local! {
862 static CONTAINMENT_PROFILE: std::cell::Cell<ContainmentProfile> =
863 const { std::cell::Cell::new(ContainmentProfile {
864 enabled: false, cache_misses: 0, seam_band_preps: 0, seam_band_ms: 0.0,
865 sphere_cap_preps: 0, sphere_cap_ms: 0.0, horizon_preps: 0, horizon_ms: 0.0,
866 rim_strip_preps: 0, rim_strip_ms: 0.0, generic_preps: 0, generic_ms: 0.0,
867 generic_chords: 0, index_builds: 0, index_ms: 0.0, region_builds: 0,
868 region_evaluate_ms: 0.0, region_canonical_ms: 0.0, region_segments_ms: 0.0,
869 loop_sample_hits: 0, loop_sample_misses: 0,
870 }) };
871}
872
873impl crate::profile::Counters for ContainmentProfile {
874 fn armed(&self) -> bool {
875 self.enabled
876 }
877}
878
879fn containment_profile(update: impl FnOnce(&mut ContainmentProfile)) {
880 crate::profile::update(&CONTAINMENT_PROFILE, update)
881}
882
883fn containment_profile_started() -> Option<web_time::Instant> {
884 crate::profile::started(&CONTAINMENT_PROFILE)
885}
886
887use crate::profile::elapsed_ms as containment_elapsed_ms;
888
889pub fn containment_profile_begin() {
891 let enabled = crate::profile::profile_enabled();
892 CONTAINMENT_PROFILE.with(|cell| {
893 cell.set(ContainmentProfile {
894 enabled,
895 ..ContainmentProfile::default()
896 })
897 });
898}
899
900pub fn containment_profile_report(label: &str) {
903 let p = CONTAINMENT_PROFILE.with(|cell| cell.get());
904 if !p.enabled {
905 return;
906 }
907 profile_line!(
908 "containment.profile {label} cache_misses={} seam_band: preps={} ms={:.2} sphere_cap: preps={} ms={:.2} horizon: preps={} ms={:.2} rim_strip: preps={} ms={:.2} generic: preps={} ms={:.2} chords={} index: builds={} ms={:.2} region: builds={} evaluate_ms={:.2} canonical_ms={:.2} segments_ms={:.2} loop_samples: memo_hits={} memo_misses={}",
909 p.cache_misses, p.seam_band_preps, p.seam_band_ms, p.sphere_cap_preps, p.sphere_cap_ms,
910 p.horizon_preps, p.horizon_ms, p.rim_strip_preps, p.rim_strip_ms, p.generic_preps,
911 p.generic_ms, p.generic_chords, p.index_builds, p.index_ms, p.region_builds,
912 p.region_evaluate_ms, p.region_canonical_ms, p.region_segments_ms,
913 p.loop_sample_hits, p.loop_sample_misses,
914 );
915 CONTAINMENT_PROFILE.with(|cell| cell.set(ContainmentProfile::default()));
916}
917
918fn timed_lane<'a, T>(
921 cell: &'a std::cell::OnceCell<Result<T, String>>,
922 build: impl FnOnce() -> Result<T, String>,
923 record: fn(&mut ContainmentProfile, f64),
924) -> Result<&'a T, String> {
925 lane(cell, || {
926 let started = containment_profile_started();
927 let built = build();
928 let ms = containment_elapsed_ms(started);
929 containment_profile(|p| record(p, ms));
930 built
931 })
932}
933
934fn lane<'a, T>(
935 cell: &'a std::cell::OnceCell<Result<T, String>>,
936 build: impl FnOnce() -> Result<T, String>,
937) -> Result<&'a T, String> {
938 match cell.get_or_init(build) {
939 Ok(value) => Ok(value),
940 Err(error) => Err(error.clone()),
941 }
942}
943
944pub struct PreparedFaceCache {
962 entries: Vec<(u64, Vec<f64>, std::rc::Rc<PreparedFace>)>,
963}
964
965const PREPARED_FACE_CACHE_ENTRIES: usize = 64;
966
967thread_local! {
968 static PREPARED_FACES: std::cell::RefCell<PreparedFaceCache> = const {
969 std::cell::RefCell::new(PreparedFaceCache {
970 entries: Vec::new(),
971 })
972 };
973}
974
975fn coedge_slots(face: &FaceRecord) -> Vec<usize> {
989 let ids: Vec<u64> = face.loops.iter().flat_map(|record| record.coedges.iter().map(|coedge| coedge.edge_id)).collect();
990 ids.iter().enumerate().map(|(at, id)| ids[..at].iter().position(|earlier| earlier == id).unwrap_or(at)).collect()
991}
992
993fn walk_face_signature<F: FnMut(f64) -> bool>(face: &FaceRecord, switches: f64, visit: &mut F) -> bool {
994 let slots = coedge_slots(face);
995 let mut flat = 0usize;
996 let surface = &face.surface;
997 let point = |visit: &mut F, p: &crate::Vec4| visit(p.x) && visit(p.y) && visit(p.z) && visit(p.w);
998 if !(visit(switches)
999 && visit(if face.same_sense { 1.0 } else { 0.0 })
1000 && visit(surface.degree_u as f64)
1001 && visit(surface.degree_v as f64)
1002 && visit(surface.knots_u.len() as f64))
1003 {
1004 return false;
1005 }
1006 if !(surface.knots_u.iter().all(|&knot| visit(knot)) && visit(surface.knots_v.len() as f64)) {
1007 return false;
1008 }
1009 if !(surface.knots_v.iter().all(|&knot| visit(knot)) && visit(surface.control_points.len() as f64)) {
1010 return false;
1011 }
1012 for row in &surface.control_points {
1013 if !(visit(row.len() as f64) && row.iter().all(|p| point(visit, p))) {
1014 return false;
1015 }
1016 }
1017 if !visit(face.loops.len() as f64) {
1018 return false;
1019 }
1020 for loop_record in &face.loops {
1021 if !visit(loop_record.coedges.len() as f64) {
1022 return false;
1023 }
1024 for coedge in &loop_record.coedges {
1025 let curve = &coedge.pcurve;
1026 let slot = slots[flat];
1027 flat += 1;
1028 if !(visit(slot as f64)
1029 && visit(if coedge.forward { 1.0 } else { 0.0 })
1030 && visit(curve.degree as f64)
1031 && visit(curve.knots.len() as f64))
1032 {
1033 return false;
1034 }
1035 if !(curve.knots.iter().all(|&knot| visit(knot)) && visit(curve.control_points.len() as f64)) {
1036 return false;
1037 }
1038 if !curve.control_points.iter().all(|p| point(visit, p)) {
1039 return false;
1040 }
1041 }
1042 }
1043 true
1044}
1045
1046fn face_key_hash(face: &FaceRecord, switches: f64) -> u64 {
1051 use std::hash::Hasher;
1052 let slots = coedge_slots(face);
1053 let mut flat = 0usize;
1054 let mut hasher = rustc_hash::FxHasher::default();
1055 let mut write = |value: f64| hasher.write_u64(value.to_bits());
1056 let surface = &face.surface;
1057 write(switches);
1058 write(if face.same_sense { 1.0 } else { 0.0 });
1059 write(surface.degree_u as f64);
1060 write(surface.degree_v as f64);
1061 write(surface.knots_u.len() as f64);
1062 write(surface.knots_v.len() as f64);
1063 write(surface.control_points.len() as f64);
1064 let corners = [surface.control_points.first().and_then(|row| row.first()), surface.control_points.last().and_then(|row| row.last())];
1065 for p in corners.into_iter().flatten() {
1066 [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
1067 }
1068 write(face.loops.len() as f64);
1069 for loop_record in &face.loops {
1070 write(loop_record.coedges.len() as f64);
1071 for coedge in &loop_record.coedges {
1072 let curve = &coedge.pcurve;
1073 write(slots[flat] as f64);
1074 flat += 1;
1075 write(if coedge.forward { 1.0 } else { 0.0 });
1076 write(curve.degree as f64);
1077 write(curve.knots.len() as f64);
1078 write(curve.control_points.len() as f64);
1079 for knot in [curve.knots.first(), curve.knots.last()].into_iter().flatten() {
1080 write(*knot);
1081 }
1082 for p in [curve.control_points.first(), curve.control_points.last()].into_iter().flatten() {
1083 [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
1084 }
1085 }
1086 }
1087 hasher.finish()
1088}
1089
1090fn cached_entry(
1092 entries: &[(u64, Vec<f64>, std::rc::Rc<PreparedFace>)],
1093 face: &FaceRecord,
1094 switches: f64,
1095 hash: u64,
1096) -> Option<usize> {
1097 entries.iter().position(|(entry_hash, signature, _)| {
1098 if *entry_hash != hash {
1099 return false;
1100 }
1101 let mut at = 0;
1102 let walked = walk_face_signature(face, switches, &mut |value: f64| {
1103 let same = signature
1104 .get(at)
1105 .is_some_and(|stored| stored.to_bits() == value.to_bits() && !value.is_nan());
1106 at += 1;
1107 same
1108 });
1109 walked && at == signature.len()
1110 })
1111}
1112
1113pub fn forget_prepared_faces() {
1117 PREPARED_FACES.with(|cache| cache.borrow_mut().entries.clear());
1118 LOOP_SAMPLE_MEMO.with(|memo| {
1119 let mut memo = memo.borrow_mut();
1120 memo.entries.clear();
1121 memo.points = 0;
1122 });
1123}
1124
1125
1126fn cached_prepared_face(face: &FaceRecord) -> Option<std::rc::Rc<PreparedFace>> {
1130 PREPARED_FACES.with(|cache| {
1131 let PreparedFaceCache { entries } = &*cache.borrow();
1132 let switches = lane_switches();
1133 let hash = face_key_hash(face, switches);
1134 cached_entry(entries, face, switches, hash).map(|index| entries[index].2.clone())
1135 })
1136}
1137
1138pub fn prepared_face(face: &FaceRecord) -> std::rc::Rc<PreparedFace> {
1139 PREPARED_FACES.with(|cache| {
1140 let PreparedFaceCache { entries } = &mut *cache.borrow_mut();
1141 let switches = lane_switches();
1142 let hash = face_key_hash(face, switches);
1143 if let Some(index) = cached_entry(entries, face, switches, hash) {
1144 if index != 0 {
1145 let entry = entries.remove(index);
1146 entries.insert(0, entry);
1147 }
1148 return entries[0].2.clone();
1149 }
1150 let mut signature = Vec::new();
1151 walk_face_signature(face, switches, &mut |value: f64| {
1152 signature.push(value);
1153 true
1154 });
1155 let prepared = std::rc::Rc::new(PreparedFace::new());
1156 entries.insert(0, (hash, signature, prepared.clone()));
1157 entries.truncate(PREPARED_FACE_CACHE_ENTRIES);
1158 containment_profile(|p| p.cache_misses += 1);
1159 prepared
1160 })
1161}
1162
1163fn prepare_seam_band(face: &FaceRecord) -> Result<SeamBandPrep, String> {
1172 if face.surface.closed_directions()? != (true, true) {
1173 return Ok(SeamBandPrep::NotApplicable);
1174 }
1175 let [u0, u1] = face.surface.domain_u()?;
1176 let [v0, v1] = face.surface.domain_v()?;
1177 if crate::topology::doubly_periodic_has_only_collapsed_loops(face)? {
1178 return Ok(SeamBandPrep::AlwaysInside);
1179 }
1180 let u_span = (u1 - u0).abs().max(1e-30);
1181 let v_span = (v1 - v0).abs().max(1e-30);
1182 let mut loops_uv: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
1183 let mut retained: Vec<usize> = Vec::with_capacity(face.loops.len());
1187 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1188 let mut points: Vec<[f64; 2]> = Vec::new();
1189 for coedge in &loop_record.coedges {
1190 let [d0, d1] = coedge.pcurve.domain()?;
1191 let samples = 24;
1192 for k in 0..=samples {
1193 let t = trim_station(d0, d1, k, samples);
1194 let p = coedge.pcurve.evaluate(t)?;
1195 points.push([p.x, p.y]);
1196 }
1197 }
1198 let (mut umin, mut umax, mut vmin, mut vmax) = (
1199 f64::INFINITY,
1200 f64::NEG_INFINITY,
1201 f64::INFINITY,
1202 f64::NEG_INFINITY,
1203 );
1204 for p in &points {
1205 umin = umin.min(p[0]);
1206 umax = umax.max(p[0]);
1207 vmin = vmin.min(p[1]);
1208 vmax = vmax.max(p[1]);
1209 }
1210 if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
1230 continue;
1231 }
1232 retained.push(loop_index);
1233 loops_uv.push(points);
1234 }
1235 if loops_uv.len() == 1 && switch!(SEAM_BAND_MERGED_SWITCH, true) {
1246 let coedges = &face.loops[retained[0]].coedges;
1247 let offsets = crate::topology::loop_seam_offsets(coedges, true, true, u_span, v_span)?;
1248 if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
1249 let mut polygon: Vec<Vec2> = Vec::new();
1250 for (coedge_index, coedge) in coedges.iter().enumerate() {
1251 let [d0, d1] = coedge.pcurve.domain()?;
1252 let samples = 24;
1253 for k in 0..samples {
1254 let t = trim_station(d0, d1, k, samples);
1255 let p = coedge.pcurve.evaluate(t)?;
1256 polygon.push(Vec2 {
1257 x: p.x + offsets[coedge_index][0],
1258 y: p.y + offsets[coedge_index][1],
1259 });
1260 }
1261 }
1262 return Ok(SeamBandPrep::Merged { polygon, u_span, v_span });
1263 }
1264 }
1265 if loops_uv.len() != 2 {
1266 return Ok(SeamBandPrep::Declined);
1267 }
1268 if let Some(band) = crate::topology::analyze_doubly_periodic_seam_band(
1269 &loops_uv,
1270 [u0, u1, v0, v1],
1271 face.same_sense,
1272 ) {
1273 let polygon: Vec<Vec2> =
1274 crate::topology::seam_band_uv_polygon(&loops_uv, [u0, u1, v0, v1], &band)
1275 .into_iter()
1276 .map(|p| Vec2 { x: p[0], y: p[1] })
1277 .collect();
1278 return Ok(SeamBandPrep::Analyzed { polygon });
1279 }
1280 for p_is_u in [true, false] {
1287 let (period, q_extent) = if p_is_u {
1288 (u1 - u0, v_span)
1289 } else {
1290 (v1 - v0, u_span)
1291 };
1292 if !(period > 0.0) {
1293 continue;
1294 }
1295 let coord = |p: &[f64; 2]| if p_is_u { (p[0], p[1]) } else { (p[1], p[0]) };
1296 let mut rings = Vec::with_capacity(2);
1297 for points in &loops_uv {
1298 let (mut pmin, mut pmax, mut qmin, mut qmax) = (
1299 f64::INFINITY,
1300 f64::NEG_INFINITY,
1301 f64::INFINITY,
1302 f64::NEG_INFINITY,
1303 );
1304 for p in points {
1305 let (periodic, cross) = coord(p);
1306 pmin = pmin.min(periodic);
1307 pmax = pmax.max(periodic);
1308 qmin = qmin.min(cross);
1309 qmax = qmax.max(cross);
1310 }
1311 if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
1312 rings.clear();
1313 break;
1314 }
1315 let mut net = 0.0;
1316 for pair in points.windows(2) {
1317 let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
1318 if delta > 0.5 * period {
1319 delta -= period;
1320 } else if delta < -0.5 * period {
1321 delta += period;
1322 }
1323 net += delta;
1324 }
1325 let direction = if net > 0.25 * period {
1326 1
1327 } else if net < -0.25 * period {
1328 -1
1329 } else {
1330 0
1331 };
1332 rings.push((0.5 * (qmin + qmax), direction));
1333 }
1334 if rings.len() != 2 {
1335 continue;
1336 }
1337 rings.sort_by(|a, b| a.0.total_cmp(&b.0));
1338 let [(q_lo, lower_direction), (q_hi, upper_direction)] = rings.as_slice() else {
1339 unreachable!()
1340 };
1341 let inconclusive =
1342 *lower_direction == 0 || *upper_direction == 0 || lower_direction == upper_direction;
1343 let between_is_ccw_uv = if p_is_u {
1344 *lower_direction > 0
1345 } else {
1346 *lower_direction < 0
1347 };
1348 let complement = !inconclusive && between_is_ccw_uv != face.same_sense;
1349 return Ok(SeamBandPrep::Rings {
1350 p_is_u,
1351 q_lo: *q_lo,
1352 q_hi: *q_hi,
1353 complement,
1354 });
1355 }
1356 Ok(SeamBandPrep::Declined)
1357}
1358
1359fn seam_band_point_in_face(
1360 prepared: &SeamBandPrep,
1361 point: Vec2,
1362 tolerance: f64,
1363) -> Option<PolygonClass> {
1364 match prepared {
1365 SeamBandPrep::NotApplicable | SeamBandPrep::Declined => None,
1366 SeamBandPrep::AlwaysInside => Some(PolygonClass::Inside),
1367 SeamBandPrep::Merged { polygon, u_span, v_span } => {
1368 let mut best = PolygonClass::Outside;
1369 'images: for du in [-1.0, 0.0, 1.0] {
1370 for dv in [-1.0, 0.0, 1.0] {
1371 let image = Vec2 {
1372 x: point.x + du * u_span,
1373 y: point.y + dv * v_span,
1374 };
1375 match point_in_polygon(image, polygon, tolerance) {
1376 PolygonClass::Boundary => {
1377 best = PolygonClass::Boundary;
1378 break 'images;
1379 }
1380 PolygonClass::Inside => best = PolygonClass::Inside,
1381 PolygonClass::Outside => {}
1382 }
1383 }
1384 }
1385 Some(best)
1386 }
1387 SeamBandPrep::Analyzed { polygon } => Some(point_in_polygon(point, polygon, tolerance)),
1388 SeamBandPrep::Rings { p_is_u, q_lo, q_hi, complement } => {
1389 let q = if *p_is_u { point.y } else { point.x };
1390 if (q - q_lo).abs() <= tolerance || (q - q_hi).abs() <= tolerance {
1391 return Some(PolygonClass::Boundary);
1392 }
1393 let between = q > *q_lo && q < *q_hi;
1394 Some(if between != *complement {
1395 PolygonClass::Inside
1396 } else {
1397 PolygonClass::Outside
1398 })
1399 }
1400 }
1401}
1402
1403fn prepare_wrapped_horizon(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<HorizonPrep>, String> {
1419 if face.surface.closed_directions()? != (true, false) || face.loops.is_empty() {
1420 return Ok(None);
1421 }
1422 if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
1423 return Ok(None);
1424 }
1425 if face.loops.len() <= 2 && !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
1436 return Ok(None);
1437 }
1438 let [u0, u1] = face.surface.domain_u()?;
1439 let u_period = u1 - u0;
1440 if u_period <= 0.0 {
1441 return Ok(None);
1442 }
1443 let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1444 let mut loops: Vec<Vec<Vec2>> = Vec::new();
1445 let mut straddling = false;
1446 for loop_index in 0..face.loops.len() {
1447 let points = loop_samples(prepared, face, loop_index)?;
1448 if points.len() < 3 {
1449 continue;
1450 }
1451 let mut unwrapped = Vec::with_capacity(points.len());
1455 let mut jumps = 0usize;
1456 let mut cursor = points[0];
1457 unwrapped.push(cursor);
1458 for pair in points.windows(2) {
1459 let mut du = pair[1].x - pair[0].x;
1460 let folded = du - u_period * (du / u_period).round();
1461 if (du - folded).abs() > 0.25 * u_period {
1462 jumps += 1;
1463 }
1464 du = folded;
1465 cursor = Vec2 {
1466 x: cursor.x + du,
1467 y: pair[1].y,
1468 };
1469 unwrapped.push(cursor);
1470 }
1471 let closure = (unwrapped[0].x - unwrapped[unwrapped.len() - 1].x).abs();
1472 if closure > 0.25 * u_period {
1473 if debug {
1474 eprintln!(
1475 "horizon: face {} loop winds the period (closure {closure:.3}) — bail",
1476 face.id
1477 );
1478 }
1479 return Ok(None); }
1481 if jumps > 0 {
1482 straddling = true;
1483 }
1484 loops.push(unwrapped);
1485 }
1486 if !straddling || loops.is_empty() {
1487 return Ok(None);
1488 }
1489 Ok(Some(HorizonPrep {
1490 loops,
1491 u_period,
1492 index: std::cell::OnceCell::new(),
1493 }))
1494}
1495
1496fn wrapped_horizon_point_in_face(
1497 face: &FaceRecord,
1498 prepared: &HorizonPrep,
1499 point: Vec2,
1500 tolerance: f64,
1501 scan: ChordScan,
1502) -> Option<PolygonClass> {
1503 let HorizonPrep { loops, u_period, index } = prepared;
1504 let u_period = *u_period;
1505 let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1506 if !horizon_cross_frame() {
1521 let mut best: Option<PolygonClass> = None;
1522 for shift in [-u_period, 0.0, u_period] {
1523 let image = Vec2 {
1524 x: point.x + shift,
1525 y: point.y,
1526 };
1527 let mut crossings = 0usize;
1528 for polygon in loops {
1529 match point_in_polygon(image, polygon, tolerance) {
1530 PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1531 PolygonClass::Inside => crossings += 1,
1532 PolygonClass::Outside => {}
1533 }
1534 }
1535 if crossings % 2 == 1 {
1536 best = Some(PolygonClass::Inside);
1537 } else if best.is_none() {
1538 best = Some(PolygonClass::Outside);
1539 }
1540 }
1541 if debug {
1542 eprintln!(
1543 "horizon: face {} loops={} straddling (legacy per-image) -> {:?}",
1544 face.id,
1545 loops.len(),
1546 best
1547 );
1548 }
1549 return best;
1550 }
1551 let images = [-u_period, 0.0, u_period].map(|shift| Vec2 {
1552 x: point.x + shift,
1553 y: point.y,
1554 });
1555 let chords: usize = loops.iter().map(Vec::len).sum();
1556 let indexed = (scan.indexes(chords) && images.iter().all(|image| in_index_range(*image)))
1557 .then(|| index.get_or_init(|| ChordIndex::build(loops.as_slice())).as_ref())
1558 .flatten();
1559 let mut crossings = 0usize;
1560 if let Some(index) = indexed {
1561 let loops = loops.as_slice();
1565 if images.iter().any(|image| index.any_within(loops, *image, tolerance)) {
1566 return Some(PolygonClass::Boundary);
1567 }
1568 let mut odd = vec![false; loops.len()];
1569 for image in images {
1570 index.flip_crossings(loops, image, &mut odd);
1571 }
1572 crossings = odd.into_iter().filter(|&parity| parity).count();
1573 } else {
1574 for polygon in loops {
1575 let mut image_hits = 0usize;
1576 for image in images {
1577 match point_in_polygon(image, polygon, tolerance) {
1578 PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1579 PolygonClass::Inside => image_hits += 1,
1580 PolygonClass::Outside => {}
1581 }
1582 }
1583 crossings += image_hits % 2;
1584 }
1585 }
1586 let class = if crossings % 2 == 1 {
1587 PolygonClass::Inside
1588 } else {
1589 PolygonClass::Outside
1590 };
1591 if debug {
1592 eprintln!(
1593 "horizon: face {} loops={} straddling -> {:?}",
1594 face.id,
1595 loops.len(),
1596 class
1597 );
1598 }
1599 Some(class)
1600}
1601
1602fn prepare_winding_sphere_cap(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<SphereCapPrep>, String> {
1607 if !matches!(
1608 face.surface.analytic(),
1609 Some(crate::AnalyticSurface::Sphere { .. })
1610 ) || face.surface.closed_directions()? != (true, false)
1611 || face.loops.len() != 2
1612 {
1613 return Ok(None);
1614 }
1615 let [u0, u1] = face.surface.domain_u()?;
1616 let [v0, v1] = face.surface.domain_v()?;
1617 let period = u1 - u0;
1618 let v_span = v1 - v0;
1619 if !(period > 0.0 && v_span > 0.0) {
1620 return Ok(None);
1621 }
1622 struct WindingLoop {
1623 points: Vec<Vec2>,
1624 winding: f64,
1625 vmin: f64,
1626 vmax: f64,
1627 }
1628 let mut loops = Vec::with_capacity(2);
1629 for loop_index in 0..face.loops.len() {
1630 let points = loop_samples(prepared, face, loop_index)?;
1631 if points.len() < 2 {
1632 return Ok(None);
1633 }
1634 let first = points[0];
1635 let mut cursor = first;
1636 let mut unwrapped = vec![cursor];
1637 for next in points.iter().skip(1) {
1638 let du = next.x - cursor.x;
1639 let folded = du - period * (du / period).round();
1640 cursor = Vec2 {
1641 x: cursor.x + folded,
1642 y: next.y,
1643 };
1644 unwrapped.push(cursor);
1645 }
1646 let last_raw = *points.last().unwrap();
1647 let closing_du = first.x - last_raw.x;
1648 let closing_folded = closing_du - period * (closing_du / period).round();
1649 let winding = cursor.x + closing_folded - first.x;
1650 let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1651 for p in &unwrapped {
1652 vmin = vmin.min(p.y);
1653 vmax = vmax.max(p.y);
1654 }
1655 loops.push(WindingLoop {
1656 points: unwrapped,
1657 winding,
1658 vmin,
1659 vmax,
1660 });
1661 }
1662 if loops
1663 .iter()
1664 .any(|loop_data| (loop_data.winding.abs() - period).abs() > 0.05 * period)
1665 || loops[0].winding * loops[1].winding >= 0.0
1666 {
1667 return Ok(None);
1668 }
1669 let flat = |loop_data: &WindingLoop| loop_data.vmax - loop_data.vmin <= 1e-6 * v_span;
1670 let (pole, rim) = match (flat(&loops[0]), flat(&loops[1])) {
1671 (true, false) => (&loops[0], &loops[1]),
1672 (false, true) => (&loops[1], &loops[0]),
1673 _ => return Ok(None),
1674 };
1675 let pole_v = 0.5 * (pole.vmin + pole.vmax);
1676 if (pole_v - v0).abs() > 1e-6 * v_span && (pole_v - v1).abs() > 1e-6 * v_span {
1677 return Ok(None);
1678 }
1679 Ok(Some(SphereCapPrep {
1680 rim: rim.points.clone(),
1681 pole_v,
1682 period,
1683 }))
1684}
1685
1686fn winding_sphere_cap_point_in_face(
1687 prepared: &SphereCapPrep,
1688 point: Vec2,
1689 tolerance: f64,
1690) -> Option<PolygonClass> {
1691 let SphereCapPrep { rim, pole_v, period } = prepared;
1692 let (pole_v, period) = (*pole_v, *period);
1693 let window_start = rim[0].x.min(rim[rim.len() - 1].x);
1694 let query_u = window_start + (point.x - window_start).rem_euclid(period);
1695 let mut crossings = Vec::new();
1696 for pair in rim.windows(2) {
1697 let (a, b) = (pair[0], pair[1]);
1698 if (a.x > query_u) != (b.x > query_u) {
1699 crossings.push(a.y + (query_u - a.x) / (b.x - a.x) * (b.y - a.y));
1700 }
1701 for image in [-period, 0.0, period] {
1702 if point_segment_distance(
1703 Vec2 {
1704 x: point.x + image,
1705 y: point.y,
1706 },
1707 a,
1708 b,
1709 ) <= tolerance
1710 {
1711 return Some(PolygonClass::Boundary);
1712 }
1713 }
1714 }
1715 let rim_v = crossings
1716 .into_iter()
1717 .min_by(|a, b| (a - point.y).abs().total_cmp(&(b - point.y).abs()))?;
1718 let inside = if pole_v < rim_v {
1719 point.y <= rim_v + tolerance
1720 } else {
1721 point.y >= rim_v - tolerance
1722 };
1723 Some(if inside {
1724 PolygonClass::Inside
1725 } else {
1726 PolygonClass::Outside
1727 })
1728}
1729
1730fn prepare_covering_rim_strip(face: &FaceRecord) -> Result<Option<RimStripPrep>, String> {
1762 if face.surface.closed_directions()? != (true, false) || face.loops.len() != 2 {
1763 return Ok(None);
1764 }
1765 if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
1766 return Ok(None);
1767 }
1768 let [u0, u1] = face.surface.domain_u()?;
1769 let [v0, v1] = face.surface.domain_v()?;
1770 let period = u1 - u0;
1771 if !(period > 0.0) {
1772 return Ok(None);
1773 }
1774 let v_span = (v1 - v0).abs().max(1e-30);
1775 struct Rim {
1776 points: Vec<Vec2>,
1777 vmin: f64,
1778 vmax: f64,
1779 ascending: bool,
1780 }
1781 let mut rims: Vec<Rim> = Vec::with_capacity(2);
1782 let mut out_of_domain = false;
1783 for loop_record in &face.loops {
1784 let mut points: Vec<Vec2> = Vec::new();
1785 for coedge in &loop_record.coedges {
1786 let curve = &coedge.pcurve;
1787 let [start, end] = curve.domain()?;
1788 let sample_count = trim_sample_count(curve);
1789 for index in 0..=sample_count {
1790 let parameter = trim_station(start, end, index, sample_count);
1791 let evaluated = curve.evaluate(parameter)?;
1792 points.push(Vec2 {
1793 x: evaluated.x,
1794 y: evaluated.y,
1795 });
1796 }
1797 }
1798 if points.len() < 3 {
1799 return Ok(None);
1800 }
1801 for p in &points {
1804 if p.x < u0 - 1e-3 * period || p.x > u1 + 1e-3 * period {
1805 out_of_domain = true;
1806 }
1807 }
1808 let mut unwrapped: Vec<Vec2> = Vec::with_capacity(points.len());
1812 let mut cursor = points[0];
1813 unwrapped.push(cursor);
1814 for pair in points.windows(2) {
1815 let du = pair[1].x - pair[0].x;
1816 let folded = du - period * (du / period).round();
1817 cursor = Vec2 {
1818 x: cursor.x + folded,
1819 y: pair[1].y,
1820 };
1821 unwrapped.push(cursor);
1822 }
1823 let net = unwrapped[unwrapped.len() - 1].x - unwrapped[0].x;
1824 if (net.abs() - period).abs() > 2e-2 * period {
1825 return Ok(None); }
1827 if (unwrapped[unwrapped.len() - 1].y - unwrapped[0].y).abs() > 1e-3 * v_span {
1828 return Ok(None); }
1830 let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1831 for p in &unwrapped {
1832 vmin = vmin.min(p.y);
1833 vmax = vmax.max(p.y);
1834 }
1835 rims.push(Rim {
1836 points: unwrapped,
1837 vmin,
1838 vmax,
1839 ascending: net > 0.0,
1840 });
1841 }
1842 if !out_of_domain {
1843 return Ok(None);
1844 }
1845 if rims[0].ascending == rims[1].ascending {
1846 return Ok(None); }
1848 let (lower, upper) = if rims[0].vmax <= rims[1].vmin {
1849 (&rims[0], &rims[1])
1850 } else if rims[1].vmax <= rims[0].vmin {
1851 (&rims[1], &rims[0])
1852 } else {
1853 return Ok(None); };
1855 if upper.vmin - lower.vmax <= 1e-6 * v_span {
1856 return Ok(None);
1857 }
1858 if (lower.ascending) != face.same_sense {
1863 return Ok(None);
1864 }
1865 Ok(Some(RimStripPrep {
1866 lower: lower.points.clone(),
1867 upper: upper.points.clone(),
1868 period,
1869 }))
1870}
1871
1872fn covering_rim_strip_point_in_face(
1873 prepared: &RimStripPrep,
1874 point: Vec2,
1875 tolerance: f64,
1876) -> Option<PolygonClass> {
1877 let RimStripPrep { lower, upper, period } = prepared;
1878 let period = *period;
1879 for rim in [lower, upper] {
1881 for shift in [-period, 0.0, period] {
1882 let image = Vec2 {
1883 x: point.x + shift,
1884 y: point.y,
1885 };
1886 for pair in rim.windows(2) {
1887 if point_segment_distance(image, pair[0], pair[1]) <= tolerance {
1888 return Some(PolygonClass::Boundary);
1889 }
1890 }
1891 }
1892 }
1893 let mut crossings = 0usize;
1896 for rim in [lower, upper] {
1897 let window_base = rim[0].x.min(rim[rim.len() - 1].x);
1898 let x = window_base + (point.x - window_base).rem_euclid(period);
1899 for pair in rim.windows(2) {
1900 let (a, b) = (pair[0], pair[1]);
1901 if (a.x > x) != (b.x > x) {
1902 let v_cross = a.y + (x - a.x) / (b.x - a.x) * (b.y - a.y);
1903 if v_cross > point.y {
1904 crossings += 1;
1905 }
1906 }
1907 }
1908 }
1909 Some(if crossings % 2 == 1 {
1910 PolygonClass::Inside
1911 } else {
1912 PolygonClass::Outside
1913 })
1914}
1915
1916pub fn prepare_generic(face: &FaceRecord, prepared: &PreparedFace) -> Result<GenericPrep, String> {
1920 let slots = coedge_slots(face);
1921 let mut flat = 0usize;
1922 let mut loops: Vec<LoopSamples> = Vec::with_capacity(face.loops.len());
1923 let mut segments: Vec<Vec<SegmentPrep>> = Vec::with_capacity(face.loops.len());
1924 let mut chord_count = 0;
1925 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1926 let polygon = loop_samples(prepared, face, loop_index)?;
1927 let mut chords = Vec::with_capacity(polygon.len());
1928 let mut coedges = Vec::with_capacity(loop_record.coedges.len());
1929 let mut first = 0;
1930 for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1931 let curve = &coedge.pcurve;
1932 let [start, end] = curve.domain()?;
1933 let sample_count = trim_sample_count(curve);
1934 for index in 0..sample_count {
1935 let parameter = trim_station(start, end, index, sample_count);
1936 let parameter_end = if index + 1 < sample_count {
1937 trim_station(start, end, index + 1, sample_count)
1938 } else {
1939 end
1940 };
1941 chords.push(SegmentPrep {
1942 coedge_index,
1943 parameter_start: parameter,
1944 parameter_end,
1945 });
1946 }
1947 coedges.push((slots[flat] as u64, first, sample_count));
1948 flat += 1;
1949 first += sample_count;
1950 }
1951 debug_assert_eq!(first, polygon.len());
1952 chord_count += chords.len();
1953 loops.push(LoopSamples { polygon, coedges });
1954 segments.push(chords);
1955 }
1956 containment_profile(|p| p.generic_chords += chord_count as u64);
1957 Ok(GenericPrep {
1958 loops,
1959 segments,
1960 chord_count,
1961 index: std::cell::OnceCell::new(),
1962 })
1963}
1964
1965pub struct LoopSamples {
1970 polygon: std::rc::Rc<Vec<Vec2>>,
1971 coedges: Vec<(u64, usize, usize)>,
1972}
1973
1974fn sphere_chart_point_in_face(
1999 face: &FaceRecord,
2000 point: Vec2,
2001 prepared: &PreparedFace,
2002 sampled: &[LoopSamples],
2003) -> Result<Option<PolygonClass>, String> {
2004 let Some(atlas) = sphere_chart_atlas(face) else {
2005 return Ok(None);
2006 };
2007 if sphere_region_reduced_enabled() {
2008 let reduced = lane(&prepared.sphere_region_reduced, || build_sphere_region_reduced(face, &atlas, sampled))?;
2009 if let Some((region, margin)) = reduced {
2010 if !region.is_whole_sphere() && region.is_decidable() {
2011 let probe = face.surface.evaluate(point.x, point.y)?;
2012 if region.clear_of_boundary(atlas.centre, probe, *margin) {
2013 return Ok(Some(if region.contains(atlas.centre, probe) {
2014 PolygonClass::Inside
2015 } else {
2016 PolygonClass::Outside
2017 }));
2018 }
2019 }
2020 }
2021 }
2022 let region = lane(&prepared.sphere_region, || build_sphere_region(face, &atlas, sampled))?;
2023 if region.is_whole_sphere() {
2024 return Ok(Some(PolygonClass::Inside));
2025 }
2026 if !region.is_decidable() {
2027 return Ok(None);
2030 }
2031 let probe = face.surface.evaluate(point.x, point.y)?;
2032 Ok(Some(if region.contains(atlas.centre, probe) {
2033 PolygonClass::Inside
2034 } else {
2035 PolygonClass::Outside
2036 }))
2037}
2038
2039fn sphere_region_reduced_enabled() -> bool {
2042 crate::switch!("BREP_SPHERE_REGION_REDUCED", true)
2043}
2044
2045const REDUCED_REGION_SAMPLES: usize = 4096;
2047
2048pub fn build_sphere_region_reduced(
2066 face: &FaceRecord,
2067 atlas: &crate::sphere_chart::SphereAtlas,
2068 sampled: &[LoopSamples],
2069) -> Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String> {
2070 let total: usize = sampled.iter().map(|samples| samples.polygon.len()).sum();
2071 if total < REDUCED_REGION_SAMPLES {
2072 return Ok(None);
2073 }
2074 let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
2075 for slot in coedge_slots(face) {
2076 *uses.entry(slot as u64).or_insert(0) += 1;
2077 }
2078 let outward_face_normal = face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
2079 let memo = sphere_reduction_memo_enabled();
2080 let carrier = memo.then(|| {
2081 let mut lane = crate::mass_properties::TwoLane::new();
2082 crate::mass_properties::hash_surface(&mut lane, &face.surface);
2083 lane.finish()
2084 });
2085 let mut points: Vec<Vec3> = Vec::new();
2086 let mut spans: Vec<(usize, usize)> = Vec::new();
2087 let mut deviation = 0.0f64;
2088 for samples in sampled {
2089 let count = samples.polygon.len();
2090 if count < 2 {
2091 continue;
2092 }
2093 for &(edge_id, first, span) in &samples.coedges {
2094 if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
2095 continue;
2096 }
2097 let key = carrier.map(|carrier| {
2098 let mut lane = crate::mass_properties::TwoLane::new();
2099 lane.u64(carrier[0]);
2100 lane.u64(carrier[1]);
2101 lane.usize(span);
2102 for offset in 0..=span {
2103 let uv = samples.polygon[(first + offset) % count];
2104 lane.f64(uv.x);
2105 lane.f64(uv.y);
2106 }
2107 lane.finish()
2108 });
2109 if let Some(served) = key.and_then(|key| SPHERE_REDUCTIONS.with(|memo| memo.borrow().get(&key).cloned())) {
2110 let Some((kept, kept_deviation)) = served else {
2111 return Ok(None);
2112 };
2113 deviation = deviation.max(kept_deviation);
2114 let start = points.len();
2115 points.extend(kept.iter().copied());
2116 spans.push((start, points.len()));
2117 continue;
2118 }
2119 let reduced = reduce_sphere_coedge(face, atlas, &samples.polygon, first, span)?;
2120 if let Some(key) = key {
2121 SPHERE_REDUCTIONS.with(|memo| {
2122 let mut memo = memo.borrow_mut();
2123 if memo.len() >= SPHERE_REDUCTION_ENTRIES {
2124 memo.clear();
2125 }
2126 memo.insert(key, reduced.clone());
2127 });
2128 }
2129 let Some((kept, kept_deviation)) = reduced else {
2130 return Ok(None);
2131 };
2132 deviation = deviation.max(kept_deviation);
2133 let start = points.len();
2134 points.extend(kept.iter().copied());
2135 spans.push((start, points.len()));
2136 }
2137 }
2138 if 2 * points.len() > total {
2139 return Ok(None);
2140 }
2141 crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2142 let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2143 for (first, last) in spans {
2144 for index in first..last.saturating_sub(1) {
2145 boundary.push((points[index], points[index + 1]));
2146 }
2147 }
2148 let region = crate::sphere_chart::SphericalRegion::from_segments(atlas.centre, &boundary, outward_face_normal);
2149 let rounding = 4e-9 / atlas.radius.max(f64::MIN_POSITIVE);
2150 Ok(Some((region, 2.0 * deviation + rounding)))
2151}
2152
2153fn reduce_sphere_coedge(
2159 face: &FaceRecord,
2160 atlas: &crate::sphere_chart::SphereAtlas,
2161 polygon: &[Vec2],
2162 first: usize,
2163 span: usize,
2164) -> Result<Option<(std::rc::Rc<Vec<Vec3>>, f64)>, String> {
2165 use crate::sphere_chart::{arc_distance, arc_normal};
2166 let count = polygon.len();
2167 let mut along: Vec<Vec3> = Vec::with_capacity(span + 1);
2168 for offset in 0..=span {
2169 let uv = polygon[(first + offset) % count];
2170 along.push(face.surface.evaluate(uv.x, uv.y)?);
2171 }
2172 let Ok(units) = along.iter().map(|p| p.sub(atlas.centre).normalized()).collect::<Result<Vec<_>, _>>() else {
2173 return Ok(None);
2174 };
2175 let last = along.len() - 1;
2176 let mut chords: Vec<f64> = units.windows(2).map(|pair| pair[0].sub(pair[1]).length()).collect();
2177 chords.sort_by(f64::total_cmp);
2178 let target = 0.1 * chords[chords.len() / 2];
2179 let mut kept: Vec<usize> = (0..=last).collect();
2180 let mut kept_deviation = 0.0f64;
2181 for stride in [32usize, 16, 8, 4, 2] {
2182 if last < 2 * stride {
2183 continue;
2184 }
2185 let indices: Vec<usize> = (0..=last).filter(|&i| i.min(last - i) % stride == 0).collect();
2186 let mut worst = 0.0f64;
2187 for pair in indices.windows(2) {
2188 let (a, b) = (units[pair[0]], units[pair[1]]);
2189 let normal = arc_normal(a, b);
2190 for j in pair[0] + 1..pair[1] {
2191 worst = worst.max(arc_distance(a, b, normal, units[j]));
2192 }
2193 }
2194 if worst <= target {
2195 kept = indices;
2196 kept_deviation = worst;
2197 break;
2198 }
2199 }
2200 Ok(Some((std::rc::Rc::new(kept.iter().map(|&i| along[i]).collect()), kept_deviation)))
2201}
2202
2203fn sphere_reduction_memo_enabled() -> bool {
2210 let enabled = crate::switch!("BREP_SPHERE_REDUCTION_MEMO", true);
2211 enabled
2212}
2213
2214
2215const SPHERE_REDUCTION_ENTRIES: usize = 4096;
2217
2218thread_local! {
2219 pub static SPHERE_REDUCTIONS: std::cell::RefCell<std::collections::HashMap<[u64; 2], Option<(std::rc::Rc<Vec<Vec3>>, f64)>>> =
2223 std::cell::RefCell::new(std::collections::HashMap::new());
2224}
2225
2226fn build_sphere_region(
2244 face: &FaceRecord,
2245 atlas: &crate::sphere_chart::SphereAtlas,
2246 sampled: &[LoopSamples],
2247) -> Result<crate::sphere_chart::SphericalRegion, String> {
2248 let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
2252 for slot in coedge_slots(face) {
2253 *uses.entry(slot as u64).or_insert(0) += 1;
2254 }
2255 let outward_face_normal =
2280 face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
2281 let evaluate_started = containment_profile_started();
2282 let mut points: Vec<Vec3> = Vec::new();
2283 let mut spans: Vec<(usize, usize)> = Vec::new();
2284 for samples in sampled {
2285 let count = samples.polygon.len();
2286 if count < 2 {
2287 continue;
2288 }
2289 for &(edge_id, first, span) in &samples.coedges {
2290 if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
2291 continue;
2292 }
2293 let start = points.len();
2297 for offset in 0..=span {
2298 let uv = samples.polygon[(first + offset) % count];
2299 points.push(face.surface.evaluate(uv.x, uv.y)?);
2300 }
2301 spans.push((start, points.len()));
2302 }
2303 }
2304 let evaluate_ms = containment_elapsed_ms(evaluate_started);
2309 let canonical_started = containment_profile_started();
2310 crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2311 let canonical_ms = containment_elapsed_ms(canonical_started);
2312 let segments_started = containment_profile_started();
2313 let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2314 for (first, last) in spans {
2315 for index in first..last.saturating_sub(1) {
2316 boundary.push((points[index], points[index + 1]));
2317 }
2318 }
2319 let region = crate::sphere_chart::SphericalRegion::from_segments(
2320 atlas.centre,
2321 &boundary,
2322 outward_face_normal,
2323 );
2324 let segments_ms = containment_elapsed_ms(segments_started);
2325 containment_profile(|p| {
2326 p.region_builds += 1;
2327 p.region_evaluate_ms += evaluate_ms;
2328 p.region_canonical_ms += canonical_ms;
2329 p.region_segments_ms += segments_ms;
2330 });
2331 Ok(region)
2332}
2333
2334
2335pub fn sphere_chart_atlas(face: &FaceRecord) -> Option<crate::sphere_chart::SphereAtlas> {
2338 if !sphere_chart_trim_enabled() {
2339 return None;
2340 }
2341 crate::sphere_chart::SphereAtlas::of_surface(&face.surface)
2342}
2343
2344fn containment_trace_enabled() -> bool {
2348 debug_flag!("BREP_DEBUG_CONTAINMENT")
2349}
2350
2351fn trace_lane(face: &FaceRecord, point: Vec2, lane: &str, class: PolygonClass) {
2356 if containment_trace_enabled() {
2357 eprintln!(
2358 "containment face={} uv=({:.8},{:.8}) lane={lane} -> {class:?}",
2359 face.id, point.x, point.y
2360 );
2361 }
2362}
2363
2364
2365enum Lane<'a> {
2367 SeamBand(&'a SeamBandPrep),
2368 SphereCap(&'a SphereCapPrep),
2369 Horizon(&'a HorizonPrep),
2370 RimStrip(&'a RimStripPrep),
2371 Generic,
2372}
2373
2374fn lane_from<'a>(
2382 face: &FaceRecord,
2383 prepared: &'a PreparedFace,
2384 from: usize,
2385) -> Result<(usize, Lane<'a>), String> {
2386 if from == 0 {
2387 let band = timed_lane(&prepared.seam_band, || prepare_seam_band(face), |p, ms| {
2388 p.seam_band_preps += 1;
2389 p.seam_band_ms += ms;
2390 })?;
2391 if !matches!(band, SeamBandPrep::NotApplicable | SeamBandPrep::Declined) {
2392 return Ok((0, Lane::SeamBand(band)));
2393 }
2394 }
2395 if from <= 1 {
2396 if let Some(cap) = timed_lane(&prepared.sphere_cap, || prepare_winding_sphere_cap(face, prepared), |p, ms| {
2397 p.sphere_cap_preps += 1;
2398 p.sphere_cap_ms += ms;
2399 })? {
2400 return Ok((1, Lane::SphereCap(cap)));
2401 }
2402 }
2403 if from <= 2 {
2404 if let Some(horizon) = timed_lane(&prepared.horizon, || prepare_wrapped_horizon(face, prepared), |p, ms| {
2405 p.horizon_preps += 1;
2406 p.horizon_ms += ms;
2407 })? {
2408 return Ok((2, Lane::Horizon(horizon)));
2409 }
2410 }
2411 if from <= 3 {
2412 if let Some(strip) = timed_lane(&prepared.rim_strip, || prepare_covering_rim_strip(face), |p, ms| {
2413 p.rim_strip_preps += 1;
2414 p.rim_strip_ms += ms;
2415 })? {
2416 return Ok((3, Lane::RimStrip(strip)));
2417 }
2418 }
2419 Ok((4, Lane::Generic))
2420}
2421
2422pub fn containment_lane(face: &FaceRecord) -> Result<ContainmentLane, String> {
2464 let prepared = cached_prepared_face(face).unwrap_or_else(|| std::rc::Rc::new(PreparedFace::new()));
2465 Ok(match lane_from(face, &prepared, 0)?.1 {
2466 Lane::SeamBand(_) => ContainmentLane::SeamBand,
2467 Lane::SphereCap(_) => ContainmentLane::SphereCap,
2468 Lane::Horizon(horizon) => ContainmentLane::WrappedHorizon {
2469 loops: horizon.loops.clone(),
2470 u_period: horizon.u_period,
2471 cross_frame: horizon_cross_frame(),
2472 },
2473 Lane::RimStrip(_) => ContainmentLane::CoveringRimStrip,
2474 Lane::Generic => ContainmentLane::Generic {
2475 sphere_chart: sphere_chart_atlas(face).is_some(),
2476 },
2477 })
2478}
2479
2480#[derive(Clone, Debug)]
2482pub enum ContainmentLane {
2483 SeamBand,
2485 SphereCap,
2489 WrappedHorizon {
2496 loops: Vec<Vec<Vec2>>,
2499 u_period: f64,
2500 cross_frame: bool,
2501 },
2502 CoveringRimStrip,
2504 Generic {
2510 sphere_chart: bool,
2513 },
2514}
2515
2516pub fn parameter_point_in_face(
2517 face: &FaceRecord,
2518 point: Vec2,
2519 tolerance: f64,
2520) -> Result<PolygonClass, String> {
2521 point_in_face_scanned(face, point, tolerance, ChordScan::Auto)
2522}
2523
2524#[doc(hidden)]
2529pub fn parameter_point_in_face_scan(
2530 face: &FaceRecord,
2531 point: Vec2,
2532 tolerance: f64,
2533 indexed: bool,
2534) -> Result<PolygonClass, String> {
2535 let scan = if indexed {
2536 ChordScan::Indexed
2537 } else {
2538 ChordScan::Linear
2539 };
2540 point_in_face_scanned(face, point, tolerance, scan)
2541}
2542
2543fn point_in_face_scanned(
2544 face: &FaceRecord,
2545 point: Vec2,
2546 tolerance: f64,
2547 scan: ChordScan,
2548) -> Result<PolygonClass, String> {
2549 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
2550 let prepared = prepared_face(face);
2551 let mut from = 0;
2552 loop {
2553 let (position, lane) = lane_from(face, &prepared, from)?;
2554 let answer = match lane {
2555 Lane::SeamBand(band) => {
2556 seam_band_point_in_face(band, point, tolerance).map(|class| ("seam_band", class))
2557 }
2558 Lane::SphereCap(cap) => winding_sphere_cap_point_in_face(cap, point, tolerance)
2559 .map(|class| ("winding_sphere_cap", class)),
2560 Lane::Horizon(horizon) => wrapped_horizon_point_in_face(face, horizon, point, tolerance, scan)
2561 .map(|class| ("wrapped_horizon", class)),
2562 Lane::RimStrip(strip) => covering_rim_strip_point_in_face(strip, point, tolerance)
2563 .map(|class| ("covering_rim_strip", class)),
2564 Lane::Generic => break,
2565 };
2566 if let Some((name, class)) = answer {
2567 trace_lane(face, point, name, class);
2568 return Ok(class);
2569 }
2570 from = position + 1;
2571 }
2572 let generic = timed_lane(&prepared.generic, || prepare_generic(face, &prepared), |p, ms| {
2573 p.generic_preps += 1;
2574 p.generic_ms += ms;
2575 })?;
2576 let (crossings, boundary, nearest) = generic_scan(generic, point, tolerance, scan);
2577 if boundary {
2578 trace_lane(face, point, "polygon_boundary", PolygonClass::Boundary);
2579 return Ok(PolygonClass::Boundary);
2580 }
2581 let parity = if crossings % 2 == 1 {
2582 PolygonClass::Inside
2583 } else {
2584 PolygonClass::Outside
2585 };
2586 let chord = nearest.map(|(loop_index, index, distance)| {
2587 let polygon = &generic.loops[loop_index].polygon;
2588 let prep = generic.segments[loop_index][index];
2589 (
2590 polygon[index],
2591 polygon[(index + 1) % polygon.len()],
2592 &face.loops[loop_index].coedges[prep.coedge_index].pcurve,
2593 prep,
2594 distance,
2595 )
2596 });
2597 if containment_trace_enabled() {
2598 let (distance, length) = match chord.as_ref() {
2599 Some((start, end, _, _, distance)) => (*distance, end.sub(*start).length()),
2600 None => (f64::NAN, f64::NAN),
2601 };
2602 eprintln!(
2603 "containment face={} uv=({:.8},{:.8}) crossings={crossings} parity={parity:?} \
2604 nearest distance={distance:.3e} segment length={length:.3e}",
2605 face.id, point.x, point.y
2606 );
2607 }
2608 let parity_decides = match chord.as_ref() {
2617 None => true,
2618 Some((start, end, _, _, distance)) => {
2619 let length = end.sub(*start).length();
2620 *distance > length || length <= 0.0
2621 }
2622 };
2623 if parity_decides {
2624 if let Some(class) = sphere_chart_point_in_face(face, point, &prepared, &generic.loops)? {
2625 trace_lane(face, point, "sphere_chart", class);
2626 return Ok(class);
2627 }
2628 }
2629 let Some((segment_start, segment_end, curve, prep, distance)) = chord else {
2630 trace_lane(face, point, "parity (no segment)", parity);
2631 return Ok(parity);
2632 };
2633 let segment_length = segment_end.sub(segment_start).length();
2634 if distance > segment_length || segment_length <= 0.0 {
2635 trace_lane(face, point, "parity (far from every segment)", parity);
2636 return Ok(parity);
2637 }
2638 let chord_parameter = prep.parameter_start
2639 + (prep.parameter_end - prep.parameter_start)
2640 * (point.sub(segment_start).dot(segment_end.sub(segment_start))
2641 / (segment_length * segment_length))
2642 .clamp(0.0, 1.0);
2643 let [domain_start, domain_end] = curve.domain()?;
2644 let small = crate::curve::small_curve_derivatives_enabled();
2645 let read = |parameter: f64, count: usize| -> Result<[Vec3; 3], String> {
2646 if small {
2647 return curve.derivatives_small(parameter, count);
2648 }
2649 let heap = curve.derivatives(parameter, count)?;
2650 let mut grid = [Vec3::default(); 3];
2651 grid[..heap.len()].copy_from_slice(&heap);
2652 Ok(grid)
2653 };
2654 use crate::projection::{curve_foot_newton, CurveFootPolicy, FootDomain, FootMode};
2655 let (parameter, _) = curve_foot_newton(curve, Vec3::new(point.x, point.y, 0.0),
2656 chord_parameter, [domain_start, domain_end], CurveFootPolicy {
2657 domain: FootDomain::Clamp,
2658 iterations: 12,
2659 slope_guard: 1e-30,
2660 step_limit: f64::INFINITY,
2661 parameter_tolerance: 1e-14 * (domain_end - domain_start + 1.0),
2662 mode: FootMode::Planar,
2663 })?;
2664 let margin = 1e-9 * (domain_end - domain_start);
2665 if parameter > domain_start + margin && parameter < domain_end - margin {
2666 let derivatives = read(parameter, 1)?;
2667 let on_curve = Vec2 {
2668 x: derivatives[0].x,
2669 y: derivatives[0].y,
2670 };
2671 let tangent = Vec2 {
2672 x: derivatives[1].x,
2673 y: derivatives[1].y,
2674 };
2675 let offset = point.sub(on_curve);
2676 if offset.length() <= tolerance {
2677 trace_lane(face, point, "nearest curve (on it)", PolygonClass::Boundary);
2678 return Ok(PolygonClass::Boundary);
2679 }
2680 let cross = tangent.x * offset.y - tangent.y * offset.x;
2681 if cross.abs() > 1e-30 {
2682 let class = if (cross > 0.0) == face.same_sense {
2683 PolygonClass::Inside
2684 } else {
2685 PolygonClass::Outside
2686 };
2687 trace_lane(face, point, "nearest curve (side)", class);
2688 return Ok(class);
2689 }
2690 }
2691 trace_lane(face, point, "parity (nearest curve declined)", parity);
2692 Ok(parity)
2693}
2694
2695