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 face_uv_tolerance(face: &FaceRecord, u: f64, v: f64, spatial: f64) -> f64 {
53 surface_uv_band(&face.surface, u, v, spatial)
54}
55
56pub fn surface_uv_band(surface: &crate::NurbsSurface, u: f64, v: f64, spatial: f64) -> f64 {
58 let Ok(derivatives) = surface.derivatives(u, v, 1) else {
59 return spatial;
60 };
61 let band = crate::tolerance::surface_uv_tolerance(
62 spatial,
63 derivatives[1][0].length(),
64 derivatives[0][1].length(),
65 );
66 let cap = match (surface.domain_u(), surface.domain_v()) {
67 (Ok([u0, u1]), Ok([v0, v1])) => ((u1 - u0).min(v1 - v0) * 0.05).max(1e-12),
68 _ => f64::INFINITY,
69 };
70 band.min(cap)
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
74#[serde(rename_all = "lowercase")]
75pub enum PointClass {
76 In,
77 Out,
78 On,
79}
80
81#[derive(Clone, Copy, Debug, Serialize)]
82pub struct PointClassification {
83 pub class: PointClass,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub on_normal: Option<Vec3>,
86}
87
88#[derive(Default, Clone, Copy)]
95pub struct ClassifyProfile {
96 pub enabled: bool,
97 pub classify_calls: u64,
98 pub band_candidates: u64,
99 pub band_project_ms: f64,
100 pub band_trim_tests: u64,
101 pub band_trim_ms: f64,
102 pub rays: u64,
103 pub ray_faces: u64,
104 pub ray_csi_ms: f64,
105 pub ray_exact_faces: u64,
108 pub ray_fallback_faces: u64,
109 pub ray_trim_tests: u64,
110 pub ray_trim_ms: f64,
111 pub coincident_calls: u64,
112 pub coincident_ms: f64,
113 pub classifier_builds: u64,
114 pub classifier_build_ms: f64,
115}
116
117thread_local! {
118 static CLASSIFY_PROFILE: std::cell::Cell<ClassifyProfile> =
119 const { std::cell::Cell::new(ClassifyProfile {
120 enabled: false, classify_calls: 0, band_candidates: 0, band_project_ms: 0.0,
121 band_trim_tests: 0, band_trim_ms: 0.0, rays: 0, ray_faces: 0, ray_csi_ms: 0.0,
122 ray_exact_faces: 0, ray_fallback_faces: 0, ray_trim_tests: 0, ray_trim_ms: 0.0, coincident_calls: 0, coincident_ms: 0.0,
123 classifier_builds: 0, classifier_build_ms: 0.0,
124 }) };
125}
126
127impl crate::profile::Counters for ClassifyProfile {
128 fn armed(&self) -> bool {
129 self.enabled
130 }
131}
132
133fn classify_profile(update: impl FnOnce(&mut ClassifyProfile)) {
134 crate::profile::update(&CLASSIFY_PROFILE, update)
135}
136
137fn classify_profile_started() -> Option<web_time::Instant> {
138 crate::profile::started(&CLASSIFY_PROFILE)
139}
140
141use crate::profile::elapsed_ms as classify_elapsed_ms;
142
143pub fn classify_profile_begin() {
145 let enabled = crate::profile::profile_enabled();
146 CLASSIFY_PROFILE.with(|cell| {
147 cell.set(ClassifyProfile {
148 enabled,
149 ..ClassifyProfile::default()
150 })
151 });
152}
153
154pub fn classify_profile_report(label: &str) {
157 let p = CLASSIFY_PROFILE.with(|cell| cell.get());
158 if !p.enabled {
159 return;
160 }
161 profile_line!(
162 "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}",
163 p.classify_calls, p.classifier_builds, p.classifier_build_ms, p.band_candidates,
164 p.band_project_ms, p.band_trim_tests, p.band_trim_ms, p.rays, p.ray_faces,
165 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,
166 );
167 CLASSIFY_PROFILE.with(|cell| cell.set(ClassifyProfile::default()));
168}
169
170fn exact_ray_enabled() -> bool {
177 switch!("BREP_CLASSIFY_EXACT_RAY", true)
178}
179
180fn ray_face_intersections(
184 sub_ray: &NurbsCurve,
185 surface: &crate::NurbsSurface,
186 tolerance: f64,
187) -> Result<Vec<crate::CurveSurfaceIntersection>, String> {
188 if exact_ray_enabled() {
189 if let Some(seeds) = crate::exact_line_surface::exact_line_surface_seeds(sub_ray, surface, tolerance) {
190 classify_profile(|p| p.ray_exact_faces += 1);
191 return crate::curve_surface_intersection::intersect_curve_surface_from_seeds(sub_ray, surface, tolerance, seeds);
192 }
193 classify_profile(|p| p.ray_fallback_faces += 1);
194 }
195 let check = crate::curve_clear::check_mode();
198 if check || ray_clear_enabled() {
199 let clear = crate::curve_clear::curve_clear_of_surface(sub_ray, surface, tolerance);
200 if check {
201 let hits = intersect_curve_surface(sub_ray, surface, tolerance)?;
202 if clear && !hits.is_empty() {
203 crate::curve_clear::disagreement("classifier ray", hits.len());
204 }
205 return Ok(hits);
206 }
207 if clear {
208 return Ok(Vec::new());
209 }
210 }
211 crate::curve_surface_intersection::intersect_ray_surface(sub_ray, surface, tolerance)
212}
213
214fn ray_clear_enabled() -> bool {
218 switch!("BREP_CLASSIFY_RAY_CLEAR", true)
219}
220
221pub struct SolidClassifier<'a> {
226 faces: Vec<&'a FaceRecord>,
227 face_boxes: Vec<Aabb>,
228 bounds: Aabb,
229 bvh: Bvh,
230 tolerance: f64,
231 coincident_caps: Vec<(Aabb, f64)>,
235}
236
237fn clip_segment_to_aabb(
241 start: Vec3,
242 direction: Vec3,
243 length: f64,
244 bounds: &Aabb,
245) -> Option<[f64; 2]> {
246 let mut s0 = 0.0f64;
247 let mut s1 = length;
248 for axis in 0..3 {
249 let (origin, delta, minimum, maximum) = match axis {
250 0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
251 1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
252 _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
253 };
254 if delta.abs() <= 1e-15 {
255 if origin < minimum || origin > maximum {
256 return None;
257 }
258 continue;
259 }
260 let mut near = (minimum - origin) / delta;
261 let mut far = (maximum - origin) / delta;
262 if near > far {
263 std::mem::swap(&mut near, &mut far);
264 }
265 s0 = s0.max(near);
266 s1 = s1.min(far);
267 if s0 > s1 {
268 return None;
269 }
270 }
271 Some([s0, s1])
272}
273
274impl<'a> SolidClassifier<'a> {
275 pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
276 let build_started = classify_profile_started();
277 let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
278 let face_boxes = faces
279 .iter()
280 .map(|face| Aabb::from_surface_controls(&face.surface))
281 .collect::<Result<Vec<_>, _>>()?;
282 let mut bounds = Aabb::empty();
283 for face_box in &face_boxes {
284 bounds.include(*face_box);
285 }
286 let bvh = Bvh::build(&face_boxes);
287 classify_profile(|p| {
288 p.classifier_builds += 1;
289 p.classifier_build_ms += classify_elapsed_ms(build_started);
290 });
291 Ok(Self {
292 faces,
293 face_boxes,
294 bounds,
295 bvh,
296 tolerance,
297 coincident_caps: Vec::new(),
298 })
299 }
300
301 pub fn chord_orientation(&self, through: Vec3, direction: Vec3) -> Result<Option<bool>, String> {
317 let on_tolerance = self.tolerance * 10.0;
318 let direction = direction.normalized()?;
319 let middle = self.bounds.minimum.add(self.bounds.maximum).scale(0.5);
320 let reach = self.bounds.diagonal() + through.sub(middle).length() + 1.0;
321 let start = through.sub(direction.scale(reach));
322 let length = 2.0 * reach;
323 let end = start.add(direction.scale(length));
324 let mut candidates = Vec::new();
325 self.bvh.intersecting_segment(start, end, on_tolerance, &mut candidates);
326 candidates.sort_unstable();
327 let mut hits: Vec<(f64, bool)> = Vec::new();
329 let mut aimed = false;
330 for &index in &candidates {
331 let face = self.faces[index];
332 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
333 let Some([span_start, span_end]) =
334 clip_segment_to_aabb(start, direction, length, &self.face_boxes[index].expanded(margin))
335 else {
336 continue;
337 };
338 let span_start = (span_start - margin).max(0.0);
339 let span_end = (span_end + margin).min(length);
340 if span_end - span_start <= 1e-12 {
341 continue;
342 }
343 let sub_ray = make_line(start.add(direction.scale(span_start)), start.add(direction.scale(span_end)))?;
344 for intersection in ray_face_intersections(&sub_ray, &face.surface, self.tolerance)? {
345 if intersection.tangential {
346 return Ok(None);
347 }
348 let uv = Vec2 { x: intersection.u, y: intersection.v };
349 match parameter_point_in_face(face, uv, face_uv_tolerance(face, uv.x, uv.y, on_tolerance))? {
350 PolygonClass::Outside => continue,
351 PolygonClass::Boundary => return Ok(None),
352 PolygonClass::Inside => {}
353 }
354 let along = face_normal(face, uv.x, uv.y)?.dot(direction);
355 if along.abs() < 1e-2 {
356 return Ok(None);
357 }
358 if intersection.point.sub(through).length() <= on_tolerance {
359 aimed = true;
360 }
361 hits.push((intersection.point.sub(start).dot(direction), along > 0.0));
362 }
363 }
364 if !aimed || hits.is_empty() || hits.len() % 2 == 1 {
365 return Ok(None);
366 }
367 hits.sort_by(|a, b| a.0.total_cmp(&b.0));
368 for pair in hits.windows(2) {
369 if pair[1].0 - pair[0].0 <= on_tolerance || pair[1].1 == pair[0].1 {
370 return Ok(None);
371 }
372 }
373 Ok(Some(!hits[0].1))
374 }
375
376 pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
382 let on_tolerance = self.tolerance * 10.0;
383 if !self.bounds.expanded(on_tolerance).contains(point) {
384 return Ok(false);
385 }
386 let mut candidates = Vec::new();
387 self.bvh
388 .containing_point(point, on_tolerance, &mut candidates);
389 for &index in &candidates {
390 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
391 if projection.distance <= on_tolerance {
392 return Ok(true);
393 }
394 }
395 Ok(false)
396 }
397
398 pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
407 if !self.bounds.expanded(band).contains(point) {
408 return Ok(false);
409 }
410 let mut candidates = Vec::new();
411 self.bvh.containing_point(point, band, &mut candidates);
412 for &index in &candidates {
413 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
414 if projection.distance <= band {
415 return Ok(true);
416 }
417 }
418 Ok(false)
419 }
420
421 pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
422 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
423 classify_profile(|p| p.classify_calls += 1);
424 let tolerance = self.tolerance;
425 if !self.bounds.expanded(tolerance).contains(point) {
426 return Ok(PointClassification {
427 class: PointClass::Out,
428 on_normal: None,
429 });
430 }
431 let on_tolerance = self.capped_band(point, tolerance * 10.0);
435 if !self.coincident_caps.is_empty() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
436 eprintln!("feature_scale: classify at {point:?} on band {on_tolerance:.3e} (uncapped {:.3e}, {} caps)", tolerance * 10.0, self.coincident_caps.len());
437 }
438 let mut candidates = Vec::new();
439 self.bvh
440 .containing_point(point, on_tolerance, &mut candidates);
441 candidates.sort_unstable();
442 let mut interior_normals: Vec<Vec3> = Vec::new();
449 let mut boundary_normals: Vec<Vec3> = Vec::new();
450 for &index in &candidates {
451 let face = self.faces[index];
452 let project_started = classify_profile_started();
453 let projection = project_point_to_surface(&face.surface, point)?;
454 classify_profile(|p| {
455 p.band_candidates += 1;
456 p.band_project_ms += classify_elapsed_ms(project_started);
457 });
458 if projection.distance > on_tolerance {
459 continue;
460 }
461 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
462 let trim_started = classify_profile_started();
463 let trim = parameter_point_in_face(
464 face,
465 Vec2 {
466 x: projection.u,
467 y: projection.v,
468 },
469 uv_tolerance,
470 )?;
471 classify_profile(|p| {
472 p.band_trim_tests += 1;
473 p.band_trim_ms += classify_elapsed_ms(trim_started);
474 });
475 match trim {
476 PolygonClass::Inside => {
477 interior_normals.push(face_normal(face, projection.u, projection.v)?)
478 }
479 PolygonClass::Boundary => {
480 boundary_normals.push(face_normal(face, projection.u, projection.v)?)
481 }
482 PolygonClass::Outside => {}
483 }
484 }
485 let pool = if interior_normals.is_empty() {
486 &boundary_normals
487 } else {
488 &interior_normals
489 };
490 if !pool.is_empty() {
491 let mut sum = Vec3::default();
492 for normal in pool {
493 sum = sum.add(*normal);
494 }
495 if sum.length() > 1e-3 {
499 return Ok(PointClassification {
500 class: PointClass::On,
501 on_normal: Some(sum.normalized()?),
502 });
503 }
504 }
505 let directions = [
506 Vec3::new(0.577215, 0.618034, 0.532088),
507 Vec3::new(-0.707107, 0.267949, 0.654321),
508 Vec3::new(0.316228, -0.741657, 0.585786),
509 Vec3::new(-0.414214, -0.552786, -0.723607),
510 Vec3::new(0.9482, 0.11893, -0.29456),
511 Vec3::new(-0.13947, 0.90271, -0.40718),
512 Vec3::new(0.62361, -0.33912, -0.70414),
513 Vec3::new(0.20912, 0.51293, 0.83261),
514 ];
515 let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
516 let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
526 let mut verdicts: Vec<PointClass> = Vec::new();
527 'directions: for direction in directions {
528 classify_profile(|p| p.rays += 1);
529 let direction = direction.normalized()?;
530 let ray_end = point.add(direction.scale(ray_length));
531 candidates.clear();
532 self.bvh
533 .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
534 candidates.sort_unstable();
535 let mut crossings = 0;
536 for &index in &candidates {
537 let face = self.faces[index];
538 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
548 let Some([span_start, span_end]) = clip_segment_to_aabb(
549 point,
550 direction,
551 ray_length,
552 &self.face_boxes[index].expanded(margin),
553 ) else {
554 continue;
555 };
556 let span_start = (span_start - margin).max(0.0);
557 let span_end = (span_end + margin).min(ray_length);
558 if span_end - span_start <= 1e-12 {
559 continue;
560 }
561 let sub_ray = make_line(
562 point.add(direction.scale(span_start)),
563 point.add(direction.scale(span_end)),
564 )?;
565 let csi_started = classify_profile_started();
566 let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
567 classify_profile(|p| {
568 p.ray_faces += 1;
569 p.ray_csi_ms += classify_elapsed_ms(csi_started);
570 });
571 for intersection in intersections {
572 if intersection.point.sub(point).length() <= on_tolerance {
573 let trim_started = classify_profile_started();
574 let trim = parameter_point_in_face(
575 face,
576 Vec2 {
577 x: intersection.u,
578 y: intersection.v,
579 },
580 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
581 )?;
582 classify_profile(|p| {
583 p.ray_trim_tests += 1;
584 p.ray_trim_ms += classify_elapsed_ms(trim_started);
585 });
586 if trim != PolygonClass::Outside {
587 return Ok(PointClassification {
588 class: PointClass::On,
589 on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
590 });
591 }
592 continue;
593 }
594 if intersection.tangential {
595 continue 'directions;
596 }
597 let trim_started = classify_profile_started();
598 let trim_class = parameter_point_in_face(
599 face,
600 Vec2 {
601 x: intersection.u,
602 y: intersection.v,
603 },
604 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
605 )?;
606 classify_profile(|p| {
607 p.ray_trim_tests += 1;
608 p.ray_trim_ms += classify_elapsed_ms(trim_started);
609 });
610 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
611 eprintln!(
612 "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
613 direction.x, direction.y, direction.z,
614 face.id,
615 intersection.point.x, intersection.point.y, intersection.point.z,
616 intersection.point.sub(point).length(),
617 intersection.u, intersection.v,
618 trim_class
619 );
620 }
621 match trim_class {
622 PolygonClass::Boundary => continue 'directions,
623 PolygonClass::Inside => crossings += 1,
624 PolygonClass::Outside => {}
625 }
626 }
627 }
628 let verdict = if crossings % 2 == 1 {
629 PointClass::In
630 } else {
631 PointClass::Out
632 };
633 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
634 eprintln!(
635 "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
636 direction.x, direction.y, direction.z
637 );
638 }
639 if !require_agreement || verdicts.contains(&verdict) {
640 return Ok(PointClassification {
641 class: verdict,
642 on_normal: None,
643 });
644 }
645 verdicts.push(verdict);
646 }
647 if let Some(&verdict) = verdicts.last() {
651 return Ok(PointClassification {
652 class: verdict,
653 on_normal: None,
654 });
655 }
656 Err("classifyPointVsSolid: no clean ray direction found".into())
657 }
658
659 pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
677 self.coincident_caps = caps;
678 self
679 }
680
681 fn capped_band(&self, point: Vec3, band: f64) -> f64 {
684 self.coincident_caps
685 .iter()
686 .filter(|(region, _)| region.expanded(band).contains(point))
687 .fold(band, |band, &(_, cap)| band.min(cap * (1.0 - 1e-9)))
688 }
689
690 pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
691 let started = classify_profile_started();
692 let result = self.coincident_on_normal_inner(point);
693 classify_profile(|p| {
694 p.coincident_calls += 1;
695 p.coincident_ms += classify_elapsed_ms(started);
696 });
697 result
698 }
699
700 fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
701 let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
702 let band = self.capped_band(point, band);
706 if !self.bounds.expanded(band).contains(point) {
707 return Ok(None);
708 }
709 let mut candidates = Vec::new();
710 self.bvh.containing_point(point, band, &mut candidates);
711 let mut interior_normals: Vec<Vec3> = Vec::new();
712 for &index in &candidates {
713 let face = self.faces[index];
714 let projection = project_point_to_surface(&face.surface, point)?;
715 if projection.distance > band {
716 continue;
717 }
718 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
719 if let PolygonClass::Inside = parameter_point_in_face(
720 face,
721 Vec2 {
722 x: projection.u,
723 y: projection.v,
724 },
725 uv_tolerance,
726 )? {
727 interior_normals.push(face_normal(face, projection.u, projection.v)?);
728 }
729 }
730 if interior_normals.is_empty() {
731 return Ok(None);
732 }
733 let mut sum = Vec3::default();
734 for normal in &interior_normals {
735 sum = sum.add(*normal);
736 }
737 if sum.length() <= 1e-3 {
738 return Ok(None);
739 }
740 Ok(Some(sum.normalized()?))
741 }
742}
743
744pub fn classify_point(
745 point: Vec3,
746 solid: &BrepSolid,
747 tolerance: f64,
748) -> Result<PointClassification, String> {
749 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
750 classify_profile_begin();
751 let result = SolidClassifier::new(solid, tolerance)?.classify(point);
752 classify_profile_report("classify_point");
753 result
754}
755