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 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
321 classify_profile(|p| p.classify_calls += 1);
322 let tolerance = self.tolerance;
323 if !self.bounds.expanded(tolerance).contains(point) {
324 return Ok(PointClassification {
325 class: PointClass::Out,
326 on_normal: None,
327 });
328 }
329 let on_tolerance = tolerance * 10.0;
330 let mut candidates = Vec::new();
331 self.bvh
332 .containing_point(point, on_tolerance, &mut candidates);
333 candidates.sort_unstable();
334 let mut interior_normals: Vec<Vec3> = Vec::new();
341 let mut boundary_normals: Vec<Vec3> = Vec::new();
342 for &index in &candidates {
343 let face = self.faces[index];
344 let project_started = classify_profile_started();
345 let projection = project_point_to_surface(&face.surface, point)?;
346 classify_profile(|p| {
347 p.band_candidates += 1;
348 p.band_project_ms += classify_elapsed_ms(project_started);
349 });
350 if projection.distance > on_tolerance {
351 continue;
352 }
353 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
354 let trim_started = classify_profile_started();
355 let trim = parameter_point_in_face(
356 face,
357 Vec2 {
358 x: projection.u,
359 y: projection.v,
360 },
361 uv_tolerance,
362 )?;
363 classify_profile(|p| {
364 p.band_trim_tests += 1;
365 p.band_trim_ms += classify_elapsed_ms(trim_started);
366 });
367 match trim {
368 PolygonClass::Inside => {
369 interior_normals.push(face_normal(face, projection.u, projection.v)?)
370 }
371 PolygonClass::Boundary => {
372 boundary_normals.push(face_normal(face, projection.u, projection.v)?)
373 }
374 PolygonClass::Outside => {}
375 }
376 }
377 let pool = if interior_normals.is_empty() {
378 &boundary_normals
379 } else {
380 &interior_normals
381 };
382 if !pool.is_empty() {
383 let mut sum = Vec3::default();
384 for normal in pool {
385 sum = sum.add(*normal);
386 }
387 if sum.length() > 1e-3 {
391 return Ok(PointClassification {
392 class: PointClass::On,
393 on_normal: Some(sum.normalized()?),
394 });
395 }
396 }
397 let directions = [
398 Vec3::new(0.577215, 0.618034, 0.532088),
399 Vec3::new(-0.707107, 0.267949, 0.654321),
400 Vec3::new(0.316228, -0.741657, 0.585786),
401 Vec3::new(-0.414214, -0.552786, -0.723607),
402 Vec3::new(0.9482, 0.11893, -0.29456),
403 Vec3::new(-0.13947, 0.90271, -0.40718),
404 Vec3::new(0.62361, -0.33912, -0.70414),
405 Vec3::new(0.20912, 0.51293, 0.83261),
406 ];
407 let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
408 let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
418 let mut verdicts: Vec<PointClass> = Vec::new();
419 'directions: for direction in directions {
420 classify_profile(|p| p.rays += 1);
421 let direction = direction.normalized()?;
422 let ray_end = point.add(direction.scale(ray_length));
423 candidates.clear();
424 self.bvh
425 .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
426 candidates.sort_unstable();
427 let mut crossings = 0;
428 for &index in &candidates {
429 let face = self.faces[index];
430 let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
440 let Some([span_start, span_end]) = clip_segment_to_aabb(
441 point,
442 direction,
443 ray_length,
444 &self.face_boxes[index].expanded(margin),
445 ) else {
446 continue;
447 };
448 let span_start = (span_start - margin).max(0.0);
449 let span_end = (span_end + margin).min(ray_length);
450 if span_end - span_start <= 1e-12 {
451 continue;
452 }
453 let sub_ray = make_line(
454 point.add(direction.scale(span_start)),
455 point.add(direction.scale(span_end)),
456 )?;
457 let csi_started = classify_profile_started();
458 let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
459 classify_profile(|p| {
460 p.ray_faces += 1;
461 p.ray_csi_ms += classify_elapsed_ms(csi_started);
462 });
463 for intersection in intersections {
464 if intersection.point.sub(point).length() <= tolerance * 10.0 {
465 let trim_started = classify_profile_started();
466 let trim = parameter_point_in_face(
467 face,
468 Vec2 {
469 x: intersection.u,
470 y: intersection.v,
471 },
472 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
473 )?;
474 classify_profile(|p| {
475 p.ray_trim_tests += 1;
476 p.ray_trim_ms += classify_elapsed_ms(trim_started);
477 });
478 if trim != PolygonClass::Outside {
479 return Ok(PointClassification {
480 class: PointClass::On,
481 on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
482 });
483 }
484 continue;
485 }
486 if intersection.tangential {
487 continue 'directions;
488 }
489 let trim_started = classify_profile_started();
490 let trim_class = parameter_point_in_face(
491 face,
492 Vec2 {
493 x: intersection.u,
494 y: intersection.v,
495 },
496 face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
497 )?;
498 classify_profile(|p| {
499 p.ray_trim_tests += 1;
500 p.ray_trim_ms += classify_elapsed_ms(trim_started);
501 });
502 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
503 eprintln!(
504 "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
505 direction.x, direction.y, direction.z,
506 face.id,
507 intersection.point.x, intersection.point.y, intersection.point.z,
508 intersection.point.sub(point).length(),
509 intersection.u, intersection.v,
510 trim_class
511 );
512 }
513 match trim_class {
514 PolygonClass::Boundary => continue 'directions,
515 PolygonClass::Inside => crossings += 1,
516 PolygonClass::Outside => {}
517 }
518 }
519 }
520 let verdict = if crossings % 2 == 1 {
521 PointClass::In
522 } else {
523 PointClass::Out
524 };
525 if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
526 eprintln!(
527 "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
528 direction.x, direction.y, direction.z
529 );
530 }
531 if !require_agreement || verdicts.contains(&verdict) {
532 return Ok(PointClassification {
533 class: verdict,
534 on_normal: None,
535 });
536 }
537 verdicts.push(verdict);
538 }
539 if let Some(&verdict) = verdicts.last() {
543 return Ok(PointClassification {
544 class: verdict,
545 on_normal: None,
546 });
547 }
548 Err("classifyPointVsSolid: no clean ray direction found".into())
549 }
550
551 pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
566 let started = classify_profile_started();
567 let result = self.coincident_on_normal_inner(point);
568 classify_profile(|p| {
569 p.coincident_calls += 1;
570 p.coincident_ms += classify_elapsed_ms(started);
571 });
572 result
573 }
574
575 fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
576 let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
577 if !self.bounds.expanded(band).contains(point) {
578 return Ok(None);
579 }
580 let mut candidates = Vec::new();
581 self.bvh.containing_point(point, band, &mut candidates);
582 let mut interior_normals: Vec<Vec3> = Vec::new();
583 for &index in &candidates {
584 let face = self.faces[index];
585 let projection = project_point_to_surface(&face.surface, point)?;
586 if projection.distance > band {
587 continue;
588 }
589 let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
590 if let PolygonClass::Inside = parameter_point_in_face(
591 face,
592 Vec2 {
593 x: projection.u,
594 y: projection.v,
595 },
596 uv_tolerance,
597 )? {
598 interior_normals.push(face_normal(face, projection.u, projection.v)?);
599 }
600 }
601 if interior_normals.is_empty() {
602 return Ok(None);
603 }
604 let mut sum = Vec3::default();
605 for normal in &interior_normals {
606 sum = sum.add(*normal);
607 }
608 if sum.length() <= 1e-3 {
609 return Ok(None);
610 }
611 Ok(Some(sum.normalized()?))
612 }
613}
614
615pub fn classify_point(
616 point: Vec3,
617 solid: &BrepSolid,
618 tolerance: f64,
619) -> Result<PointClassification, String> {
620 let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
621 classify_profile_begin();
622 let result = SolidClassifier::new(solid, tolerance)?.classify(point);
623 classify_profile_report("classify_point");
624 result
625}