1use super::*;
2
3fn face_normal(face: &FaceRecord, u: f64, v: f64) -> Result<Vec3, String> {
4 let normal = match face.surface.normal(u, v) {
5 Ok(normal) => normal,
6 Err(error) => {
7 if !error.contains("zero-length")
17 || std::env::var("BREP_POLE_NORMAL_RESCUE").as_deref() == Ok("0")
18 {
19 return Err(error);
20 }
21 let [u0, u1] = face.surface.domain_u()?;
22 let [v0, v1] = face.surface.domain_v()?;
23 let step_u = (u1 - u0) * 1e-4;
24 let step_v = (v1 - v0) * 1e-4;
25 let inner_u = u.clamp(u0 + step_u, u1 - step_u);
26 let inner_v = v.clamp(v0 + step_v, v1 - step_v);
27 let mut recovered = None;
28 for (cu, cv) in [(u, inner_v), (inner_u, v), (inner_u, inner_v)] {
29 if let Ok(normal) = face.surface.normal(cu, cv) {
30 recovered = Some(normal);
31 break;
32 }
33 }
34 match recovered {
35 Some(normal) => normal,
36 None => return Err(error),
37 }
38 }
39 };
40 Ok(if face.same_sense {
41 normal
42 } else {
43 normal.scale(-1.0)
44 })
45}
46
47fn thin_body_band_enabled() -> bool {
55 crate::switch!("BREP_CLASSIFY_THIN_BODY_BAND", true)
56}
57
58fn thin_body_band_check() -> bool {
61 crate::switch!("BREP_CLASSIFY_THIN_BODY_BAND_CHECK", false)
62}
63
64fn face_uv_tolerance(face: &FaceRecord, u: f64, v: f64, spatial: f64) -> f64 {
65 surface_uv_band(&face.surface, u, v, spatial)
66}
67
68pub fn surface_uv_band(surface: &crate::NurbsSurface, u: f64, v: f64, spatial: f64) -> f64 {
70 let Ok(derivatives) = surface.derivatives(u, v, 1) else {
71 return spatial;
72 };
73 let band = crate::tolerance::surface_uv_tolerance(
74 spatial,
75 derivatives[1][0].length(),
76 derivatives[0][1].length(),
77 );
78 let cap = match (surface.domain_u(), surface.domain_v()) {
79 (Ok([u0, u1]), Ok([v0, v1])) => ((u1 - u0).min(v1 - v0) * 0.05).max(1e-12),
80 _ => f64::INFINITY,
81 };
82 band.min(cap)
83}
84
85fn metric_trim_enabled() -> bool {
88 switch!("BREP_CLASSIFY_METRIC_TRIM", true)
89}
90
91fn metric_trim_check() -> bool {
94 switch!("BREP_CLASSIFY_METRIC_TRIM_CHECK", false)
95}
96
97fn metric_trim(face: &FaceRecord, u: f64, v: f64, spatial: f64) -> Result<PolygonClass, String> {
113 let band = face_uv_tolerance(face, u, v, spatial);
114 let old = parameter_point_in_face(face, Vec2 { x: u, y: v }, band)?;
115 let check = metric_trim_check();
116 if old != PolygonClass::Boundary || !(metric_trim_enabled() || check) {
117 return Ok(old);
118 }
119 let Ok(derivatives) = face.surface.derivatives(u, v, 1) else {
120 return Ok(old);
121 };
122 let cap = match (face.surface.domain_u(), face.surface.domain_v()) {
123 (Ok([u0, u1]), Ok([v0, v1])) => ((u1 - u0).min(v1 - v0) * 0.05).max(1e-12),
124 _ => f64::INFINITY,
125 };
126 let along_u = crate::tolerance::parametric_tolerance(spatial, derivatives[1][0].length()).min(cap);
127 let along_v = crate::tolerance::parametric_tolerance(spatial, derivatives[0][1].length()).min(cap);
128 let minor = along_u.min(along_v);
129 if !(minor > 0.0) || along_u.max(along_v) <= 4.0 * minor {
130 return Ok(old);
131 }
132 let centre = parameter_point_in_face(face, Vec2 { x: u, y: v }, minor)?;
133 let mut answer = centre;
134 if centre != PolygonClass::Boundary {
135 for step in 0..8 {
136 let angle = step as f64 * std::f64::consts::FRAC_PI_4;
137 let tip = Vec2 { x: u + along_u * angle.cos(), y: v + along_v * angle.sin() };
138 if parameter_point_in_face(face, tip, minor)? != centre {
139 answer = PolygonClass::Boundary;
140 break;
141 }
142 }
143 }
144 if check && answer != old {
145 eprintln!(
146 "classify metric trim: face {} uv ({u:.9}, {v:.9}) band {band:.3e} axes ({along_u:.3e}, {along_v:.3e}) old {old:?} metric {answer:?}",
147 face.id
148 );
149 }
150 Ok(if metric_trim_enabled() { answer } else { old })
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
154#[serde(rename_all = "lowercase")]
155pub enum PointClass {
156 In,
157 Out,
158 On,
159}
160
161#[derive(Clone, Copy, Debug, Serialize)]
162pub struct PointClassification {
163 pub class: PointClass,
164 #[serde(skip_serializing_if = "Option::is_none")]
165 pub on_normal: Option<Vec3>,
166}
167
168#[derive(Default, Clone, Copy)]
175pub struct ClassifyProfile {
176 pub enabled: bool,
177 pub classify_calls: u64,
178 pub band_candidates: u64,
179 pub band_project_ms: f64,
180 pub band_trim_tests: u64,
181 pub band_trim_ms: f64,
182 pub rays: u64,
183 pub ray_faces: u64,
184 pub ray_csi_ms: f64,
185 pub ray_exact_faces: u64,
188 pub ray_fallback_faces: u64,
189 pub ray_trim_tests: u64,
190 pub ray_trim_ms: f64,
191 pub coincident_calls: u64,
192 pub coincident_ms: f64,
193 pub classifier_builds: u64,
194 pub classifier_build_ms: f64,
195}
196
197thread_local! {
198 static CLASSIFY_PROFILE: std::cell::Cell<ClassifyProfile> =
199 const { std::cell::Cell::new(ClassifyProfile {
200 enabled: false, classify_calls: 0, band_candidates: 0, band_project_ms: 0.0,
201 band_trim_tests: 0, band_trim_ms: 0.0, rays: 0, ray_faces: 0, ray_csi_ms: 0.0,
202 ray_exact_faces: 0, ray_fallback_faces: 0, ray_trim_tests: 0, ray_trim_ms: 0.0, coincident_calls: 0, coincident_ms: 0.0,
203 classifier_builds: 0, classifier_build_ms: 0.0,
204 }) };
205}
206
207impl crate::profile::Counters for ClassifyProfile {
208 fn armed(&self) -> bool {
209 self.enabled
210 }
211}
212
213fn classify_profile(update: impl FnOnce(&mut ClassifyProfile)) {
214 crate::profile::update(&CLASSIFY_PROFILE, update)
215}
216
217fn classify_profile_started() -> Option<web_time::Instant> {
218 crate::profile::started(&CLASSIFY_PROFILE)
219}
220
221use crate::profile::elapsed_ms as classify_elapsed_ms;
222
223pub fn classify_profile_begin() {
225 let enabled = crate::profile::profile_enabled();
226 CLASSIFY_PROFILE.with(|cell| {
227 cell.set(ClassifyProfile {
228 enabled,
229 ..ClassifyProfile::default()
230 })
231 });
232}
233
234pub fn classify_profile_report(label: &str) {
237 let p = CLASSIFY_PROFILE.with(|cell| cell.get());
238 if !p.enabled {
239 return;
240 }
241 profile_line!(
242 "classify.profile {label} calls={} builds={} build_ms={:.2} band: candidates={} project_ms={:.2} trim_tests={} trim_ms={:.2} rays={} ray_faces={} csi_ms={:.2} exact_faces={} fallback_faces={} ray_trim_tests={} ray_trim_ms={:.2} coincident: calls={} ms={:.2}",
243 p.classify_calls, p.classifier_builds, p.classifier_build_ms, p.band_candidates,
244 p.band_project_ms, p.band_trim_tests, p.band_trim_ms, p.rays, p.ray_faces,
245 p.ray_csi_ms, p.ray_exact_faces, p.ray_fallback_faces, p.ray_trim_tests, p.ray_trim_ms, p.coincident_calls, p.coincident_ms,
246 );
247 CLASSIFY_PROFILE.with(|cell| cell.set(ClassifyProfile::default()));
248}
249
250fn exact_ray_enabled() -> bool {
257 switch!("BREP_CLASSIFY_EXACT_RAY", true)
258}
259
260fn ray_face_intersections(
264 sub_ray: &NurbsCurve,
265 surface: &crate::NurbsSurface,
266 tolerance: f64,
267) -> Result<Vec<crate::CurveSurfaceIntersection>, String> {
268 if exact_ray_enabled() {
269 if let Some(seeds) = crate::exact_line_surface::exact_line_surface_seeds(sub_ray, surface, tolerance) {
270 classify_profile(|p| p.ray_exact_faces += 1);
271 return crate::curve_surface_intersection::intersect_curve_surface_from_seeds(sub_ray, surface, tolerance, seeds);
272 }
273 classify_profile(|p| p.ray_fallback_faces += 1);
274 }
275 let check = crate::curve_clear::check_mode();
278 if check || ray_clear_enabled() {
279 let clear = crate::curve_clear::curve_clear_of_surface(sub_ray, surface, tolerance);
280 if check {
281 let hits = intersect_curve_surface(sub_ray, surface, tolerance)?;
282 if clear && !hits.is_empty() {
283 crate::curve_clear::disagreement("classifier ray", hits.len());
284 }
285 return Ok(hits);
286 }
287 if clear {
288 return Ok(Vec::new());
289 }
290 }
291 crate::curve_surface_intersection::intersect_ray_surface(sub_ray, surface, tolerance)
292}
293
294fn ray_clear_enabled() -> bool {
298 switch!("BREP_CLASSIFY_RAY_CLEAR", true)
299}
300
301pub struct SolidClassifier<'a> {
306 faces: Vec<&'a FaceRecord>,
307 face_boxes: Vec<Aabb>,
308 bounds: Aabb,
309 bvh: Bvh,
310 tolerance: f64,
311 coincident_caps: Vec<(Aabb, f64)>,
315}
316
317fn clip_segment_to_aabb(
321 start: Vec3,
322 direction: Vec3,
323 length: f64,
324 bounds: &Aabb,
325) -> Option<[f64; 2]> {
326 let mut s0 = 0.0f64;
327 let mut s1 = length;
328 for axis in 0..3 {
329 let (origin, delta, minimum, maximum) = match axis {
330 0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
331 1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
332 _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
333 };
334 if delta.abs() <= 1e-15 {
335 if origin < minimum || origin > maximum {
336 return None;
337 }
338 continue;
339 }
340 let mut near = (minimum - origin) / delta;
341 let mut far = (maximum - origin) / delta;
342 if near > far {
343 std::mem::swap(&mut near, &mut far);
344 }
345 s0 = s0.max(near);
346 s1 = s1.min(far);
347 if s0 > s1 {
348 return None;
349 }
350 }
351 Some([s0, s1])
352}
353
354fn planar_trim_boxes_enabled() -> bool {
363 switch!("BREP_CLASSIFY_PLANAR_TRIM_BOXES", true)
364}
365
366fn planar_trim_box(face: &FaceRecord, edges: &std::collections::HashMap<u64, &crate::topology::EdgeRecord>) -> Option<Aabb> {
369 if edges.is_empty() || face.loops.is_empty() || !face.surface.is_affine().unwrap_or(false) {
370 return None;
371 }
372 let mut trimmed = Aabb::empty();
373 for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
374 let edge = edges.get(&coedge.edge_id)?;
375 trimmed.include(Aabb::from_curve_controls(&edge.curve).ok()?);
376 }
377 Some(trimmed)
378}
379
380impl<'a> SolidClassifier<'a> {
381 pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
382 let build_started = classify_profile_started();
383 let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
384 let edges: std::collections::HashMap<u64, &crate::topology::EdgeRecord> =
385 if planar_trim_boxes_enabled() { solid.edges.iter().map(|edge| (edge.id, edge)).collect() } else { Default::default() };
386 let face_boxes = faces
387 .iter()
388 .map(|face| match planar_trim_box(face, &edges) {
389 Some(trimmed) => Ok(trimmed),
390 None => Aabb::from_surface_controls(&face.surface),
391 })
392 .collect::<Result<Vec<_>, _>>()?;
393 let mut bounds = Aabb::empty();
394 for face_box in &face_boxes {
395 bounds.include(*face_box);
396 }
397 let bvh = Bvh::build(&face_boxes);
398 classify_profile(|p| {
399 p.classifier_builds += 1;
400 p.classifier_build_ms += classify_elapsed_ms(build_started);
401 });
402 Ok(Self {
403 faces,
404 face_boxes,
405 bounds,
406 bvh,
407 tolerance,
408 coincident_caps: Vec::new(),
409 })
410 }
411
412 pub fn chord_orientation(&self, through: Vec3, direction: Vec3) -> Result<Option<bool>, String> {
428 let on_tolerance = self.tolerance * 10.0;
429 let direction = direction.normalized()?;
430 let middle = self.bounds.minimum.add(self.bounds.maximum).scale(0.5);
431 let reach = self.bounds.diagonal() + through.sub(middle).length() + 1.0;
432 let start = through.sub(direction.scale(reach));
433 let length = 2.0 * reach;
434 let end = start.add(direction.scale(length));
435 let mut candidates = Vec::new();
436 self.bvh.intersecting_segment(start, end, on_tolerance, &mut candidates);
437 candidates.sort_unstable();
438 let mut hits: Vec<(f64, bool)> = Vec::new();
440 let mut aimed = false;
441 for &index in &candidates {
442 let face = self.faces[index];
443 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
444 let Some([span_start, span_end]) =
445 clip_segment_to_aabb(start, direction, length, &self.face_boxes[index].expanded(margin))
446 else {
447 continue;
448 };
449 let span_start = (span_start - margin).max(0.0);
450 let span_end = (span_end + margin).min(length);
451 if span_end - span_start <= 1e-12 {
452 continue;
453 }
454 let sub_ray = make_line(start.add(direction.scale(span_start)), start.add(direction.scale(span_end)))?;
455 for intersection in ray_face_intersections(&sub_ray, &face.surface, self.tolerance)? {
456 if intersection.tangential {
457 return Ok(None);
458 }
459 let uv = Vec2 { x: intersection.u, y: intersection.v };
460 match parameter_point_in_face(face, uv, face_uv_tolerance(face, uv.x, uv.y, on_tolerance))? {
461 PolygonClass::Outside => continue,
462 PolygonClass::Boundary => return Ok(None),
463 PolygonClass::Inside => {}
464 }
465 let along = face_normal(face, uv.x, uv.y)?.dot(direction);
466 if along.abs() < 1e-2 {
467 return Ok(None);
468 }
469 if intersection.point.sub(through).length() <= on_tolerance {
470 aimed = true;
471 }
472 hits.push((intersection.point.sub(start).dot(direction), along > 0.0));
473 }
474 }
475 if !aimed || hits.is_empty() || hits.len() % 2 == 1 {
476 return Ok(None);
477 }
478 hits.sort_by(|a, b| a.0.total_cmp(&b.0));
479 for pair in hits.windows(2) {
480 if pair[1].0 - pair[0].0 <= on_tolerance || pair[1].1 == pair[0].1 {
481 return Ok(None);
482 }
483 }
484 Ok(Some(!hits[0].1))
485 }
486
487 pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
493 let on_tolerance = self.tolerance * 10.0;
494 if !self.bounds.expanded(on_tolerance).contains(point) {
495 return Ok(false);
496 }
497 let mut candidates = Vec::new();
498 self.bvh
499 .containing_point(point, on_tolerance, &mut candidates);
500 for &index in &candidates {
501 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
502 if projection.distance <= on_tolerance {
503 return Ok(true);
504 }
505 }
506 Ok(false)
507 }
508
509 pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
518 if !self.bounds.expanded(band).contains(point) {
519 return Ok(false);
520 }
521 let mut candidates = Vec::new();
522 self.bvh.containing_point(point, band, &mut candidates);
523 for &index in &candidates {
524 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
525 if projection.distance <= band {
526 return Ok(true);
527 }
528 }
529 Ok(false)
530 }
531
532 pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
533 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
534 classify_profile(|p| p.classify_calls += 1);
535 let tolerance = self.tolerance;
536 if !self.bounds.expanded(tolerance).contains(point) {
537 return Ok(PointClassification {
538 class: PointClass::Out,
539 on_normal: None,
540 });
541 }
542 let on_tolerance = self.capped_band(point, tolerance * 10.0);
546 if !self.coincident_caps.is_empty() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
547 eprintln!("feature_scale: classify at {point:?} on band {on_tolerance:.3e} (uncapped {:.3e}, {} caps)", tolerance * 10.0, self.coincident_caps.len());
548 }
549 let (thin_on, thin_check) = (thin_body_band_enabled(), thin_body_band_check());
558 if thin_on || thin_check {
559 if let Some(cap) = self.thin_body_cap(point, on_tolerance)? {
560 if cap < on_tolerance {
561 let ray_tolerance = (0.1 * cap).min(self.tolerance);
565 if thin_on {
566 return self.classify_banded(point, cap, ray_tolerance);
567 }
568 let kept = self.classify_banded(point, on_tolerance, self.tolerance)?;
569 let capped = self.classify_banded(point, cap, ray_tolerance)?;
570 if kept.class != capped.class {
571 eprintln!(
572 "thin-body band check: {point:?} reads {:?} at the band {on_tolerance:.3e}, {:?} at the thickness cap {cap:.3e}",
573 kept.class, capped.class
574 );
575 }
576 return Ok(kept);
577 }
578 }
579 }
580 self.classify_banded(point, on_tolerance, self.tolerance)
581 }
582
583 fn thin_body_cap(&self, point: Vec3, band: f64) -> Result<Option<f64>, String> {
590 let mut candidates = Vec::new();
591 self.bvh.containing_point(point, band, &mut candidates);
592 let mut cap: Option<f64> = None;
593 let reach = 4.0 * band;
594 for &index in &candidates {
595 let face = self.faces[index];
596 let projection = project_point_to_surface(&face.surface, point)?;
597 if projection.distance > band {
598 continue;
599 }
600 let uv = Vec2 { x: projection.u, y: projection.v };
601 if parameter_point_in_face(face, uv, face_uv_tolerance(face, projection.u, projection.v, band))? == PolygonClass::Outside {
602 continue;
603 }
604 let Ok(normal) = face_normal(face, projection.u, projection.v) else { continue };
605 let inward = normal.scale(-1.0);
606 let offset = 1e-3 * band;
612 let resolution = 1e-3 * band;
613 let foot = projection.point;
614 let from = foot.add(inward.scale(offset));
615 let to = foot.add(inward.scale(reach));
616 let mut hits = Vec::new();
617 self.bvh.intersecting_segment(from, to, band, &mut hits);
618 let ray = make_line(from, to)?;
619 for &other in &hits {
620 let other_face = self.faces[other];
621 for hit in ray_face_intersections(&ray, &other_face.surface, resolution)? {
622 let distance = hit.point.sub(foot).length();
623 if !(distance > offset) || distance > reach {
624 continue;
625 }
626 let trim = parameter_point_in_face(
627 other_face,
628 Vec2 { x: hit.u, y: hit.v },
629 face_uv_tolerance(other_face, hit.u, hit.v, resolution),
630 )?;
631 if trim != PolygonClass::Outside {
632 let quarter = distance / 4.0;
633 cap = Some(cap.map_or(quarter, |c: f64| c.min(quarter)));
634 }
635 }
636 }
637 }
638 Ok(cap)
639 }
640
641 fn classify_banded(&self, point: Vec3, on_tolerance: f64, tolerance: f64) -> Result<PointClassification, String> {
644 let mut candidates = Vec::new();
645 self.bvh
646 .containing_point(point, on_tolerance, &mut candidates);
647 candidates.sort_unstable();
648 let mut interior_normals: Vec<Vec3> = Vec::new();
655 let mut boundary_normals: Vec<Vec3> = Vec::new();
656 for &index in &candidates {
657 let face = self.faces[index];
658 let project_started = classify_profile_started();
659 let projection = project_point_to_surface(&face.surface, point)?;
660 classify_profile(|p| {
661 p.band_candidates += 1;
662 p.band_project_ms += classify_elapsed_ms(project_started);
663 });
664 if projection.distance > on_tolerance {
665 continue;
666 }
667 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
668 let trim_started = classify_profile_started();
669 let trim = parameter_point_in_face(
670 face,
671 Vec2 {
672 x: projection.u,
673 y: projection.v,
674 },
675 uv_tolerance,
676 )?;
677 classify_profile(|p| {
678 p.band_trim_tests += 1;
679 p.band_trim_ms += classify_elapsed_ms(trim_started);
680 });
681 match trim {
682 PolygonClass::Inside => {
683 interior_normals.push(face_normal(face, projection.u, projection.v)?)
684 }
685 PolygonClass::Boundary => {
686 boundary_normals.push(face_normal(face, projection.u, projection.v)?)
687 }
688 PolygonClass::Outside => {}
689 }
690 }
691 let pool = if interior_normals.is_empty() {
692 &boundary_normals
693 } else {
694 &interior_normals
695 };
696 if !pool.is_empty() {
697 let mut sum = Vec3::default();
698 for normal in pool {
699 sum = sum.add(*normal);
700 }
701 if sum.length() > 1e-3 {
705 return Ok(PointClassification {
706 class: PointClass::On,
707 on_normal: Some(sum.normalized()?),
708 });
709 }
710 }
711 let directions = [
712 Vec3::new(0.577215, 0.618034, 0.532088),
713 Vec3::new(-0.707107, 0.267949, 0.654321),
714 Vec3::new(0.316228, -0.741657, 0.585786),
715 Vec3::new(-0.414214, -0.552786, -0.723607),
716 Vec3::new(0.9482, 0.11893, -0.29456),
717 Vec3::new(-0.13947, 0.90271, -0.40718),
718 Vec3::new(0.62361, -0.33912, -0.70414),
719 Vec3::new(0.20912, 0.51293, 0.83261),
720 ];
721 let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
722 let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
732 let mut verdicts: Vec<PointClass> = Vec::new();
733 'directions: for direction in directions {
734 classify_profile(|p| p.rays += 1);
735 let direction = direction.normalized()?;
736 let ray_end = point.add(direction.scale(ray_length));
737 candidates.clear();
738 self.bvh
739 .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
740 candidates.sort_unstable();
741 let mut crossings = 0;
742 for &index in &candidates {
743 let face = self.faces[index];
744 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
754 let Some([span_start, span_end]) = clip_segment_to_aabb(
755 point,
756 direction,
757 ray_length,
758 &self.face_boxes[index].expanded(margin),
759 ) else {
760 continue;
761 };
762 let span_start = (span_start - margin).max(0.0);
763 let span_end = (span_end + margin).min(ray_length);
764 if span_end - span_start <= 1e-12 {
765 continue;
766 }
767 let sub_ray = make_line(
768 point.add(direction.scale(span_start)),
769 point.add(direction.scale(span_end)),
770 )?;
771 let csi_started = classify_profile_started();
772 let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
773 classify_profile(|p| {
774 p.ray_faces += 1;
775 p.ray_csi_ms += classify_elapsed_ms(csi_started);
776 });
777 for intersection in intersections {
778 if intersection.point.sub(point).length() <= on_tolerance {
779 let trim_started = classify_profile_started();
780 let trim = parameter_point_in_face(
781 face,
782 Vec2 {
783 x: intersection.u,
784 y: intersection.v,
785 },
786 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
787 )?;
788 classify_profile(|p| {
789 p.ray_trim_tests += 1;
790 p.ray_trim_ms += classify_elapsed_ms(trim_started);
791 });
792 if trim != PolygonClass::Outside {
793 return Ok(PointClassification {
794 class: PointClass::On,
795 on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
796 });
797 }
798 continue;
799 }
800 if intersection.tangential {
801 continue 'directions;
802 }
803 let trim_started = classify_profile_started();
804 let trim_class = metric_trim(face, intersection.u, intersection.v, on_tolerance)?;
805 classify_profile(|p| {
806 p.ray_trim_tests += 1;
807 p.ray_trim_ms += classify_elapsed_ms(trim_started);
808 });
809 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
810 eprintln!(
811 "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
812 direction.x, direction.y, direction.z,
813 face.id,
814 intersection.point.x, intersection.point.y, intersection.point.z,
815 intersection.point.sub(point).length(),
816 intersection.u, intersection.v,
817 trim_class
818 );
819 }
820 match trim_class {
821 PolygonClass::Boundary => continue 'directions,
822 PolygonClass::Inside => crossings += 1,
823 PolygonClass::Outside => {}
824 }
825 }
826 }
827 let verdict = if crossings % 2 == 1 {
828 PointClass::In
829 } else {
830 PointClass::Out
831 };
832 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
833 eprintln!(
834 "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
835 direction.x, direction.y, direction.z
836 );
837 }
838 if !require_agreement || verdicts.contains(&verdict) {
839 return Ok(PointClassification {
840 class: verdict,
841 on_normal: None,
842 });
843 }
844 verdicts.push(verdict);
845 }
846 if let Some(&verdict) = verdicts.last() {
850 return Ok(PointClassification {
851 class: verdict,
852 on_normal: None,
853 });
854 }
855 Err("classifyPointVsSolid: no clean ray direction found".into())
856 }
857
858 pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
876 self.coincident_caps = caps;
877 self
878 }
879
880 fn capped_band(&self, point: Vec3, band: f64) -> f64 {
883 self.coincident_caps
884 .iter()
885 .filter(|(region, _)| region.expanded(band).contains(point))
886 .fold(band, |band, &(_, cap)| band.min(cap * (1.0 - 1e-9)))
887 }
888
889 pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
890 let started = classify_profile_started();
891 let result = self.coincident_on_normal_inner(point);
892 classify_profile(|p| {
893 p.coincident_calls += 1;
894 p.coincident_ms += classify_elapsed_ms(started);
895 });
896 result
897 }
898
899 fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
900 let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
901 let band = self.capped_band(point, band);
905 if !self.bounds.expanded(band).contains(point) {
906 return Ok(None);
907 }
908 let mut candidates = Vec::new();
909 self.bvh.containing_point(point, band, &mut candidates);
910 let mut interior_normals: Vec<Vec3> = Vec::new();
911 for &index in &candidates {
912 let face = self.faces[index];
913 let projection = project_point_to_surface(&face.surface, point)?;
914 if projection.distance > band {
915 continue;
916 }
917 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
918 if let PolygonClass::Inside = parameter_point_in_face(
919 face,
920 Vec2 {
921 x: projection.u,
922 y: projection.v,
923 },
924 uv_tolerance,
925 )? {
926 interior_normals.push(face_normal(face, projection.u, projection.v)?);
927 }
928 }
929 if interior_normals.is_empty() {
930 return Ok(None);
931 }
932 let mut sum = Vec3::default();
933 for normal in &interior_normals {
934 sum = sum.add(*normal);
935 }
936 if sum.length() <= 1e-3 {
937 return Ok(None);
938 }
939 Ok(Some(sum.normalized()?))
940 }
941}
942
943pub fn classify_point(
944 point: Vec3,
945 solid: &BrepSolid,
946 tolerance: f64,
947) -> Result<PointClassification, String> {
948 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
949 classify_profile_begin();
950 let result = SolidClassifier::new(solid, tolerance)?.classify(point);
951 classify_profile_report("classify_point");
952 result
953}
954
955
956
957