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(crate) 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(crate) 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(crate) 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(crate) 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
180
181fn ray_face_intersections(
185 sub_ray: &NurbsCurve,
186 surface: &crate::NurbsSurface,
187 tolerance: f64,
188) -> Result<Vec<crate::CurveSurfaceIntersection>, String> {
189 if exact_ray_enabled() {
190 if let Some(seeds) = crate::exact_line_surface::exact_line_surface_seeds(sub_ray, surface, tolerance) {
191 classify_profile(|p| p.ray_exact_faces += 1);
192 return crate::curve_surface_intersection::intersect_curve_surface_from_seeds(sub_ray, surface, tolerance, seeds);
193 }
194 classify_profile(|p| p.ray_fallback_faces += 1);
195 }
196 intersect_curve_surface(sub_ray, surface, tolerance)
197}
198
199pub struct SolidClassifier<'a> {
204 faces: Vec<&'a FaceRecord>,
205 face_boxes: Vec<Aabb>,
206 bounds: Aabb,
207 bvh: Bvh,
208 tolerance: f64,
209}
210
211fn clip_segment_to_aabb(
215 start: Vec3,
216 direction: Vec3,
217 length: f64,
218 bounds: &Aabb,
219) -> Option<[f64; 2]> {
220 let mut s0 = 0.0f64;
221 let mut s1 = length;
222 for axis in 0..3 {
223 let (origin, delta, minimum, maximum) = match axis {
224 0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
225 1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
226 _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
227 };
228 if delta.abs() <= 1e-15 {
229 if origin < minimum || origin > maximum {
230 return None;
231 }
232 continue;
233 }
234 let mut near = (minimum - origin) / delta;
235 let mut far = (maximum - origin) / delta;
236 if near > far {
237 std::mem::swap(&mut near, &mut far);
238 }
239 s0 = s0.max(near);
240 s1 = s1.min(far);
241 if s0 > s1 {
242 return None;
243 }
244 }
245 Some([s0, s1])
246}
247
248impl<'a> SolidClassifier<'a> {
249 pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
250 let build_started = classify_profile_started();
251 let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
252 let face_boxes = faces
253 .iter()
254 .map(|face| Aabb::from_surface_controls(&face.surface))
255 .collect::<Result<Vec<_>, _>>()?;
256 let mut bounds = Aabb::empty();
257 for face_box in &face_boxes {
258 bounds.include(*face_box);
259 }
260 let bvh = Bvh::build(&face_boxes);
261 classify_profile(|p| {
262 p.classifier_builds += 1;
263 p.classifier_build_ms += classify_elapsed_ms(build_started);
264 });
265 Ok(Self {
266 faces,
267 face_boxes,
268 bounds,
269 bvh,
270 tolerance,
271 })
272 }
273
274 pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
280 let on_tolerance = self.tolerance * 10.0;
281 if !self.bounds.expanded(on_tolerance).contains(point) {
282 return Ok(false);
283 }
284 let mut candidates = Vec::new();
285 self.bvh
286 .containing_point(point, on_tolerance, &mut candidates);
287 for &index in &candidates {
288 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
289 if projection.distance <= on_tolerance {
290 return Ok(true);
291 }
292 }
293 Ok(false)
294 }
295
296 pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
305 if !self.bounds.expanded(band).contains(point) {
306 return Ok(false);
307 }
308 let mut candidates = Vec::new();
309 self.bvh.containing_point(point, band, &mut candidates);
310 for &index in &candidates {
311 let projection = project_point_to_surface(&self.faces[index].surface, point)?;
312 if projection.distance <= band {
313 return Ok(true);
314 }
315 }
316 Ok(false)
317 }
318
319 pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
320 classify_profile(|p| p.classify_calls += 1);
321 let tolerance = self.tolerance;
322 if !self.bounds.expanded(tolerance).contains(point) {
323 return Ok(PointClassification {
324 class: PointClass::Out,
325 on_normal: None,
326 });
327 }
328 let on_tolerance = tolerance * 10.0;
329 let mut candidates = Vec::new();
330 self.bvh
331 .containing_point(point, on_tolerance, &mut candidates);
332 candidates.sort_unstable();
333 let mut interior_normals: Vec<Vec3> = Vec::new();
340 let mut boundary_normals: Vec<Vec3> = Vec::new();
341 for &index in &candidates {
342 let face = self.faces[index];
343 let project_started = classify_profile_started();
344 let projection = project_point_to_surface(&face.surface, point)?;
345 classify_profile(|p| {
346 p.band_candidates += 1;
347 p.band_project_ms += classify_elapsed_ms(project_started);
348 });
349 if projection.distance > on_tolerance {
350 continue;
351 }
352 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
353 let trim_started = classify_profile_started();
354 let trim = parameter_point_in_face(
355 face,
356 Vec2 {
357 x: projection.u,
358 y: projection.v,
359 },
360 uv_tolerance,
361 )?;
362 classify_profile(|p| {
363 p.band_trim_tests += 1;
364 p.band_trim_ms += classify_elapsed_ms(trim_started);
365 });
366 match trim {
367 PolygonClass::Inside => {
368 interior_normals.push(face_normal(face, projection.u, projection.v)?)
369 }
370 PolygonClass::Boundary => {
371 boundary_normals.push(face_normal(face, projection.u, projection.v)?)
372 }
373 PolygonClass::Outside => {}
374 }
375 }
376 let pool = if interior_normals.is_empty() {
377 &boundary_normals
378 } else {
379 &interior_normals
380 };
381 if !pool.is_empty() {
382 let mut sum = Vec3::default();
383 for normal in pool {
384 sum = sum.add(*normal);
385 }
386 if sum.length() > 1e-3 {
390 return Ok(PointClassification {
391 class: PointClass::On,
392 on_normal: Some(sum.normalized()?),
393 });
394 }
395 }
396 let directions = [
397 Vec3::new(0.577215, 0.618034, 0.532088),
398 Vec3::new(-0.707107, 0.267949, 0.654321),
399 Vec3::new(0.316228, -0.741657, 0.585786),
400 Vec3::new(-0.414214, -0.552786, -0.723607),
401 Vec3::new(0.9482, 0.11893, -0.29456),
402 Vec3::new(-0.13947, 0.90271, -0.40718),
403 Vec3::new(0.62361, -0.33912, -0.70414),
404 Vec3::new(0.20912, 0.51293, 0.83261),
405 ];
406 let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
407 let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
417 let mut verdicts: Vec<PointClass> = Vec::new();
418 'directions: for direction in directions {
419 classify_profile(|p| p.rays += 1);
420 let direction = direction.normalized()?;
421 let ray_end = point.add(direction.scale(ray_length));
422 candidates.clear();
423 self.bvh
424 .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
425 candidates.sort_unstable();
426 let mut crossings = 0;
427 for &index in &candidates {
428 let face = self.faces[index];
429 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
439 let Some([span_start, span_end]) = clip_segment_to_aabb(
440 point,
441 direction,
442 ray_length,
443 &self.face_boxes[index].expanded(margin),
444 ) else {
445 continue;
446 };
447 let span_start = (span_start - margin).max(0.0);
448 let span_end = (span_end + margin).min(ray_length);
449 if span_end - span_start <= 1e-12 {
450 continue;
451 }
452 let sub_ray = make_line(
453 point.add(direction.scale(span_start)),
454 point.add(direction.scale(span_end)),
455 )?;
456 let csi_started = classify_profile_started();
457 let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
458 classify_profile(|p| {
459 p.ray_faces += 1;
460 p.ray_csi_ms += classify_elapsed_ms(csi_started);
461 });
462 for intersection in intersections {
463 if intersection.point.sub(point).length() <= tolerance * 10.0 {
464 let trim_started = classify_profile_started();
465 let trim = parameter_point_in_face(
466 face,
467 Vec2 {
468 x: intersection.u,
469 y: intersection.v,
470 },
471 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
472 )?;
473 classify_profile(|p| {
474 p.ray_trim_tests += 1;
475 p.ray_trim_ms += classify_elapsed_ms(trim_started);
476 });
477 if trim != PolygonClass::Outside {
478 return Ok(PointClassification {
479 class: PointClass::On,
480 on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
481 });
482 }
483 continue;
484 }
485 if intersection.tangential {
486 continue 'directions;
487 }
488 let trim_started = classify_profile_started();
489 let trim_class = parameter_point_in_face(
490 face,
491 Vec2 {
492 x: intersection.u,
493 y: intersection.v,
494 },
495 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
496 )?;
497 classify_profile(|p| {
498 p.ray_trim_tests += 1;
499 p.ray_trim_ms += classify_elapsed_ms(trim_started);
500 });
501 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
502 eprintln!(
503 "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
504 direction.x, direction.y, direction.z,
505 face.id,
506 intersection.point.x, intersection.point.y, intersection.point.z,
507 intersection.point.sub(point).length(),
508 intersection.u, intersection.v,
509 trim_class
510 );
511 }
512 match trim_class {
513 PolygonClass::Boundary => continue 'directions,
514 PolygonClass::Inside => crossings += 1,
515 PolygonClass::Outside => {}
516 }
517 }
518 }
519 let verdict = if crossings % 2 == 1 {
520 PointClass::In
521 } else {
522 PointClass::Out
523 };
524 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
525 eprintln!(
526 "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
527 direction.x, direction.y, direction.z
528 );
529 }
530 if !require_agreement || verdicts.contains(&verdict) {
531 return Ok(PointClassification {
532 class: verdict,
533 on_normal: None,
534 });
535 }
536 verdicts.push(verdict);
537 }
538 if let Some(&verdict) = verdicts.last() {
542 return Ok(PointClassification {
543 class: verdict,
544 on_normal: None,
545 });
546 }
547 Err("classifyPointVsSolid: no clean ray direction found".into())
548 }
549
550 pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
565 let started = classify_profile_started();
566 let result = self.coincident_on_normal_inner(point);
567 classify_profile(|p| {
568 p.coincident_calls += 1;
569 p.coincident_ms += classify_elapsed_ms(started);
570 });
571 result
572 }
573
574 fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
575 let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
576 if !self.bounds.expanded(band).contains(point) {
577 return Ok(None);
578 }
579 let mut candidates = Vec::new();
580 self.bvh.containing_point(point, band, &mut candidates);
581 let mut interior_normals: Vec<Vec3> = Vec::new();
582 for &index in &candidates {
583 let face = self.faces[index];
584 let projection = project_point_to_surface(&face.surface, point)?;
585 if projection.distance > band {
586 continue;
587 }
588 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
589 if let PolygonClass::Inside = parameter_point_in_face(
590 face,
591 Vec2 {
592 x: projection.u,
593 y: projection.v,
594 },
595 uv_tolerance,
596 )? {
597 interior_normals.push(face_normal(face, projection.u, projection.v)?);
598 }
599 }
600 if interior_normals.is_empty() {
601 return Ok(None);
602 }
603 let mut sum = Vec3::default();
604 for normal in &interior_normals {
605 sum = sum.add(*normal);
606 }
607 if sum.length() <= 1e-3 {
608 return Ok(None);
609 }
610 Ok(Some(sum.normalized()?))
611 }
612}
613
614pub fn classify_point(
615 point: Vec3,
616 solid: &BrepSolid,
617 tolerance: f64,
618) -> Result<PointClassification, String> {
619 classify_profile_begin();
620 let result = SolidClassifier::new(solid, tolerance)?.classify(point);
621 classify_profile_report("classify_point");
622 result
623}