Skip to main content

brep_topology/brep/classification/
solid_classifier.rs

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            // POLE RESCUE: at a collapsed parameterization pole (sphere pole,
8            // cone apex) du×dv vanishes and `normal()` errors — which used to
9            // propagate and kill the ENTIRE boolean (trial 9: a sphere placed
10            // TANGENT at its pole dies with "Vec3.normalized: zero-length
11            // vector" before any fragment is classified). The GEOMETRIC
12            // normal is well-defined and continuous there; recover it by
13            // stepping slightly inside the domain (at the pole every azimuth
14            // shares the same limit normal, so the offset direction does not
15            // matter). Escape hatch: BREP_POLE_NORMAL_RESCUE=0.
16            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
47/// UV band equivalent to a spatial band of `spatial` at (u, v), derived
48/// from the local surface derivative magnitudes (`tolerance.rs`
49/// `surface_uv_tolerance`).  Capped to a fraction of the smaller domain
50/// span so a pole or collapsed direction cannot widen the band into the
51/// whole face.
52/// `BREP_CLASSIFY_THIN_BODY_BAND` (default on, `=0` off): see
53/// [`SolidClassifier::classify`].
54fn thin_body_band_enabled() -> bool {
55    crate::switch!("BREP_CLASSIFY_THIN_BODY_BAND", true)
56}
57
58/// `BREP_CLASSIFY_THIN_BODY_BAND_CHECK` (default off, `=1` on): measure the
59/// thin-body band and report where it would change the answer, keeping it.
60fn 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
68/// [`face_uv_tolerance`] for a bare carrier.
69pub 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
85/// `BREP_CLASSIFY_METRIC_TRIM` (default on; `=0` reads the isotropic band as
86/// before): see [`metric_trim`].
87fn metric_trim_enabled() -> bool {
88    switch!("BREP_CLASSIFY_METRIC_TRIM", true)
89}
90
91/// `BREP_CLASSIFY_METRIC_TRIM_CHECK` (default off): compute the old read and
92/// the metric read side by side and print each ray hit where they differ.
93fn metric_trim_check() -> bool {
94    switch!("BREP_CLASSIFY_METRIC_TRIM_CHECK", false)
95}
96
97/// The trim read of a ray's crossing at `(u, v)`, with its `Boundary` band
98/// measured in space along each parameter direction. [`face_uv_tolerance`]
99/// is one uv radius, `spatial / min(|Su|, |Sv|)`: on a wall 5e-3 tall and a
100/// dozen long (|Su| 11, |Sv| 8.8e-3) a 1e-6 band read 1.1e-4 in u, 1.25e-3 in
101/// space, and every ray from a point within a millimetre of the wall's corner
102/// edge read `Boundary` there and gave up ("no clean ray direction").
103///
104/// The spatial band is the ellipse with semi-axes `spatial / |Su|` and
105/// `spatial / |Sv|` about the hit. When the two differ by more than 4×, a hit
106/// the isotropic band reads `Boundary` is read again with the ellipse's minor
107/// radius at its centre and at its eight tips every 45°. It stays `Boundary`
108/// unless all nine reads agree on one side. A straight trim within the
109/// ellipse misses all nine only if it cuts off a cap between two tips, at
110/// least `cos 22.5°` (0.92) of the band from the hit. Hits on a near-isotropic
111/// chart and hits the old band reads `Inside` or `Outside` read as before.
112fn 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/// Per-thread counters for the classifier, printed by
169/// [`classify_profile_report`] when `BREP_PROFILE` is set: how many point
170/// queries ran, how many face projections and trim tests the On band cost,
171/// how many rays were cast and how many face intersections and trim tests
172/// they cost, and the wall time of each part. When the switch is off every
173/// counter is one thread-local flag test.
174#[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    /// Ray-face intersections the exact lane seeded (`exact_ray_enabled`) and
186    /// the ones it declined to the sampled search.
187    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
223/// Arm the classifier counters (reset to zero) when `BREP_PROFILE` is set.
224pub 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
234/// Print the counters gathered since [`classify_profile_begin`] under
235/// `label` and disarm them. Silent when profiling is off.
236pub 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
250/// The exact ray lane (lane B row 1, 2026-10-17): a ray against an ANALYTIC
251/// face is seeded with its closed-form roots (`crate::exact_line_surface`)
252/// instead of the sampled search's 32-sample scan, then solved and filtered
253/// by the same code. Default ON since its on/off census (production 96/96,
254/// bench 52/52 bodies and 1197/1197 lines) read identical;
255/// `BREP_CLASSIFY_EXACT_RAY=0` (or `off`) restores the sampled search.
256fn exact_ray_enabled() -> bool {
257    switch!("BREP_CLASSIFY_EXACT_RAY", true)
258}
259
260/// One ray-face intersection of the ray pass: the exact lane's seeds when it
261/// is on and the face admits them, the sampled search otherwise. Counted on
262/// the profile as `exact_faces` / `fallback_faces` (never timed).
263fn 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    // A ray proved clear of the face: the sampled search's answer is known to be empty (the check
276    // mode runs the search anyway and stops on a disagreement).
277    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
294/// `BREP_CLASSIFY_RAY_CLEAR` (default on since its promotion; `=0` restores the search alone): a ray the sampled search would take against a freeform
295/// face is first proved clear of it by hull boxes (`crate::curve_clear`); most such searches find
296/// nothing, each after many Newton starts that open with a global projection.
297fn ray_clear_enabled() -> bool {
298    switch!("BREP_CLASSIFY_RAY_CLEAR", true)
299}
300
301/// Point-in-solid classification with per-solid precomputation: face
302/// bounds, the solid box, and a face BVH are built once so repeated
303/// queries (boolean fragment selection asks once per fragment) prune to
304/// the few faces a probe point or ray can actually touch.
305pub struct SolidClassifier<'a> {
306    faces: Vec<&'a FaceRecord>,
307    face_boxes: Vec<Aabb>,
308    bounds: Aabb,
309    bvh: Bvh,
310    tolerance: f64,
311    /// `(region, cap)`: within `region` the On and coincident-On bands reach
312    /// at most `cap` (the feature-scale design's B6/B6′; empty unless the boolean's
313    /// `BREP_FEATURE_SCALE_SELECT` sets it with [`Self::with_coincident_caps`]).
314    coincident_caps: Vec<(Aabb, f64)>,
315}
316
317/// Clip the segment `start + s·direction, s ∈ [0, length]` to `bounds`
318/// (slab test).  Returns the clipped `[s_entry, s_exit]` span, or None when
319/// the segment misses the box.
320fn 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
354/// `BREP_CLASSIFY_PLANAR_TRIM_BOXES` (default on; `=0` restores): a planar
355/// face's box is its boundary's (the control points of the edges its loops
356/// use), not its carrier's. A linear function over a plane region takes its
357/// extremes on the region's boundary, so the region lies in the boundary's
358/// box. A boolean's planar faces keep the carrier they were cut from: on a
359/// molded bottle cap 180 of 484 planes span up to 85 times their trims, every
360/// ray met about 100 face boxes against 14 on the same body read back from
361/// STEP, and 4096 points took 57 s against 8 s.
362fn planar_trim_boxes_enabled() -> bool {
363    switch!("BREP_CLASSIFY_PLANAR_TRIM_BOXES", true)
364}
365
366/// The box of a planar face's boundary curves, when every coedge's edge is
367/// known; `None` for a curved face, a face with no loop, or a missing edge.
368fn 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    /// The orientation a chord through `through` along `direction` reads, or
413    /// `None` when the chord cannot tell (`BREP_BOOLEAN_SIGN_CHORDS`).
414    ///
415    /// The chord runs from outside the faces' box to outside it, so a closed,
416    /// consistently oriented boundary is entered and left in turn: its hits,
417    /// ordered along the chord, alternate between outward normals against
418    /// the chord and along it, and their number is even. `Some(true)` when
419    /// they do and the first is an entry (material lies behind the normals,
420    /// as on a solid of positive volume), `Some(false)` when they do and the
421    /// first is an exit (inside out). `None` when any hit is tangential,
422    /// grazes (`|n · d|` under 1e-2), falls in a trim's boundary band, sits
423    /// within the On band of another hit, when the hits do not alternate or
424    /// are odd in number (a root the finder lost, or a face reversed against
425    /// its neighbours), or when no hit lies within the On band of `through`
426    /// (the aimed face itself was missed).
427    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        // (distance along the chord, the outward normal along it).
439        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    /// Cheap On-band probe: is the point within the classifier's On
488    /// tolerance of ANY face carrier (trim not checked — conservative)?
489    /// Used to guard adjacency propagation: fragments near the other
490    /// solid's surface need the full normal-based On decision, everything
491    /// else can inherit its fate from a neighbor.
492    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    /// Conservative carrier-proximity probe: is `point` within `band` of ANY
510    /// face's carrier surface (trim NOT checked)?  A strict superset of the
511    /// `On` verdict (which additionally requires the point to fall in a face's
512    /// trim), so callers that want to skip every point that *might* be on or
513    /// near the boundary — the semantic oracle's On-skip — can rely on a `true`
514    /// here to mean "not safely In/Out".  `band` is taken explicitly so the
515    /// caller can widen it to a size-relative width and absorb near-coincidence
516    /// gaps (Golovanov §4.13 derived tolerances).
517    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        // FEATURE SCALE B6′ (`BREP_FEATURE_SCALE_SELECT`; no caps without it):
543        // the On band (1e-6) reaches across a slab 1e-6 thick, so the middle
544        // of the hairline slot's strips read On its walls, not In the saw.
545        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        // THIN-BODY BAND (`BREP_CLASSIFY_THIN_BODY_BAND`, default on; with it
550        // off and `BREP_CLASSIFY_THIN_BODY_BAND_CHECK` on, the band is measured
551        // and a differing answer reported, the answer kept): where the body is
552        // thinner than four On bands at a face the point lies within the band
553        // of, the band is capped at a quarter of the body's local thickness
554        // there, measured exactly along the face's inward normal from the
555        // point's foot to the next face. A lens 1.8e-6 thick read a point
556        // 4.7e-7 outside it On its wall (the band is 1e-6), so inside.
557        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                    // The rays then read crossings at a tenth of the cap: at
562                    // the classifier's own tolerance two crossings of a wall
563                    // 8e-7 across merge into one.
564                    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    /// The least quarter of the body's local thickness at every face whose
584    /// band `band` reaches the point inside its trim, where that thickness is
585    /// under four bands: from the point's foot on the face, along the face's
586    /// inward normal, to the nearest other boundary point within four bands
587    /// (a face's own surface is passed over at its foot). `None` where the
588    /// body is no thinner than that.
589    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            // The probe starts a thousandth of a band inside, past its own
607            // wall (no self-hit to exclude, at any distance from the origin),
608            // and reads the hits at that resolution (the intersection merges
609            // hits within ten of its tolerance; at the classifier's own a
610            // wall 8e-7 across would merge with its foot).
611            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    /// [`Self::classify`] at the On band `on_tolerance`, its rays' crossings
642    /// read at `tolerance`.
643    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        // All faces the point lies On, split by whether it sits in the trim
649        // interior or within the boundary band.  Where the point is on an
650        // edge or vertex shared by several faces, the classification normal
651        // is the normalized sum of their normals (Golovanov §4.11/§6.3) —
652        // a single face's normal is ambiguous there, and falling through to
653        // ray casting made the answer direction-dependent.
654        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            // A near-zero sum means opposed normals (knife edge, coincident
702            // back-to-back faces): genuinely ambiguous, let the ray casting
703            // below decide.
704            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        // RAY-AGREEMENT VOTING: a single ray's parity flips when the root
723        // finder loses one of two close crossings through a thin feature
724        // (trial 533's 00000231-p4: a ray pierced a curved flange twice ~3 mm
725        // apart, intersect_curve_surface returned one root, and a point 2 mm
726        // clear of the material classified In). One lost root is a
727        // direction-specific accident, so require TWO clean directions to
728        // AGREE before trusting the parity; on disagreement keep sampling
729        // directions and return the first verdict confirmed twice. Escape
730        // hatch: BREP_CLASSIFY_RAY_AGREE=0 restores first-clean-ray.
731        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                // Intersect the ray with this face over the SHORT span the
745                // ray actually spends near the face's bounding box, not the
746                // whole solid-diagonal-scale ray.  The root finder seeds one
747                // Newton start per curve sample segment, so a long ray gives
748                // a small face a single seed — a ray that crosses a small
749                // curved face twice within one sample segment (e.g. a probe
750                // from a tangency line through a blend tube) silently loses
751                // a crossing and flips the parity.  Clipping the ray to the
752                // face box makes the seed density match the face scale.
753                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        // Every direction bailed (tangential/boundary) or, under agreement
847        // voting, the clean directions never confirmed one another. A single
848        // unconfirmed verdict is still far better than an error.
849        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    /// Wider-band On probe for near-coincident faces.  A model built from
859    /// noisy input carries faces that are geometrically coincident with the
860    /// other solid's boundary yet separated by a gap that scales with the
861    /// model (a few microns), not with the absolute model tolerance.  Such a
862    /// gap slips a face fragment's interior test point past the fixed On band
863    /// (`classify`), so it reads as a stray In/Out.  This probe re-checks
864    /// whether `point` sits in the trim INTERIOR of a coincident boundary
865    /// face within a band derived from the solid's size (Golovanov §4.13
866    /// derived tolerances), returning the mean outward normal of the
867    /// coincident faces when it does.  It only ever RESCUES an On verdict —
868    /// callers keep the tight-band In/Out otherwise — so the general
869    /// classification path is unchanged.  Interior-only (boundary hits are
870    /// ignored) so it fires only on a genuine surface overlap, never on mere
871    /// proximity to an edge.
872    /// Caps the coincident-On band within each region (see
873    /// `coincident_caps`): a test point a sliver's width from the other
874    /// solid's face is a feature, not noise to rescue to On.
875    pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
876        self.coincident_caps = caps;
877        self
878    }
879
880    /// `band` capped by every `coincident_caps` region within its reach of
881    /// `point`, strictly (a point exactly at a cap's distance is a feature).
882    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        // A point at a capped band's edge is a feature, not noise: strictly
902        // inside the cap only (`< cap`, as the projection test below reads
903        // `> band` as off).
904        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