Skip to main content

brep_topology/brep/classification/
face_containment.rs

1use crate::curve::interior_knot_count;
2use crate::topology::LoopRecord;
3pub use super::*;
4
5/// How many chords the containment lanes sample ONE pcurve at:
6/// `max(2, (k + 1)(p + 1)·4)`, `k` the pcurve's distinct interior knots (two
7/// knots are one when they differ by no more than
8/// [`KNOT_DEDUP_EPS`](crate::KNOT_DEDUP_EPS), and a knot that close to an end
9/// of the active domain is not interior) and `p` its degree. Knot- and
10/// degree-aware, so a spline trim is resolved wherever its shape can bend and a
11/// line is two chords.
12///
13/// Nothing compares the count; it IS the polygon [`parameter_point_in_face`]
14/// classifies against. The generic scan, the wrapped-horizon, sphere-cap and
15/// covering-rim-strip lanes sample every pcurve at
16/// [`trim_station`]`(start, end, i, count)` for `i` in `0..count` (the rim
17/// strip `0..=count`), the pcurve's domain being `[start, end]`.
18///
19/// Published rather than copied: [`crate::loop_self_crossings`] and the
20/// soundness detectors test EXACTLY these chords, or the kernel could hold that
21/// a loop does not cross itself while classifying points against a polygon
22/// that does; and a caller that answers containment questions ahead of the
23/// kernel (the sheets' hidden-line pass) must build its polygon from the same
24/// stations, or it stops answering as the kernel does.
25pub fn trim_sample_count(curve: &NurbsCurve) -> usize {
26    2usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4)
27}
28
29/// The pcurve parameter of trim station `index` of `count` over `[start, end]`:
30/// `start + (end − start)·index / count`, evaluated in exactly that order.
31///
32/// The comparand is bit identity with the stations the lanes sampled: the
33/// prepared-face cache, the self-crossing detector and any caller mirroring a
34/// lane rely on the same floats. At `index == count` this is NOT `end` to the
35/// bit; the generic scan closes a pcurve's last chord at `end` itself.
36pub fn trim_station(start: f64, end: f64, index: usize, count: usize) -> f64 {
37    start + (end - start) * index as f64 / count as f64
38}
39
40/// `BREP_SEAM_BAND_MERGED`: set to `"0"` (the only value compared), the
41/// doubly-periodic seam-band lane stops unwrapping a single merged seam-carrying
42/// loop, and that face goes on to the two-loop analyses or the generic scan.
43/// Read when a face is prepared; part of the prepared-face cache key.
44pub const SEAM_BAND_MERGED_SWITCH: &str = "BREP_SEAM_BAND_MERGED";
45
46/// `BREP_HORIZON_CONTAINMENT`: set to `"0"`, the wrapped-horizon lane declines
47/// every face. Read when a face is prepared; part of the cache key.
48pub const HORIZON_CONTAINMENT_SWITCH: &str = "BREP_HORIZON_CONTAINMENT";
49
50/// `BREP_HORIZON_SINGLE_LOOP`: set to `"0"`, the wrapped-horizon lane declines a
51/// face of one or two loops (compared: `face.loops.len() <= 2`). Read when a
52/// face is prepared; part of the cache key.
53pub const HORIZON_SINGLE_LOOP_SWITCH: &str = "BREP_HORIZON_SINGLE_LOOP";
54
55/// `BREP_HORIZON_CROSS_FRAME`: set to `"0"`, the wrapped-horizon lane combines
56/// its period images per image (Inside when any image counts odd) instead of
57/// summing each loop's parity over the images. Read per QUERY, not when the
58/// face is prepared; see [`horizon_cross_frame`].
59pub const HORIZON_CROSS_FRAME_SWITCH: &str = "BREP_HORIZON_CROSS_FRAME";
60
61/// `BREP_COVERING_RIM_STRIP`: set to `"0"`, the covering-rim-strip lane declines
62/// every face. Read when a face is prepared; part of the cache key.
63pub const COVERING_RIM_STRIP_SWITCH: &str = "BREP_COVERING_RIM_STRIP";
64
65/// `BREP_NO_SPHERE_CHART_TRIM`: SET to any value (compared: present in the
66/// environment), the sphere-chart lane stops substituting for the generic scan's
67/// parity count. `BREP_NO_SPHERE_CHARTS`, which turns every sphere-chart path
68/// off, does the same here. Read per query.
69pub const NO_SPHERE_CHART_TRIM_SWITCH: &str = "BREP_NO_SPHERE_CHART_TRIM";
70
71// The lane switches below are `"0"`-style: each is off when its environment
72// value is exactly `"0"` (`switch!(.., true)`), read through its call
73// site's once-cell while `BREP_ENV_READ_ONCE` is on. They were read once
74// under `BREP_CONTAINMENT_SWITCHES_ONCE` (lane O row 18) until S1 folded that
75// table into `switch!`; only variables set before a process starts go
76// through it, so `NO_SPHERE_CHART_TRIM_SWITCH` and the debug flags stay live.
77
78
79/// Whether the wrapped-horizon lane sums each loop's parity over the query's
80/// period images (`true`, the default) or keeps the per-image combining
81/// (`false`, [`HORIZON_CROSS_FRAME_SWITCH`] = `"0"`). Read from the environment
82/// on every call, as the lane reads it on every query.
83pub fn horizon_cross_frame() -> bool {
84    switch!(HORIZON_CROSS_FRAME_SWITCH, true)
85}
86
87/// Whether the sphere-chart lane may substitute for the generic scan's parity
88/// count: neither `BREP_NO_SPHERE_CHARTS` nor [`NO_SPHERE_CHART_TRIM_SWITCH`]
89/// is set. Read on every call.
90fn sphere_chart_trim_enabled() -> bool {
91    env_read!("BREP_NO_SPHERE_CHARTS").is_none()
92        && std::env::var(NO_SPHERE_CHART_TRIM_SWITCH).is_err()
93}
94
95fn point_segment_distance(point: Vec2, start: Vec2, end: Vec2) -> f64 {
96    point.distance_to_segment(start, end, 1e-30)
97}
98
99pub use crate::polygon::PolygonClass;
100
101pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
102    crate::polygon::classify(point, polygon, tolerance, 1e-30)
103}
104
105/// The even-odd half of [`point_in_polygon`]: whether a ray from `point`
106/// towards +x crosses `polygon` an odd number of times.
107fn polygon_parity_inside(point: Vec2, polygon: &[Vec2]) -> bool {
108    crate::polygon::parity_inside([point.x, point.y], polygon.len(), |i| [polygon[i].x, polygon[i].y])
109}
110
111
112/// One chord of a trim loop as the generic scan samples it: the loop and
113/// coedge it belongs to (the pcurve is looked up on the face at query time —
114/// the prepared data is cached across faces and must own nothing borrowed)
115/// and the pcurve parameters at its ends.
116#[derive(Clone, Copy)]
117struct SegmentPrep {
118    coedge_index: usize,
119    parameter_start: f64,
120    parameter_end: f64,
121}
122
123/// Which of the environment switches the lanes read were set when a face was
124/// prepared; part of the cache signature so a test that flips one between two
125/// queries on one thread never answers from data prepared under the other.
126pub fn lane_switches() -> f64 {
127    let mut bits = 0u32;
128    if !switch!(SEAM_BAND_MERGED_SWITCH, true) {
129        bits |= 1;
130    }
131    if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
132        bits |= 2;
133    }
134    if !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
135        bits |= 4;
136    }
137    if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
138        bits |= 8;
139    }
140    bits as f64
141}
142
143/// Doubly-periodic seam-band lane, prepared.
144enum SeamBandPrep {
145    /// The surface is not closed in both directions: the lane declines.
146    NotApplicable,
147    /// Every loop is a collapsed puncture: the whole torus is material.
148    AlwaysInside,
149    /// One seam-crossing loop unwrapped onto the covering plane.
150    Merged { polygon: Vec<Vec2>, u_span: f64, v_span: f64 },
151    /// Two loops the seam-band analysis reassembled into one polygon.
152    Analyzed { polygon: Vec<Vec2> },
153    /// Two clean full-wrap rims at constant cross levels.
154    Rings { p_is_u: bool, q_lo: f64, q_hi: f64, complement: bool },
155    /// None of the shapes above: keep the general path.
156    Declined,
157}
158
159/// Winding sphere-cap lane, prepared: `None` when the face is not a cap.
160struct SphereCapPrep {
161    rim: Vec<Vec2>,
162    pole_v: f64,
163    period: f64,
164}
165
166/// Wrapped-horizon lane, prepared: `None` when no loop straddles the seam.
167struct HorizonPrep {
168    loops: Vec<Vec<Vec2>>,
169    u_period: f64,
170    /// The loops' chords, indexed the first time a query asks.
171    index: std::cell::OnceCell<Option<ChordIndex>>,
172}
173
174/// Covering rim-strip lane, prepared: `None` when the face is not a strip.
175struct RimStripPrep {
176    lower: Vec<Vec2>,
177    upper: Vec<Vec2>,
178    period: f64,
179}
180
181/// The generic scan's samples: per loop the parity polygon, the chord
182/// parameters behind it and the per-coedge runs the spherical lane reads.
183pub struct GenericPrep {
184    pub loops: Vec<LoopSamples>,
185    segments: Vec<Vec<SegmentPrep>>,
186    /// Every loop's chords, counted.
187    chord_count: usize,
188    /// The chords indexed ([`ChordIndex`]), built the first time a query asks
189    /// for the index; `None` inside when a sample is too large or not finite.
190    index: std::cell::OnceCell<Option<ChordIndex>>,
191}
192
193/// The fewest chords a lane must carry before a query goes through its
194/// [`ChordIndex`] rather than scanning every chord: below it the scan costs
195/// about what a descent does. Either answers the same.
196const CHORD_INDEX_MIN_CHORDS: usize = 64;
197
198/// Chords per leaf of a [`ChordIndex`].
199const CHORD_INDEX_LEAF: usize = 6;
200
201/// The largest coordinate, of a chord end or of a query point, the index is
202/// used for. Squares of anything smaller stay finite, so every distance the
203/// scan computes is a finite number the index can bound; beyond it the scan
204/// answers.
205const CHORD_INDEX_MAX_COORDINATE: f64 = 1e100;
206
207/// A node of a [`ChordIndex`]: the exact box (the min and max of the samples,
208/// not a computed value) of a run of consecutive chords of one loop, chords
209/// `first..last` of loop `loop_index`, chord `i` running from `polygon[i]` to
210/// `polygon[(i + 1) % len]`. A leaf reads its chords; an inner node has two
211/// children, the runs before and after its middle.
212#[derive(Clone, Copy)]
213struct ChordNode {
214    low: Vec2,
215    high: Vec2,
216    loop_index: u32,
217    first: u32,
218    last: u32,
219    children: Option<(u32, u32)>,
220}
221
222/// A hierarchy of boxes over every chord of a face's generic scan, or of its
223/// wrapped-horizon lane's unwrapped loops, so a query reads the chords near it
224/// rather than all of them — and gives the scan's answer to the bit.
225///
226/// Consecutive chords of a trim lie together, so each loop's chords are cut
227/// into runs of [`CHORD_INDEX_LEAF`] and the runs paired, and paired again, up
228/// to one box per loop: built in one pass over the samples, holding no copy of
229/// them. (A median-split tree over the chords of `gear-hex-bore-push`'s face
230/// 8307, 557 504 of them, took 200 ms to build — more than the questions it
231/// answered saved.)
232///
233/// The scan asks three things of its chords, and the index asks each of the
234/// same chords with the same arithmetic (the wrapped horizon asks the second
235/// and third, at each of its three period images):
236///
237/// - the NEAREST chord, `point_segment_distance` to every chord with a strict
238///   `<` in loop-then-chord order, so the first minimum is kept. The index
239///   keeps the least `(distance, loop, chord)`, which is that chord, and skips a
240///   box only when its distance exceeds the best by more than `slack`;
241/// - whether any chord is within the tolerance (`Boundary`): exactly when the
242///   nearest chord's distance is, both being that same float;
243/// - each loop's even-odd count along +x, the test `(a.y > p.y) != (b.y > p.y)`
244///   and `crossing > p.x`. A chord that passes the first has one sample above
245///   `p.y` and one at or below it, which its box holds exactly, and its
246///   crossing is within rounding of its samples' largest `x`; a box is skipped
247///   only when its `y` range cannot straddle `p.y` or its largest `x` is short
248///   of `p.x` by more than `slack`.
249///
250/// `slack` is `1e-12` of the largest coordinate in play, some four thousand
251/// times the few units in the last place a computed foot or crossing can stray
252/// outside its chord's box. Distances and crossings are only COMPARED against
253/// boxes with that slack; every value that decides an answer is the scan's own.
254struct ChordIndex {
255    nodes: Vec<ChordNode>,
256    /// One per loop with chords.
257    roots: Vec<u32>,
258    /// `1e-12 × (1 + the largest |coordinate| of a sample)`.
259    slack: f64,
260}
261
262/// The closed polygons a [`ChordIndex`] is built over and read against: the
263/// generic scan's loops, or the wrapped-horizon lane's unwrapped ones.
264trait ChordLoops {
265    fn loop_count(&self) -> usize;
266    fn polygon(&self, index: usize) -> &[Vec2];
267}
268
269impl ChordLoops for [LoopSamples] {
270    fn loop_count(&self) -> usize {
271        self.len()
272    }
273
274    fn polygon(&self, index: usize) -> &[Vec2] {
275        &self[index].polygon
276    }
277}
278
279impl ChordLoops for [Vec<Vec2>] {
280    fn loop_count(&self) -> usize {
281        self.len()
282    }
283
284    fn polygon(&self, index: usize) -> &[Vec2] {
285        &self[index]
286    }
287}
288
289impl ChordIndex {
290    /// The index over `loops`, or `None` when a sample is not finite, a
291    /// coordinate exceeds [`CHORD_INDEX_MAX_COORDINATE`], a count does not fit
292    /// in `u32`, or there is no chord.
293    fn build<L: ChordLoops + ?Sized>(loops: &L) -> Option<ChordIndex> {
294        let mut nodes: Vec<ChordNode> = Vec::new();
295        let mut roots = Vec::new();
296        let mut largest: f64 = 0.0;
297        for loop_index in 0..loops.loop_count() {
298            let polygon = loops.polygon(loop_index);
299            let len = polygon.len();
300            if len == 0 {
301                continue;
302            }
303            u32::try_from(len).ok()?;
304            for sample in polygon {
305                if !(sample.x.abs() <= CHORD_INDEX_MAX_COORDINATE && sample.y.abs() <= CHORD_INDEX_MAX_COORDINATE) {
306                    return None;
307                }
308                largest = largest.max(sample.x.abs()).max(sample.y.abs());
309            }
310            let loop_index = u32::try_from(loop_index).ok()?;
311            let mut level: Vec<u32> = Vec::with_capacity(len / CHORD_INDEX_LEAF + 1);
312            for first in (0..len).step_by(CHORD_INDEX_LEAF) {
313                let last = (first + CHORD_INDEX_LEAF).min(len);
314                let (mut low, mut high) = (polygon[first], polygon[first]);
315                for index in first..last {
316                    let end = polygon[(index + 1) % len];
317                    low = Vec2 { x: low.x.min(end.x), y: low.y.min(end.y) };
318                    high = Vec2 { x: high.x.max(end.x), y: high.y.max(end.y) };
319                    let start = polygon[index];
320                    low = Vec2 { x: low.x.min(start.x), y: low.y.min(start.y) };
321                    high = Vec2 { x: high.x.max(start.x), y: high.y.max(start.y) };
322                }
323                level.push(u32::try_from(nodes.len()).ok()?);
324                nodes.push(ChordNode {
325                    low,
326                    high,
327                    loop_index,
328                    first: first as u32,
329                    last: last as u32,
330                    children: None,
331                });
332            }
333            while level.len() > 1 {
334                let mut next = Vec::with_capacity(level.len() / 2 + 1);
335                for pair in level.chunks(2) {
336                    let &[left, right] = pair else {
337                        next.push(pair[0]);
338                        continue;
339                    };
340                    let (a, b) = (nodes[left as usize], nodes[right as usize]);
341                    next.push(u32::try_from(nodes.len()).ok()?);
342                    nodes.push(ChordNode {
343                        low: Vec2 { x: a.low.x.min(b.low.x), y: a.low.y.min(b.low.y) },
344                        high: Vec2 { x: a.high.x.max(b.high.x), y: a.high.y.max(b.high.y) },
345                        loop_index,
346                        first: a.first,
347                        last: b.last,
348                        children: Some((left, right)),
349                    });
350                }
351                level = next;
352            }
353            roots.push(level[0]);
354        }
355        if roots.is_empty() {
356            return None;
357        }
358        Some(ChordIndex {
359            nodes,
360            roots,
361            slack: 1e-12 * (1.0 + largest),
362        })
363    }
364
365    /// The slack for a query at `point`: the index's own plus `1e-12` of the
366    /// point's largest coordinate.
367    fn slack_at(&self, point: Vec2) -> f64 {
368        self.slack + 1e-12 * point.x.abs().max(point.y.abs())
369    }
370
371    fn box_distance(node: &ChordNode, point: Vec2) -> f64 {
372        let dx = (node.low.x - point.x).max(point.x - node.high.x).max(0.0);
373        let dy = (node.low.y - point.y).max(point.y - node.high.y).max(0.0);
374        (dx * dx + dy * dy).sqrt()
375    }
376
377    /// The scan's nearest chord of `loops` to `point` as `(loop, chord,
378    /// distance)`: the least distance, and of equal distances the first in
379    /// loop-then-chord order.
380    fn nearest<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2) -> Option<(usize, usize, f64)> {
381        let slack = self.slack_at(point);
382        let mut best: Option<(f64, u32, u32)> = None;
383        let mut stack: Vec<(u32, f64)> = Vec::with_capacity(64);
384        for &root in &self.roots {
385            stack.push((root, Self::box_distance(&self.nodes[root as usize], point)));
386        }
387        while let Some((node_index, bound)) = stack.pop() {
388            if best.is_some_and(|(distance, _, _)| bound > distance + slack + 1e-12 * distance) {
389                continue;
390            }
391            let node = self.nodes[node_index as usize];
392            match node.children {
393                None => {
394                    let polygon = loops.polygon(node.loop_index as usize);
395                    for index in node.first..node.last {
396                        let start = polygon[index as usize];
397                        let end = polygon[(index as usize + 1) % polygon.len()];
398                        let distance = point_segment_distance(point, start, end);
399                        let better = best.is_none_or(|(least, loop_index, chord_index)| {
400                            distance < least
401                                || (distance == least && (node.loop_index, index) < (loop_index, chord_index))
402                        });
403                        if better {
404                            best = Some((distance, node.loop_index, index));
405                        }
406                    }
407                }
408                Some((left, right)) => {
409                    let left_bound = Self::box_distance(&self.nodes[left as usize], point);
410                    let right_bound = Self::box_distance(&self.nodes[right as usize], point);
411                    // The nearer box is read first, so the best tightens early.
412                    if left_bound <= right_bound {
413                        stack.push((right, right_bound));
414                        stack.push((left, left_bound));
415                    } else {
416                        stack.push((left, left_bound));
417                        stack.push((right, right_bound));
418                    }
419                }
420            }
421        }
422        best.map(|(distance, loop_index, chord_index)| {
423            (loop_index as usize, chord_index as usize, distance)
424        })
425    }
426
427    /// Whether a chord of `loops` lies within `tolerance` of `point`, by
428    /// `point_segment_distance`, the scan's own test.
429    fn any_within<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, tolerance: f64) -> bool {
430        let reach = tolerance + self.slack_at(point) + 1e-12 * tolerance.abs();
431        let mut stack: Vec<u32> = self.roots.clone();
432        while let Some(node_index) = stack.pop() {
433            let node = self.nodes[node_index as usize];
434            if Self::box_distance(&node, point) > reach {
435                continue;
436            }
437            match node.children {
438                None => {
439                    let polygon = loops.polygon(node.loop_index as usize);
440                    for index in node.first as usize..node.last as usize {
441                        let (start, end) = (polygon[index], polygon[(index + 1) % polygon.len()]);
442                        if point_segment_distance(point, start, end) <= tolerance {
443                            return true;
444                        }
445                    }
446                }
447                Some((left, right)) => {
448                    stack.push(right);
449                    stack.push(left);
450                }
451            }
452        }
453        false
454    }
455
456    /// Flips `odd[loop]` once for every chord of that loop the +x ray from
457    /// `point` crosses, with `point_in_polygon`'s crossing test.
458    fn flip_crossings<L: ChordLoops + ?Sized>(&self, loops: &L, point: Vec2, odd: &mut [bool]) {
459        let slack = self.slack_at(point);
460        let mut stack: Vec<u32> = self.roots.clone();
461        while let Some(node_index) = stack.pop() {
462            let node = self.nodes[node_index as usize];
463            if !(node.low.y <= point.y && node.high.y > point.y) || node.high.x + slack < point.x {
464                continue;
465            }
466            match node.children {
467                None => {
468                    let polygon = loops.polygon(node.loop_index as usize);
469                    for index in node.first as usize..node.last as usize {
470                        let a = polygon[index];
471                        let b = polygon[(index + 1) % polygon.len()];
472                        if crate::polygon::crosses_ray([point.x, point.y], [a.x, a.y], [b.x, b.y]) {
473                            let parity = &mut odd[node.loop_index as usize];
474                            *parity = !*parity;
475                        }
476                    }
477                }
478                Some((left, right)) => {
479                    stack.push(right);
480                    stack.push(left);
481                }
482            }
483        }
484    }
485}
486
487/// How a query reads a lane's chords: the generic scan's, or the wrapped
488/// horizon's.
489#[derive(Clone, Copy, PartialEq, Eq)]
490enum ChordScan {
491    /// Through the index on a face of [`CHORD_INDEX_MIN_CHORDS`] or more.
492    Auto,
493    /// Through the index whenever it can be built.
494    Indexed,
495    /// Every chord.
496    Linear,
497}
498
499impl ChordScan {
500    /// Whether a lane of `chords` chords is read through its index.
501    fn indexes(self, chords: usize) -> bool {
502        match self {
503            ChordScan::Linear => false,
504            ChordScan::Indexed => true,
505            ChordScan::Auto => chords >= CHORD_INDEX_MIN_CHORDS,
506        }
507    }
508}
509
510/// Whether a query point is one the index is used for
511/// ([`CHORD_INDEX_MAX_COORDINATE`]).
512fn in_index_range(point: Vec2) -> bool {
513    point.x.abs() <= CHORD_INDEX_MAX_COORDINATE && point.y.abs() <= CHORD_INDEX_MAX_COORDINATE
514}
515
516/// The generic scan over every chord: `(odd loops, boundary, nearest chord as
517/// (loop, chord, distance))`. The reference the index answers as.
518fn linear_scan(
519    generic: &GenericPrep,
520    point: Vec2,
521    tolerance: f64,
522) -> (usize, bool, Option<(usize, usize, f64)>) {
523    let mut crossings = 0;
524    let mut boundary = false;
525    // `(loop index, chord index, distance)` of the nearest chord, scanned in
526    // loop order then chord order so a tie resolves as it always has.
527    let mut nearest: Option<(usize, usize, f64)> = None;
528    let fused = fused_scan_enabled();
529    for (loop_index, (samples, chords)) in generic.loops.iter().zip(&generic.segments).enumerate() {
530        let polygon = &samples.polygon;
531        if fused {
532            // One distance per chord serves the boundary test and the nearest
533            // chord; `chords` holds one entry per polygon sample.
534            let mut on_boundary = false;
535            for index in 0..polygon.len() {
536                let distance = point_segment_distance(point, polygon[index], polygon[(index + 1) % polygon.len()]);
537                if distance <= tolerance {
538                    on_boundary = true;
539                }
540                if index < chords.len()
541                    && nearest
542                        .as_ref()
543                        .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
544                {
545                    nearest = Some((loop_index, index, distance));
546                }
547            }
548            if on_boundary {
549                boundary = true;
550            } else if polygon_parity_inside(point, polygon) {
551                crossings += 1;
552            }
553            continue;
554        }
555        match point_in_polygon(point, polygon, tolerance) {
556            PolygonClass::Boundary => boundary = true,
557            PolygonClass::Inside => crossings += 1,
558            PolygonClass::Outside => {}
559        }
560        for index in 0..chords.len() {
561            let start = polygon[index];
562            let end = polygon[(index + 1) % polygon.len()];
563            let distance = point_segment_distance(point, start, end);
564            if nearest
565                .as_ref()
566                .is_none_or(|(_, _, nearest_distance)| distance < *nearest_distance)
567            {
568                nearest = Some((loop_index, index, distance));
569            }
570        }
571    }
572    (crossings, boundary, nearest)
573}
574
575/// FUSED SCAN (lane O row 24, 2026-10-29; on by default since the batch 6 promotion, `BREP_CONTAINMENT_FUSED_SCAN=0` restores the two passes).
576/// [`linear_scan`] measured every chord's distance twice, once in
577/// [`point_in_polygon`]'s boundary pass and once for the nearest chord; on the
578/// D2 outward shells that pair was most of the point-in-face query's own time.
579/// The fused pass computes each distance once and feeds both, then counts
580/// parity only off the boundary, as `point_in_polygon` does. Read once per process.
581fn fused_scan_enabled() -> bool {
582    switch!("BREP_CONTAINMENT_FUSED_SCAN", true)
583}
584
585
586/// The generic scan's `(odd loops, boundary, nearest chord)` for `point`, read
587/// as `scan` says. When the index answers, `odd loops` is not counted on a
588/// boundary point, where nothing reads it.
589fn generic_scan(
590    generic: &GenericPrep,
591    point: Vec2,
592    tolerance: f64,
593    scan: ChordScan,
594) -> (usize, bool, Option<(usize, usize, f64)>) {
595    if scan.indexes(generic.chord_count) && in_index_range(point) {
596        if let Some(index) = generic.index.get_or_init(|| {
597            let started = containment_profile_started();
598            let built = ChordIndex::build(generic.loops.as_slice());
599            let ms = containment_elapsed_ms(started);
600            containment_profile(|p| {
601                p.index_builds += 1;
602                p.index_ms += ms;
603            });
604            built
605        }) {
606            let loops = generic.loops.as_slice();
607            let nearest = index.nearest(loops, point);
608            let boundary = nearest.is_some_and(|(_, _, distance)| distance <= tolerance);
609            let crossings = if boundary {
610                0
611            } else {
612                let mut odd = vec![false; loops.len()];
613                index.flip_crossings(loops, point, &mut odd);
614                odd.into_iter().filter(|&parity| parity).count()
615            };
616            return (crossings, boundary, nearest);
617        }
618    }
619    linear_scan(generic, point, tolerance)
620}
621
622/// Everything [`parameter_point_in_face`] derives from the FACE alone, so a
623/// face queried many times — the imprint clip asks once per marched sample,
624/// the fragment builder and the classifier's rays once per crossing — samples
625/// its trim once. Each lane is prepared the first time a query REACHES it, so
626/// an error in a lane's sampling surfaces on exactly the faces and queries it
627/// did when the lanes sampled inline.
628pub struct PreparedFace {
629    seam_band: std::cell::OnceCell<Result<SeamBandPrep, String>>,
630    sphere_cap: std::cell::OnceCell<Result<Option<SphereCapPrep>, String>>,
631    horizon: std::cell::OnceCell<Result<Option<HorizonPrep>, String>>,
632    rim_strip: std::cell::OnceCell<Result<Option<RimStripPrep>, String>>,
633    generic: std::cell::OnceCell<Result<GenericPrep, String>>,
634    /// The spherical trim lane's region, built from `generic`'s samples.
635    sphere_region: std::cell::OnceCell<Result<crate::sphere_chart::SphericalRegion, String>>,
636    /// The same region from a reduced boundary, with the margin within which it
637    /// may differ from `sphere_region` ([`build_sphere_region_reduced`]); `None`
638    /// for a trim too small to reduce.
639    sphere_region_reduced: std::cell::OnceCell<Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String>>,
640    /// Each loop's trim samples at [`trim_station`] `0..count` per pcurve, in
641    /// coedge order, taken once and shared by the sphere-cap, wrapped-horizon
642    /// and generic lanes ([`loop_samples`]); one entry per loop, filled the
643    /// first time a lane reaches that loop.
644    loop_samples: std::cell::RefCell<Vec<Option<Result<std::rc::Rc<Vec<Vec2>>, String>>>>,
645}
646
647impl PreparedFace {
648    fn new() -> Self {
649        Self {
650            seam_band: std::cell::OnceCell::new(),
651            sphere_cap: std::cell::OnceCell::new(),
652            horizon: std::cell::OnceCell::new(),
653            rim_strip: std::cell::OnceCell::new(),
654            generic: std::cell::OnceCell::new(),
655            sphere_region: std::cell::OnceCell::new(),
656            sphere_region_reduced: std::cell::OnceCell::new(),
657            loop_samples: std::cell::RefCell::new(Vec::new()),
658        }
659    }
660}
661
662/// Loop `loop_index` of `face` sampled as the lanes sample it: every pcurve
663/// at [`trim_sample_count`] chords, [`trim_station`] `0..count`, in coedge
664/// order. The three lanes that read exactly these samples (the sphere cap,
665/// the wrapped horizon, the generic scan) used to each evaluate them again,
666/// 2 500 pcurve evaluations per pass on a box-fillet corner patch; the
667/// samples are taken the first time any lane reaches the loop and shared
668/// from then on, loop by loop, so a loop a lane never reaches (it declined
669/// on an earlier loop) is never sampled, and a sampling error surfaces at
670/// the loop and the query it did when each lane sampled for itself.
671fn loop_samples(prepared: &PreparedFace, face: &FaceRecord, loop_index: usize) -> Result<std::rc::Rc<Vec<Vec2>>, String> {
672    if let Some(Some(sampled)) = prepared.loop_samples.borrow().get(loop_index) {
673        return sampled.clone();
674    }
675    let sampled = shared_loop_samples(&face.loops[loop_index]);
676    let mut cells = prepared.loop_samples.borrow_mut();
677    if cells.len() < face.loops.len() {
678        cells.resize(face.loops.len(), None);
679    }
680    cells[loop_index] = Some(sampled.clone());
681    sampled
682}
683
684/// `BREP_LOOP_SAMPLE_MEMO`: set to `"0"`, [`loop_samples`] samples every loop
685/// of a newly prepared face again instead of serving a loop this thread
686/// sampled before from [`LOOP_SAMPLE_MEMO`].
687pub const LOOP_SAMPLE_MEMO_SWITCH: &str = "BREP_LOOP_SAMPLE_MEMO";
688
689/// Loops this thread sampled most recently, keyed by everything sampling
690/// reads: per coedge, in order, the pcurve's degree, knots and control points
691/// (each value by its bits, never a NaN). The prepared-face cache is keyed by
692/// the whole face, so a face that gained one loop (a cut's new hole) was a
693/// miss that sampled every unchanged loop again: a ball cut by 62 dimples one
694/// after another re-evaluated every earlier rim at each cut, 7.8% of the run.
695/// The samples are a function of the pcurves alone, so serving them from here
696/// gives the lanes the same floats.
697struct LoopSampleMemo {
698    /// `(hash, signature, samples)`, the most recently used first.
699    entries: Vec<(u64, Vec<f64>, std::rc::Rc<Vec<Vec2>>)>,
700    /// Sum of the entries' sample counts.
701    points: usize,
702}
703
704/// Most entries [`LOOP_SAMPLE_MEMO`] keeps.
705const LOOP_SAMPLE_MEMO_ENTRIES: usize = 256;
706/// Most samples [`LOOP_SAMPLE_MEMO`] keeps over all its entries (16 bytes
707/// each), past which the least recently used entries go.
708const LOOP_SAMPLE_MEMO_POINTS: usize = 1 << 21;
709
710thread_local! {
711    static LOOP_SAMPLE_MEMO: std::cell::RefCell<LoopSampleMemo> =
712        const { std::cell::RefCell::new(LoopSampleMemo { entries: Vec::new(), points: 0 }) };
713}
714
715/// Walks what [`sample_loop`] reads of `record`, every count before the
716/// values it counts, handing each value to `visit` until it returns false.
717/// Returns whether every value was visited.
718fn walk_loop_signature<F: FnMut(f64) -> bool>(record: &LoopRecord, visit: &mut F) -> bool {
719    if !visit(record.coedges.len() as f64) {
720        return false;
721    }
722    for coedge in &record.coedges {
723        let curve = &coedge.pcurve;
724        if !(visit(curve.degree as f64) && visit(curve.knots.len() as f64)) {
725            return false;
726        }
727        if !(curve.knots.iter().all(|&knot| visit(knot)) && visit(curve.control_points.len() as f64)) {
728            return false;
729        }
730        if !curve.control_points.iter().all(|p| visit(p.x) && visit(p.y) && visit(p.z) && visit(p.w)) {
731            return false;
732        }
733    }
734    true
735}
736
737/// Every pcurve of `record` at [`trim_sample_count`] chords, [`trim_station`]
738/// `0..count`, in coedge order.
739fn sample_loop(record: &LoopRecord) -> Result<Vec<Vec2>, String> {
740    let mut points: Vec<Vec2> = Vec::new();
741    for coedge in &record.coedges {
742        let curve = &coedge.pcurve;
743        let [start, end] = curve.domain()?;
744        let sample_count = trim_sample_count(curve);
745        for index in 0..sample_count {
746            let parameter = trim_station(start, end, index, sample_count);
747            let evaluated = curve.evaluate(parameter)?;
748            points.push(Vec2 {
749                x: evaluated.x,
750                y: evaluated.y,
751            });
752        }
753    }
754    Ok(points)
755}
756
757/// [`sample_loop`] of `record`, served from [`LOOP_SAMPLE_MEMO`] when this
758/// thread sampled a loop with the same signature to the bit. An error is
759/// returned and not kept.
760fn shared_loop_samples(record: &LoopRecord) -> Result<std::rc::Rc<Vec<Vec2>>, String> {
761    if !switch!(LOOP_SAMPLE_MEMO_SWITCH, true) {
762        return sample_loop(record).map(std::rc::Rc::new);
763    }
764    use std::hash::Hasher;
765    let mut hasher = rustc_hash::FxHasher::default();
766    walk_loop_signature(record, &mut |value: f64| {
767        hasher.write_u64(value.to_bits());
768        true
769    });
770    let hash = hasher.finish();
771    let found = LOOP_SAMPLE_MEMO.with(|memo| {
772        let mut memo = memo.borrow_mut();
773        let at = memo.entries.iter().position(|(entry_hash, signature, _)| {
774            if *entry_hash != hash {
775                return false;
776            }
777            let mut index = 0;
778            let walked = walk_loop_signature(record, &mut |value: f64| {
779                let same = signature
780                    .get(index)
781                    .is_some_and(|stored| stored.to_bits() == value.to_bits() && !value.is_nan());
782                index += 1;
783                same
784            });
785            walked && index == signature.len()
786        })?;
787        let entry = memo.entries.remove(at);
788        let samples = entry.2.clone();
789        memo.entries.insert(0, entry);
790        Some(samples)
791    });
792    if let Some(samples) = found {
793        // Whether sampling succeeds also depends on each pcurve instance's
794        // validation, which the key does not hold (an instance validated
795        // before its fields changed evaluates content a fresh one rejects).
796        // Sampling validates each pcurve first, in coedge order, and every
797        // evaluation of content served here succeeded, so validating in the
798        // same order returns exactly the error a fresh sampling would.
799        for coedge in &record.coedges {
800            coedge.pcurve.domain()?;
801        }
802        containment_profile(|p| p.loop_sample_hits += 1);
803        return Ok(samples);
804    }
805    let samples = std::rc::Rc::new(sample_loop(record)?);
806    containment_profile(|p| p.loop_sample_misses += 1);
807    if samples.len() > LOOP_SAMPLE_MEMO_POINTS {
808        return Ok(samples);
809    }
810    let mut signature = Vec::new();
811    walk_loop_signature(record, &mut |value: f64| {
812        signature.push(value);
813        true
814    });
815    LOOP_SAMPLE_MEMO.with(|memo| {
816        let mut memo = memo.borrow_mut();
817        memo.points += samples.len();
818        memo.entries.insert(0, (hash, signature, samples.clone()));
819        while memo.entries.len() > LOOP_SAMPLE_MEMO_ENTRIES || memo.points > LOOP_SAMPLE_MEMO_POINTS {
820            let Some((_, _, dropped)) = memo.entries.pop() else { break };
821            memo.points -= dropped.len();
822        }
823    });
824    Ok(samples)
825}
826
827/// Per-thread split of what a face's FIRST query pays to prepare it, printed
828/// by [`containment_profile_report`] when `BREP_PROFILE` is set (the
829/// restriction lane and the interference scan report it beside the
830/// classifier's `classify.profile`): how many faces missed the prepared-face
831/// cache, how many of each lane's preparations ran and their wall time, the
832/// generic scan's chord index builds, and the spherical lane's region builds
833/// split into the surface evaluations, the canonicalization and the region's
834/// own construction (`from_segments`, its seed included). When the switch is
835/// off every counter is one thread-local flag test.
836#[derive(Default, Clone, Copy)]
837struct ContainmentProfile {
838    enabled: bool,
839    cache_misses: u64,
840    seam_band_preps: u64,
841    seam_band_ms: f64,
842    sphere_cap_preps: u64,
843    sphere_cap_ms: f64,
844    horizon_preps: u64,
845    horizon_ms: f64,
846    rim_strip_preps: u64,
847    rim_strip_ms: f64,
848    generic_preps: u64,
849    generic_ms: f64,
850    generic_chords: u64,
851    index_builds: u64,
852    index_ms: f64,
853    region_builds: u64,
854    region_evaluate_ms: f64,
855    region_canonical_ms: f64,
856    region_segments_ms: f64,
857    loop_sample_hits: u64,
858    loop_sample_misses: u64,
859}
860
861thread_local! {
862    static CONTAINMENT_PROFILE: std::cell::Cell<ContainmentProfile> =
863        const { std::cell::Cell::new(ContainmentProfile {
864            enabled: false, cache_misses: 0, seam_band_preps: 0, seam_band_ms: 0.0,
865            sphere_cap_preps: 0, sphere_cap_ms: 0.0, horizon_preps: 0, horizon_ms: 0.0,
866            rim_strip_preps: 0, rim_strip_ms: 0.0, generic_preps: 0, generic_ms: 0.0,
867            generic_chords: 0, index_builds: 0, index_ms: 0.0, region_builds: 0,
868            region_evaluate_ms: 0.0, region_canonical_ms: 0.0, region_segments_ms: 0.0,
869            loop_sample_hits: 0, loop_sample_misses: 0,
870        }) };
871}
872
873impl crate::profile::Counters for ContainmentProfile {
874    fn armed(&self) -> bool {
875        self.enabled
876    }
877}
878
879fn containment_profile(update: impl FnOnce(&mut ContainmentProfile)) {
880    crate::profile::update(&CONTAINMENT_PROFILE, update)
881}
882
883fn containment_profile_started() -> Option<web_time::Instant> {
884    crate::profile::started(&CONTAINMENT_PROFILE)
885}
886
887use crate::profile::elapsed_ms as containment_elapsed_ms;
888
889/// Arm the preparation counters (reset to zero) when `BREP_PROFILE` is set.
890pub fn containment_profile_begin() {
891    let enabled = crate::profile::profile_enabled();
892    CONTAINMENT_PROFILE.with(|cell| {
893        cell.set(ContainmentProfile {
894            enabled,
895            ..ContainmentProfile::default()
896        })
897    });
898}
899
900/// Print the counters gathered since [`containment_profile_begin`] under
901/// `label` and disarm them. Silent when profiling is off.
902pub fn containment_profile_report(label: &str) {
903    let p = CONTAINMENT_PROFILE.with(|cell| cell.get());
904    if !p.enabled {
905        return;
906    }
907    profile_line!(
908        "containment.profile {label} cache_misses={} seam_band: preps={} ms={:.2} sphere_cap: preps={} ms={:.2} horizon: preps={} ms={:.2} rim_strip: preps={} ms={:.2} generic: preps={} ms={:.2} chords={} index: builds={} ms={:.2} region: builds={} evaluate_ms={:.2} canonical_ms={:.2} segments_ms={:.2} loop_samples: memo_hits={} memo_misses={}",
909        p.cache_misses, p.seam_band_preps, p.seam_band_ms, p.sphere_cap_preps, p.sphere_cap_ms,
910        p.horizon_preps, p.horizon_ms, p.rim_strip_preps, p.rim_strip_ms, p.generic_preps,
911        p.generic_ms, p.generic_chords, p.index_builds, p.index_ms, p.region_builds,
912        p.region_evaluate_ms, p.region_canonical_ms, p.region_segments_ms,
913        p.loop_sample_hits, p.loop_sample_misses,
914    );
915    CONTAINMENT_PROFILE.with(|cell| cell.set(ContainmentProfile::default()));
916}
917
918/// A lane's preparation, timed into the profile's `(count, ms)` pair when it
919/// is on.
920fn timed_lane<'a, T>(
921    cell: &'a std::cell::OnceCell<Result<T, String>>,
922    build: impl FnOnce() -> Result<T, String>,
923    record: fn(&mut ContainmentProfile, f64),
924) -> Result<&'a T, String> {
925    lane(cell, || {
926        let started = containment_profile_started();
927        let built = build();
928        let ms = containment_elapsed_ms(started);
929        containment_profile(|p| record(p, ms));
930        built
931    })
932}
933
934fn lane<'a, T>(
935    cell: &'a std::cell::OnceCell<Result<T, String>>,
936    build: impl FnOnce() -> Result<T, String>,
937) -> Result<&'a T, String> {
938    match cell.get_or_init(build) {
939        Ok(value) => Ok(value),
940        Err(error) => Err(error.clone()),
941    }
942}
943
944/// The prepared faces this thread queried most recently, keyed by the EXACT
945/// data the lanes read: the environment switches, the face sense, the surface's
946/// degrees, knots and control points, and per loop each coedge's edge id,
947/// direction, pcurve degree, knots and control points. A hit compares the whole
948/// signature, value by value to the bit (and never a NaN); the hash only
949/// chooses which entries to compare. It also holds the spherical lane's region
950/// (`PreparedFace::sphere_region`, [`build_sphere_region`]). Sampling a
951/// 16-coedge sphere trim at 2 600 chords per coedge four times per query was 1.5 s of
952/// `anotherBooleanFail`'s imprint clip and most of its fragment selection, for
953/// samples that never change between one query and the next.
954///
955/// The lookup is paid on every query, so it walks the face once against the
956/// stored signature and copies nothing: the hash reads the signature's shape
957/// and a few values, not all of it. Building, hashing and comparing the whole
958/// signature per query was 0.68 ms on `gear-hex-bore-push`'s face 8307 (562
959/// pcurves, 36 530 control points), which is all a query there costs once its
960/// chords are indexed.
961pub struct PreparedFaceCache {
962    entries: Vec<(u64, Vec<f64>, std::rc::Rc<PreparedFace>)>,
963}
964
965const PREPARED_FACE_CACHE_ENTRIES: usize = 64;
966
967thread_local! {
968    static PREPARED_FACES: std::cell::RefCell<PreparedFaceCache> = const {
969        std::cell::RefCell::new(PreparedFaceCache {
970            entries: Vec::new(),
971        })
972    };
973}
974
975/// Walks a face's signature — `switches` ([`lane_switches`], read once by the
976/// caller), then the face's data in a fixed order, every count before the
977/// values it counts — handing each value to `visit` until it returns false.
978/// Returns whether every value was visited.
979/// Each coedge's SLOT: the flat index (loops in order, coedges in order) of
980/// the first coedge of this face that names the same edge. The prepared face
981/// reads an edge id only to see whether one face uses an edge twice (a slit,
982/// `build_sphere_region`), which is this pattern and not the id's value; the
983/// assembler renumbers every result's edges (`next_edge_id: 1`), so a key on
984/// the ids missed for every geometrically unchanged face of a running body
985/// (the elephant's fold: 167 misses of 167 uncut probes, 1.47 s of region
986/// builds, 2026-11-02). Keying and storing the slot instead
987/// serves the same prepared face, whose every lane reads the same pattern.
988fn coedge_slots(face: &FaceRecord) -> Vec<usize> {
989    let ids: Vec<u64> = face.loops.iter().flat_map(|record| record.coedges.iter().map(|coedge| coedge.edge_id)).collect();
990    ids.iter().enumerate().map(|(at, id)| ids[..at].iter().position(|earlier| earlier == id).unwrap_or(at)).collect()
991}
992
993fn walk_face_signature<F: FnMut(f64) -> bool>(face: &FaceRecord, switches: f64, visit: &mut F) -> bool {
994    let slots = coedge_slots(face);
995    let mut flat = 0usize;
996    let surface = &face.surface;
997    let point = |visit: &mut F, p: &crate::Vec4| visit(p.x) && visit(p.y) && visit(p.z) && visit(p.w);
998    if !(visit(switches)
999        && visit(if face.same_sense { 1.0 } else { 0.0 })
1000        && visit(surface.degree_u as f64)
1001        && visit(surface.degree_v as f64)
1002        && visit(surface.knots_u.len() as f64))
1003    {
1004        return false;
1005    }
1006    if !(surface.knots_u.iter().all(|&knot| visit(knot)) && visit(surface.knots_v.len() as f64)) {
1007        return false;
1008    }
1009    if !(surface.knots_v.iter().all(|&knot| visit(knot)) && visit(surface.control_points.len() as f64)) {
1010        return false;
1011    }
1012    for row in &surface.control_points {
1013        if !(visit(row.len() as f64) && row.iter().all(|p| point(visit, p))) {
1014            return false;
1015        }
1016    }
1017    if !visit(face.loops.len() as f64) {
1018        return false;
1019    }
1020    for loop_record in &face.loops {
1021        if !visit(loop_record.coedges.len() as f64) {
1022            return false;
1023        }
1024        for coedge in &loop_record.coedges {
1025            let curve = &coedge.pcurve;
1026            let slot = slots[flat];
1027            flat += 1;
1028            if !(visit(slot as f64)
1029                && visit(if coedge.forward { 1.0 } else { 0.0 })
1030                && visit(curve.degree as f64)
1031                && visit(curve.knots.len() as f64))
1032            {
1033                return false;
1034            }
1035            if !(curve.knots.iter().all(|&knot| visit(knot)) && visit(curve.control_points.len() as f64)) {
1036                return false;
1037            }
1038            if !curve.control_points.iter().all(|p| point(visit, p)) {
1039                return false;
1040            }
1041        }
1042    }
1043    true
1044}
1045
1046/// The cache's hash of a face: its signature's every count, the switches and
1047/// sense, the surface's first and last control point, and each pcurve's
1048/// first and last knot and control point, each value by its bits. Two faces
1049/// whose signatures agree to the bit hash the same.
1050fn face_key_hash(face: &FaceRecord, switches: f64) -> u64 {
1051    use std::hash::Hasher;
1052    let slots = coedge_slots(face);
1053    let mut flat = 0usize;
1054    let mut hasher = rustc_hash::FxHasher::default();
1055    let mut write = |value: f64| hasher.write_u64(value.to_bits());
1056    let surface = &face.surface;
1057    write(switches);
1058    write(if face.same_sense { 1.0 } else { 0.0 });
1059    write(surface.degree_u as f64);
1060    write(surface.degree_v as f64);
1061    write(surface.knots_u.len() as f64);
1062    write(surface.knots_v.len() as f64);
1063    write(surface.control_points.len() as f64);
1064    let corners = [surface.control_points.first().and_then(|row| row.first()), surface.control_points.last().and_then(|row| row.last())];
1065    for p in corners.into_iter().flatten() {
1066        [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
1067    }
1068    write(face.loops.len() as f64);
1069    for loop_record in &face.loops {
1070        write(loop_record.coedges.len() as f64);
1071        for coedge in &loop_record.coedges {
1072            let curve = &coedge.pcurve;
1073            write(slots[flat] as f64);
1074            flat += 1;
1075            write(if coedge.forward { 1.0 } else { 0.0 });
1076            write(curve.degree as f64);
1077            write(curve.knots.len() as f64);
1078            write(curve.control_points.len() as f64);
1079            for knot in [curve.knots.first(), curve.knots.last()].into_iter().flatten() {
1080                write(*knot);
1081            }
1082            for p in [curve.control_points.first(), curve.control_points.last()].into_iter().flatten() {
1083                [p.x, p.y, p.z, p.w].into_iter().for_each(&mut write);
1084            }
1085        }
1086    }
1087    hasher.finish()
1088}
1089
1090/// Where `face` is in the cache's `entries`, compared exactly.
1091fn cached_entry(
1092    entries: &[(u64, Vec<f64>, std::rc::Rc<PreparedFace>)],
1093    face: &FaceRecord,
1094    switches: f64,
1095    hash: u64,
1096) -> Option<usize> {
1097    entries.iter().position(|(entry_hash, signature, _)| {
1098        if *entry_hash != hash {
1099            return false;
1100        }
1101        let mut at = 0;
1102        let walked = walk_face_signature(face, switches, &mut |value: f64| {
1103            let same = signature
1104                .get(at)
1105                .is_some_and(|stored| stored.to_bits() == value.to_bits() && !value.is_nan());
1106            at += 1;
1107            same
1108        });
1109        walked && at == signature.len()
1110    })
1111}
1112
1113/// Empties this thread's prepared-face cache, spherical regions included, and
1114/// its loop-sample memo. For the boolean's operand-state instrument
1115/// (`BREP_DEBUG_OPERAND_STATE=tls`) only.
1116pub fn forget_prepared_faces() {
1117    PREPARED_FACES.with(|cache| cache.borrow_mut().entries.clear());
1118    LOOP_SAMPLE_MEMO.with(|memo| {
1119        let mut memo = memo.borrow_mut();
1120        memo.entries.clear();
1121        memo.points = 0;
1122    });
1123}
1124
1125
1126/// `face`'s prepared data if a query on this thread prepared it and it is
1127/// still cached, without touching the cache: a caller that only wants the
1128/// lane ([`containment_lane`]) must not push out the faces queries are using.
1129fn cached_prepared_face(face: &FaceRecord) -> Option<std::rc::Rc<PreparedFace>> {
1130    PREPARED_FACES.with(|cache| {
1131        let PreparedFaceCache { entries } = &*cache.borrow();
1132        let switches = lane_switches();
1133        let hash = face_key_hash(face, switches);
1134        cached_entry(entries, face, switches, hash).map(|index| entries[index].2.clone())
1135    })
1136}
1137
1138pub fn prepared_face(face: &FaceRecord) -> std::rc::Rc<PreparedFace> {
1139    PREPARED_FACES.with(|cache| {
1140        let PreparedFaceCache { entries } = &mut *cache.borrow_mut();
1141        let switches = lane_switches();
1142        let hash = face_key_hash(face, switches);
1143        if let Some(index) = cached_entry(entries, face, switches, hash) {
1144            if index != 0 {
1145                let entry = entries.remove(index);
1146                entries.insert(0, entry);
1147            }
1148            return entries[0].2.clone();
1149        }
1150        let mut signature = Vec::new();
1151        walk_face_signature(face, switches, &mut |value: f64| {
1152            signature.push(value);
1153            true
1154        });
1155        let prepared = std::rc::Rc::new(PreparedFace::new());
1156        entries.insert(0, (hash, signature, prepared.clone()));
1157        entries.truncate(PREPARED_FACE_CACHE_ENTRIES);
1158        containment_profile(|p| p.cache_misses += 1);
1159        prepared
1160    })
1161}
1162
1163/// Point-in-face for a DOUBLY-periodic (torus) seam-band face, whose material
1164/// region the raw even-odd/tangent test below gets wrong: the constant-level
1165/// seam rim is a zero-area iso line and the wavy cut's own polygon encloses only
1166/// the thin strip it bounds, so a point in the band reads Outside (or flips on
1167/// the fragile nearest-tangent refinement). Reconstruct the band as one simple
1168/// (u,v) polygon — identical topology to the mass integrator and tessellator —
1169/// and test the point against it, so all three subsystems agree on the material
1170/// side. Returns None (keep the general path) for every other face.
1171fn prepare_seam_band(face: &FaceRecord) -> Result<SeamBandPrep, String> {
1172    if face.surface.closed_directions()? != (true, true) {
1173        return Ok(SeamBandPrep::NotApplicable);
1174    }
1175    let [u0, u1] = face.surface.domain_u()?;
1176    let [v0, v1] = face.surface.domain_v()?;
1177    if crate::topology::doubly_periodic_has_only_collapsed_loops(face)? {
1178        return Ok(SeamBandPrep::AlwaysInside);
1179    }
1180    let u_span = (u1 - u0).abs().max(1e-30);
1181    let v_span = (v1 - v0).abs().max(1e-30);
1182    let mut loops_uv: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
1183    // Which face loop each retained entry came from: the collapsed punctures
1184    // dropped below make the two lists disagree, and the merged-band lane needs
1185    // the ORIGINAL coedges of the loop it is about to unwrap.
1186    let mut retained: Vec<usize> = Vec::with_capacity(face.loops.len());
1187    for (loop_index, loop_record) in face.loops.iter().enumerate() {
1188        let mut points: Vec<[f64; 2]> = Vec::new();
1189        for coedge in &loop_record.coedges {
1190            let [d0, d1] = coedge.pcurve.domain()?;
1191            let samples = 24;
1192            for k in 0..=samples {
1193                let t = trim_station(d0, d1, k, samples);
1194                let p = coedge.pcurve.evaluate(t)?;
1195                points.push([p.x, p.y]);
1196            }
1197        }
1198        let (mut umin, mut umax, mut vmin, mut vmax) = (
1199            f64::INFINITY,
1200            f64::NEG_INFINITY,
1201            f64::INFINITY,
1202            f64::NEG_INFINITY,
1203        );
1204        for p in &points {
1205            umin = umin.min(p[0]);
1206            umax = umax.max(p[0]);
1207            vmin = vmin.min(p[1]);
1208            vmax = vmax.max(p[1]);
1209        }
1210        // Mirror `mass_properties::biperiodic_band_range`: a torus has no
1211        // geometric pole, so a VERTEX_LOOP whose whole pcurve trace collapses
1212        // to one parameter point is a zero-area puncture, not a band boundary.
1213        //
1214        // This used to drop the puncture only on faces with MORE than two loops,
1215        // to leave "ordinary two-loop torus classification" alone. That gate was
1216        // wrong, and mass integration never had it: one merged seam-carrying band
1217        // plus one puncture IS a two-loop face, and keeping the puncture put it at
1218        // `loops_uv.len() == 2`, where the two-loop analyses both decline (a
1219        // collapsed loop never full-wraps) and the face fell through to the plain
1220        // even-odd — whose verdict across a seam-wrapped band is the COMPLEMENT.
1221        // Measured on `anotherBooleanFail`'s imported body: face 280 read its
1222        // material band as v ∈ [0.125, 0.875] where its puncture-free twin face
1223        // 166 reads v ∈ [0.875, 1] ∪ [0, 0.125], and a ray crossing there was
1224        // silently lost, so points OpenCASCADE calls interior classified `Out`.
1225        // A zero-area point removes no material from any face, so drop it
1226        // wherever it appears; the all-collapsed case (an untrimmed torus written
1227        // as a sole VERTEX_LOOP) is already answered above, so at least one real
1228        // loop always survives.
1229        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
1230            continue;
1231        }
1232        retained.push(loop_index);
1233        loops_uv.push(points);
1234    }
1235    // MERGED SEAM-CARRYING BAND (single loop): `insert_periodic_band_seam_edges`
1236    // fuses a wrapped band's two rims into ONE loop joined by seam columns, so
1237    // the two-loop paths below never see it, and the plain even-odd polygon
1238    // carries a period-magnitude hop at each rim→column junction (a phantom
1239    // diagonal across the domain) that misclassifies the whole middle zone.
1240    // Unwrap the loop onto the covering plane (`loop_seam_offsets`, the same
1241    // fold mass integration and tessellation use), where it IS a simple
1242    // polygon, and even-odd the query's period images against it. Gated on a
1243    // genuinely seam-crossing single loop on a doubly-periodic surface; every
1244    // other face falls through unchanged. Hatch: BREP_SEAM_BAND_MERGED=0.
1245    if loops_uv.len() == 1 && switch!(SEAM_BAND_MERGED_SWITCH, true) {
1246        let coedges = &face.loops[retained[0]].coedges;
1247        let offsets = crate::topology::loop_seam_offsets(coedges, true, true, u_span, v_span)?;
1248        if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
1249            let mut polygon: Vec<Vec2> = Vec::new();
1250            for (coedge_index, coedge) in coedges.iter().enumerate() {
1251                let [d0, d1] = coedge.pcurve.domain()?;
1252                let samples = 24;
1253                for k in 0..samples {
1254                    let t = trim_station(d0, d1, k, samples);
1255                    let p = coedge.pcurve.evaluate(t)?;
1256                    polygon.push(Vec2 {
1257                        x: p.x + offsets[coedge_index][0],
1258                        y: p.y + offsets[coedge_index][1],
1259                    });
1260                }
1261            }
1262            return Ok(SeamBandPrep::Merged { polygon, u_span, v_span });
1263        }
1264    }
1265    if loops_uv.len() != 2 {
1266        return Ok(SeamBandPrep::Declined);
1267    }
1268    if let Some(band) = crate::topology::analyze_doubly_periodic_seam_band(
1269        &loops_uv,
1270        [u0, u1, v0, v1],
1271        face.same_sense,
1272    ) {
1273        let polygon: Vec<Vec2> =
1274            crate::topology::seam_band_uv_polygon(&loops_uv, [u0, u1, v0, v1], &band)
1275                .into_iter()
1276                .map(|p| Vec2 { x: p[0], y: p[1] })
1277                .collect();
1278        return Ok(SeamBandPrep::Analyzed { polygon });
1279    }
1280    // TWO clean full-wrap rims are the companion `biperiodic_band_range` case,
1281    // with or without an extra collapsed puncture. Classify only the cross
1282    // parameter: the material is either the strip between the rims or its
1283    // periodic complement. The exact two-loop/full-wrap/constant-cross-level
1284    // gates below mirror mass integration and tessellation; every other torus
1285    // face retains the general classifier.
1286    for p_is_u in [true, false] {
1287        let (period, q_extent) = if p_is_u {
1288            (u1 - u0, v_span)
1289        } else {
1290            (v1 - v0, u_span)
1291        };
1292        if !(period > 0.0) {
1293            continue;
1294        }
1295        let coord = |p: &[f64; 2]| if p_is_u { (p[0], p[1]) } else { (p[1], p[0]) };
1296        let mut rings = Vec::with_capacity(2);
1297        for points in &loops_uv {
1298            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
1299                f64::INFINITY,
1300                f64::NEG_INFINITY,
1301                f64::INFINITY,
1302                f64::NEG_INFINITY,
1303            );
1304            for p in points {
1305                let (periodic, cross) = coord(p);
1306                pmin = pmin.min(periodic);
1307                pmax = pmax.max(periodic);
1308                qmin = qmin.min(cross);
1309                qmax = qmax.max(cross);
1310            }
1311            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
1312                rings.clear();
1313                break;
1314            }
1315            let mut net = 0.0;
1316            for pair in points.windows(2) {
1317                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
1318                if delta > 0.5 * period {
1319                    delta -= period;
1320                } else if delta < -0.5 * period {
1321                    delta += period;
1322                }
1323                net += delta;
1324            }
1325            let direction = if net > 0.25 * period {
1326                1
1327            } else if net < -0.25 * period {
1328                -1
1329            } else {
1330                0
1331            };
1332            rings.push((0.5 * (qmin + qmax), direction));
1333        }
1334        if rings.len() != 2 {
1335            continue;
1336        }
1337        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
1338        let [(q_lo, lower_direction), (q_hi, upper_direction)] = rings.as_slice() else {
1339            unreachable!()
1340        };
1341        let inconclusive =
1342            *lower_direction == 0 || *upper_direction == 0 || lower_direction == upper_direction;
1343        let between_is_ccw_uv = if p_is_u {
1344            *lower_direction > 0
1345        } else {
1346            *lower_direction < 0
1347        };
1348        let complement = !inconclusive && between_is_ccw_uv != face.same_sense;
1349        return Ok(SeamBandPrep::Rings {
1350            p_is_u,
1351            q_lo: *q_lo,
1352            q_hi: *q_hi,
1353            complement,
1354        });
1355    }
1356    Ok(SeamBandPrep::Declined)
1357}
1358
1359fn seam_band_point_in_face(
1360    prepared: &SeamBandPrep,
1361    point: Vec2,
1362    tolerance: f64,
1363) -> Option<PolygonClass> {
1364    match prepared {
1365        SeamBandPrep::NotApplicable | SeamBandPrep::Declined => None,
1366        SeamBandPrep::AlwaysInside => Some(PolygonClass::Inside),
1367        SeamBandPrep::Merged { polygon, u_span, v_span } => {
1368            let mut best = PolygonClass::Outside;
1369            'images: for du in [-1.0, 0.0, 1.0] {
1370                for dv in [-1.0, 0.0, 1.0] {
1371                    let image = Vec2 {
1372                        x: point.x + du * u_span,
1373                        y: point.y + dv * v_span,
1374                    };
1375                    match point_in_polygon(image, polygon, tolerance) {
1376                        PolygonClass::Boundary => {
1377                            best = PolygonClass::Boundary;
1378                            break 'images;
1379                        }
1380                        PolygonClass::Inside => best = PolygonClass::Inside,
1381                        PolygonClass::Outside => {}
1382                    }
1383                }
1384            }
1385            Some(best)
1386        }
1387        SeamBandPrep::Analyzed { polygon } => Some(point_in_polygon(point, polygon, tolerance)),
1388        SeamBandPrep::Rings { p_is_u, q_lo, q_hi, complement } => {
1389            let q = if *p_is_u { point.y } else { point.x };
1390            if (q - q_lo).abs() <= tolerance || (q - q_hi).abs() <= tolerance {
1391                return Some(PolygonClass::Boundary);
1392            }
1393            let between = q > *q_lo && q < *q_hi;
1394            Some(if between != *complement {
1395                PolygonClass::Inside
1396            } else {
1397                PolygonClass::Outside
1398            })
1399        }
1400    }
1401}
1402
1403/// Point-in-face for a SINGLY-PERIODIC face with a SEAM-STRADDLING loop: a
1404/// trim loop crossing the u seam is stored with its samples folded into the
1405/// domain, so its flat polygon is TORN at the seam and plain even-odd
1406/// misclassifies near the tear (STEP 00000585-family: face 519's big inner
1407/// loop straddles the seam and a REAL section sub-segment between two accepted
1408/// pieces read Outside in `process_curve`'s midpoint gate — trial 174's
1409/// missing middle segment). Mirror fragment.rs's proven seam-straddling
1410/// fallback: UNWRAP every loop by accumulating period-folded deltas (a
1411/// zero-winding loop closes in the covering plane), then even-odd the query at
1412/// its −P/0/+P period images across all unwrapped loops. Fires only when the
1413/// face is closed in exactly u, has >2 loops, and at least one loop straddles
1414/// the seam (≥1 fold jump); every other face returns None and keeps the plain
1415/// classifier bit-identically. Loops that WIND the period (net winding ≠ 0)
1416/// do not close under unwrapping — bail to the plain path rather than guess.
1417/// Escape hatch `BREP_HORIZON_CONTAINMENT=0`.
1418fn prepare_wrapped_horizon(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<HorizonPrep>, String> {
1419    if face.surface.closed_directions()? != (true, false) || face.loops.is_empty() {
1420        return Ok(None);
1421    }
1422    if !switch!(HORIZON_CONTAINMENT_SWITCH, true) {
1423        return Ok(None);
1424    }
1425    // SINGLE/DOUBLE-LOOP straddlers (t91's face 675: ONE loop drawn in-domain
1426    // that hops the u-seam twice, trimming a sliver strip AT the seam) used
1427    // to be excluded by a `loops.len() <= 2` gate and fell to the plain
1428    // even-odd, whose verdict on the hopped polygon is INVERTED (the strip
1429    // interior read Outside, far azimuths read Inside) — minting bogus
1430    // far-azimuth section pieces and discarding the real ones. The unwrap +
1431    // period-image even-odd below is loop-count-agnostic, so the gate now
1432    // only requires a non-empty loop set; non-straddling loops still bail to
1433    // the plain path unchanged. Escape hatch: BREP_HORIZON_SINGLE_LOOP=0
1434    // restores the old minimum.
1435    if face.loops.len() <= 2 && !switch!(HORIZON_SINGLE_LOOP_SWITCH, true) {
1436        return Ok(None);
1437    }
1438    let [u0, u1] = face.surface.domain_u()?;
1439    let u_period = u1 - u0;
1440    if u_period <= 0.0 {
1441        return Ok(None);
1442    }
1443    let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1444    let mut loops: Vec<Vec<Vec2>> = Vec::new();
1445    let mut straddling = false;
1446    for loop_index in 0..face.loops.len() {
1447        let points = loop_samples(prepared, face, loop_index)?;
1448        if points.len() < 3 {
1449            continue;
1450        }
1451        // Unwrap into the covering plane: place each sample at the previous
1452        // one plus the period-folded delta. A seam-straddling loop becomes a
1453        // continuous closed polygon; a WINDING loop does not close — bail.
1454        let mut unwrapped = Vec::with_capacity(points.len());
1455        let mut jumps = 0usize;
1456        let mut cursor = points[0];
1457        unwrapped.push(cursor);
1458        for pair in points.windows(2) {
1459            let mut du = pair[1].x - pair[0].x;
1460            let folded = du - u_period * (du / u_period).round();
1461            if (du - folded).abs() > 0.25 * u_period {
1462                jumps += 1;
1463            }
1464            du = folded;
1465            cursor = Vec2 {
1466                x: cursor.x + du,
1467                y: pair[1].y,
1468            };
1469            unwrapped.push(cursor);
1470        }
1471        let closure = (unwrapped[0].x - unwrapped[unwrapped.len() - 1].x).abs();
1472        if closure > 0.25 * u_period {
1473            if debug {
1474                eprintln!(
1475                    "horizon: face {} loop winds the period (closure {closure:.3}) — bail",
1476                    face.id
1477                );
1478            }
1479            return Ok(None); // winding loop: unwrapping cannot close it
1480        }
1481        if jumps > 0 {
1482            straddling = true;
1483        }
1484        loops.push(unwrapped);
1485    }
1486    if !straddling || loops.is_empty() {
1487        return Ok(None);
1488    }
1489    Ok(Some(HorizonPrep {
1490        loops,
1491        u_period,
1492        index: std::cell::OnceCell::new(),
1493    }))
1494}
1495
1496fn wrapped_horizon_point_in_face(
1497    face: &FaceRecord,
1498    prepared: &HorizonPrep,
1499    point: Vec2,
1500    tolerance: f64,
1501    scan: ChordScan,
1502) -> Option<PolygonClass> {
1503    let HorizonPrep { loops, u_period, index } = prepared;
1504    let u_period = *u_period;
1505    let debug = std::env::var("BREP_DEBUG_HORIZON").is_ok();
1506    // Even-odd on the QUOTIENT cylinder: each unwrapped loop is tested at
1507    // every period image of the query and contributes its own parity. The old
1508    // combining ("any single image with an odd crossing count ⇒ Inside") is
1509    // wrong whenever two loops live in DIFFERENT period frames after
1510    // unwrapping — t181/00000312#p7: face 519's seam-straddling HOLE unwraps
1511    // to u∈[−0.039, 0.039] while the outer rectangle spans [0, 1], so a query
1512    // inside the hole at u≈0.986 is contained by the outer loop at shift 0
1513    // (odd ⇒ Inside) and by the hole at shift −P (odd ⇒ Inside again); the
1514    // true even count (outer + hole = 2 ⇒ Outside) is never assembled at any
1515    // single image. Fragment selection then kept a PHANTOM half-hole region
1516    // whose boundary (half the hole loop + a derived chord) minted same-sense
1517    // coedges at assembly. Summing per-loop parities across images restores
1518    // the covering-space even-odd. Escape hatch: BREP_HORIZON_CROSS_FRAME=0
1519    // restores the old per-image combining.
1520    if !horizon_cross_frame() {
1521        let mut best: Option<PolygonClass> = None;
1522        for shift in [-u_period, 0.0, u_period] {
1523            let image = Vec2 {
1524                x: point.x + shift,
1525                y: point.y,
1526            };
1527            let mut crossings = 0usize;
1528            for polygon in loops {
1529                match point_in_polygon(image, polygon, tolerance) {
1530                    PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1531                    PolygonClass::Inside => crossings += 1,
1532                    PolygonClass::Outside => {}
1533                }
1534            }
1535            if crossings % 2 == 1 {
1536                best = Some(PolygonClass::Inside);
1537            } else if best.is_none() {
1538                best = Some(PolygonClass::Outside);
1539            }
1540        }
1541        if debug {
1542            eprintln!(
1543                "horizon: face {} loops={} straddling (legacy per-image) -> {:?}",
1544                face.id,
1545                loops.len(),
1546                best
1547            );
1548        }
1549        return best;
1550    }
1551    let images = [-u_period, 0.0, u_period].map(|shift| Vec2 {
1552        x: point.x + shift,
1553        y: point.y,
1554    });
1555    let chords: usize = loops.iter().map(Vec::len).sum();
1556    let indexed = (scan.indexes(chords) && images.iter().all(|image| in_index_range(*image)))
1557        .then(|| index.get_or_init(|| ChordIndex::build(loops.as_slice())).as_ref())
1558        .flatten();
1559    let mut crossings = 0usize;
1560    if let Some(index) = indexed {
1561        // The per-loop parities summed over the images, as the scan below
1562        // sums them: `Boundary` if any image is within the band of any chord,
1563        // otherwise each loop's crossings flipped across all three images.
1564        let loops = loops.as_slice();
1565        if images.iter().any(|image| index.any_within(loops, *image, tolerance)) {
1566            return Some(PolygonClass::Boundary);
1567        }
1568        let mut odd = vec![false; loops.len()];
1569        for image in images {
1570            index.flip_crossings(loops, image, &mut odd);
1571        }
1572        crossings = odd.into_iter().filter(|&parity| parity).count();
1573    } else {
1574        for polygon in loops {
1575            let mut image_hits = 0usize;
1576            for image in images {
1577                match point_in_polygon(image, polygon, tolerance) {
1578                    PolygonClass::Boundary => return Some(PolygonClass::Boundary),
1579                    PolygonClass::Inside => image_hits += 1,
1580                    PolygonClass::Outside => {}
1581                }
1582            }
1583            crossings += image_hits % 2;
1584        }
1585    }
1586    let class = if crossings % 2 == 1 {
1587        PolygonClass::Inside
1588    } else {
1589        PolygonClass::Outside
1590    };
1591    if debug {
1592        eprintln!(
1593            "horizon: face {} loops={} straddling -> {:?}",
1594            face.id,
1595            loops.len(),
1596            class
1597        );
1598    }
1599    Some(class)
1600}
1601
1602/// Classify a spherical cap represented by a varying full-wrap contact rim and
1603/// the oppositely wound collapsed rim at one sphere pole.  This is the natural
1604/// topology when a circle about an oblique axis encloses a pole of the sphere's
1605/// stored parameter frame.
1606fn prepare_winding_sphere_cap(face: &FaceRecord, prepared: &PreparedFace) -> Result<Option<SphereCapPrep>, String> {
1607    if !matches!(
1608        face.surface.analytic(),
1609        Some(crate::AnalyticSurface::Sphere { .. })
1610    ) || face.surface.closed_directions()? != (true, false)
1611        || face.loops.len() != 2
1612    {
1613        return Ok(None);
1614    }
1615    let [u0, u1] = face.surface.domain_u()?;
1616    let [v0, v1] = face.surface.domain_v()?;
1617    let period = u1 - u0;
1618    let v_span = v1 - v0;
1619    if !(period > 0.0 && v_span > 0.0) {
1620        return Ok(None);
1621    }
1622    struct WindingLoop {
1623        points: Vec<Vec2>,
1624        winding: f64,
1625        vmin: f64,
1626        vmax: f64,
1627    }
1628    let mut loops = Vec::with_capacity(2);
1629    for loop_index in 0..face.loops.len() {
1630        let points = loop_samples(prepared, face, loop_index)?;
1631        if points.len() < 2 {
1632            return Ok(None);
1633        }
1634        let first = points[0];
1635        let mut cursor = first;
1636        let mut unwrapped = vec![cursor];
1637        for next in points.iter().skip(1) {
1638            let du = next.x - cursor.x;
1639            let folded = du - period * (du / period).round();
1640            cursor = Vec2 {
1641                x: cursor.x + folded,
1642                y: next.y,
1643            };
1644            unwrapped.push(cursor);
1645        }
1646        let last_raw = *points.last().unwrap();
1647        let closing_du = first.x - last_raw.x;
1648        let closing_folded = closing_du - period * (closing_du / period).round();
1649        let winding = cursor.x + closing_folded - first.x;
1650        let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1651        for p in &unwrapped {
1652            vmin = vmin.min(p.y);
1653            vmax = vmax.max(p.y);
1654        }
1655        loops.push(WindingLoop {
1656            points: unwrapped,
1657            winding,
1658            vmin,
1659            vmax,
1660        });
1661    }
1662    if loops
1663        .iter()
1664        .any(|loop_data| (loop_data.winding.abs() - period).abs() > 0.05 * period)
1665        || loops[0].winding * loops[1].winding >= 0.0
1666    {
1667        return Ok(None);
1668    }
1669    let flat = |loop_data: &WindingLoop| loop_data.vmax - loop_data.vmin <= 1e-6 * v_span;
1670    let (pole, rim) = match (flat(&loops[0]), flat(&loops[1])) {
1671        (true, false) => (&loops[0], &loops[1]),
1672        (false, true) => (&loops[1], &loops[0]),
1673        _ => return Ok(None),
1674    };
1675    let pole_v = 0.5 * (pole.vmin + pole.vmax);
1676    if (pole_v - v0).abs() > 1e-6 * v_span && (pole_v - v1).abs() > 1e-6 * v_span {
1677        return Ok(None);
1678    }
1679    Ok(Some(SphereCapPrep {
1680        rim: rim.points.clone(),
1681        pole_v,
1682        period,
1683    }))
1684}
1685
1686fn winding_sphere_cap_point_in_face(
1687    prepared: &SphereCapPrep,
1688    point: Vec2,
1689    tolerance: f64,
1690) -> Option<PolygonClass> {
1691    let SphereCapPrep { rim, pole_v, period } = prepared;
1692    let (pole_v, period) = (*pole_v, *period);
1693    let window_start = rim[0].x.min(rim[rim.len() - 1].x);
1694    let query_u = window_start + (point.x - window_start).rem_euclid(period);
1695    let mut crossings = Vec::new();
1696    for pair in rim.windows(2) {
1697        let (a, b) = (pair[0], pair[1]);
1698        if (a.x > query_u) != (b.x > query_u) {
1699            crossings.push(a.y + (query_u - a.x) / (b.x - a.x) * (b.y - a.y));
1700        }
1701        for image in [-period, 0.0, period] {
1702            if point_segment_distance(
1703                Vec2 {
1704                    x: point.x + image,
1705                    y: point.y,
1706                },
1707                a,
1708                b,
1709            ) <= tolerance
1710            {
1711                return Some(PolygonClass::Boundary);
1712            }
1713        }
1714    }
1715    let rim_v = crossings
1716        .into_iter()
1717        .min_by(|a, b| (a - point.y).abs().total_cmp(&(b - point.y).abs()))?;
1718    let inside = if pole_v < rim_v {
1719        point.y <= rim_v + tolerance
1720    } else {
1721        point.y >= rim_v - tolerance
1722    };
1723    Some(if inside {
1724        PolygonClass::Inside
1725    } else {
1726        PolygonClass::Outside
1727    })
1728}
1729
1730/// Point-in-face for a SINGLY-PERIODIC (closed-u) FULL-BAND STRIP whose two
1731/// full-wrap rim loops are drawn as COVERING-PLANE pcurves running OUT OF the
1732/// u-domain by up to a whole period (case 08:10-genus face 1513, the 4th seam
1733/// representation after helmet-unwrapped / band-complement / 675-hops): the
1734/// raw even-odd sees u-winding loop polygons whose parity is meaningless, so
1735/// nearly the whole material strip reads Outside, the marched clip crumbles
1736/// the section curves to sub-mm bits, and the neighbours strand one-use.
1737///
1738/// The material region is the strip BETWEEN the two rims: on an open-v
1739/// surface a 2-loop face whose loops both wrap the full period has no other
1740/// representable region. The verdict is a sampled per-u hull — each rim is a
1741/// single periodic polyline v = rim(u) in the covering plane, and the query
1742/// point is between the rims iff an upward (+v) vertical ray at the query's
1743/// u (folded modulo the period into each rim's own one-period window) crosses
1744/// the two rim polylines an odd number of times in total. NO flat-level
1745/// approximation is used (the rims are scalloped: 1513's upper rim is flat at
1746/// v=1 on parts of u but dips to v=0.745 elsewhere — a v-between-extremes
1747/// rule is provably wrong on it).
1748///
1749/// STRUCTURAL gates (all must hold; anything else returns None and keeps the
1750/// previous classification bit-identically):
1751///   - surface closed in exactly u; exactly 2 loops;
1752///   - at least one loop's samples run OUT of the u-domain by >1e-3 period
1753///     (the covering-plane discriminator — in-domain 2-rim bands keep their
1754///     current path);
1755///   - each loop's unwrapped net u-travel is exactly ±one period and its v
1756///     closes (a true full-wrap rim, not a partial arc);
1757///   - opposite travel directions, disjoint v-hulls, and the material-left
1758///     winding rule confirming the BETWEEN strip (a complement verdict cannot
1759///     be represented on an open-v surface — decline, never guess).
1760/// Escape hatch: BREP_COVERING_RIM_STRIP=0.
1761fn prepare_covering_rim_strip(face: &FaceRecord) -> Result<Option<RimStripPrep>, String> {
1762    if face.surface.closed_directions()? != (true, false) || face.loops.len() != 2 {
1763        return Ok(None);
1764    }
1765    if !switch!(COVERING_RIM_STRIP_SWITCH, true) {
1766        return Ok(None);
1767    }
1768    let [u0, u1] = face.surface.domain_u()?;
1769    let [v0, v1] = face.surface.domain_v()?;
1770    let period = u1 - u0;
1771    if !(period > 0.0) {
1772        return Ok(None);
1773    }
1774    let v_span = (v1 - v0).abs().max(1e-30);
1775    struct Rim {
1776        points: Vec<Vec2>,
1777        vmin: f64,
1778        vmax: f64,
1779        ascending: bool,
1780    }
1781    let mut rims: Vec<Rim> = Vec::with_capacity(2);
1782    let mut out_of_domain = false;
1783    for loop_record in &face.loops {
1784        let mut points: Vec<Vec2> = Vec::new();
1785        for coedge in &loop_record.coedges {
1786            let curve = &coedge.pcurve;
1787            let [start, end] = curve.domain()?;
1788            let sample_count = trim_sample_count(curve);
1789            for index in 0..=sample_count {
1790                let parameter = trim_station(start, end, index, sample_count);
1791                let evaluated = curve.evaluate(parameter)?;
1792                points.push(Vec2 {
1793                    x: evaluated.x,
1794                    y: evaluated.y,
1795                });
1796            }
1797        }
1798        if points.len() < 3 {
1799            return Ok(None);
1800        }
1801        // Covering-plane discriminator: this lane exists for loops drawn PAST
1802        // the domain; everything in-domain keeps the existing classifiers.
1803        for p in &points {
1804            if p.x < u0 - 1e-3 * period || p.x > u1 + 1e-3 * period {
1805                out_of_domain = true;
1806            }
1807        }
1808        // Unwrap into the covering plane (period-folded deltas — a no-op for
1809        // an already-continuous covering-plane representation, and the same
1810        // fold the horizon lane uses for in-domain seam hops).
1811        let mut unwrapped: Vec<Vec2> = Vec::with_capacity(points.len());
1812        let mut cursor = points[0];
1813        unwrapped.push(cursor);
1814        for pair in points.windows(2) {
1815            let du = pair[1].x - pair[0].x;
1816            let folded = du - period * (du / period).round();
1817            cursor = Vec2 {
1818                x: cursor.x + folded,
1819                y: pair[1].y,
1820            };
1821            unwrapped.push(cursor);
1822        }
1823        let net = unwrapped[unwrapped.len() - 1].x - unwrapped[0].x;
1824        if (net.abs() - period).abs() > 2e-2 * period {
1825            return Ok(None); // not a clean single full wrap
1826        }
1827        if (unwrapped[unwrapped.len() - 1].y - unwrapped[0].y).abs() > 1e-3 * v_span {
1828            return Ok(None); // rim does not close in v
1829        }
1830        let (mut vmin, mut vmax) = (f64::INFINITY, f64::NEG_INFINITY);
1831        for p in &unwrapped {
1832            vmin = vmin.min(p.y);
1833            vmax = vmax.max(p.y);
1834        }
1835        rims.push(Rim {
1836            points: unwrapped,
1837            vmin,
1838            vmax,
1839            ascending: net > 0.0,
1840        });
1841    }
1842    if !out_of_domain {
1843        return Ok(None);
1844    }
1845    if rims[0].ascending == rims[1].ascending {
1846        return Ok(None); // rims must traverse opposite u directions
1847    }
1848    let (lower, upper) = if rims[0].vmax <= rims[1].vmin {
1849        (&rims[0], &rims[1])
1850    } else if rims[1].vmax <= rims[0].vmin {
1851        (&rims[1], &rims[0])
1852    } else {
1853        return Ok(None); // interleaved v-hulls: not a clean strip
1854    };
1855    if upper.vmin - lower.vmax <= 1e-6 * v_span {
1856        return Ok(None);
1857    }
1858    // Material-left rule (same convention as the doubly-periodic band lanes):
1859    // the between strip is CCW in uv iff the LOWER rim travels +u; that must
1860    // match the face sense, else the material would be the complement — which
1861    // an open-v surface cannot represent. Decline rather than guess.
1862    if (lower.ascending) != face.same_sense {
1863        return Ok(None);
1864    }
1865    Ok(Some(RimStripPrep {
1866        lower: lower.points.clone(),
1867        upper: upper.points.clone(),
1868        period,
1869    }))
1870}
1871
1872fn covering_rim_strip_point_in_face(
1873    prepared: &RimStripPrep,
1874    point: Vec2,
1875    tolerance: f64,
1876) -> Option<PolygonClass> {
1877    let RimStripPrep { lower, upper, period } = prepared;
1878    let period = *period;
1879    // Boundary: proximity to either rim polyline at the query's period images.
1880    for rim in [lower, upper] {
1881        for shift in [-period, 0.0, period] {
1882            let image = Vec2 {
1883                x: point.x + shift,
1884                y: point.y,
1885            };
1886            for pair in rim.windows(2) {
1887                if point_segment_distance(image, pair[0], pair[1]) <= tolerance {
1888                    return Some(PolygonClass::Boundary);
1889                }
1890            }
1891        }
1892    }
1893    // Sampled per-u hull: fold the query into each rim's own one-period
1894    // window and count upward-ray crossings; odd total = between the rims.
1895    let mut crossings = 0usize;
1896    for rim in [lower, upper] {
1897        let window_base = rim[0].x.min(rim[rim.len() - 1].x);
1898        let x = window_base + (point.x - window_base).rem_euclid(period);
1899        for pair in rim.windows(2) {
1900            let (a, b) = (pair[0], pair[1]);
1901            if (a.x > x) != (b.x > x) {
1902                let v_cross = a.y + (x - a.x) / (b.x - a.x) * (b.y - a.y);
1903                if v_cross > point.y {
1904                    crossings += 1;
1905                }
1906            }
1907        }
1908    }
1909    Some(if crossings % 2 == 1 {
1910        PolygonClass::Inside
1911    } else {
1912        PolygonClass::Outside
1913    })
1914}
1915
1916/// The generic scan's trim samples: every pcurve at `(interior knots + 1) ×
1917/// (degree + 1) × 4` chords, the closed polygon per loop, and the chord
1918/// parameters behind every polygon edge.
1919pub fn prepare_generic(face: &FaceRecord, prepared: &PreparedFace) -> Result<GenericPrep, String> {
1920    let slots = coedge_slots(face);
1921    let mut flat = 0usize;
1922    let mut loops: Vec<LoopSamples> = Vec::with_capacity(face.loops.len());
1923    let mut segments: Vec<Vec<SegmentPrep>> = Vec::with_capacity(face.loops.len());
1924    let mut chord_count = 0;
1925    for (loop_index, loop_record) in face.loops.iter().enumerate() {
1926        let polygon = loop_samples(prepared, face, loop_index)?;
1927        let mut chords = Vec::with_capacity(polygon.len());
1928        let mut coedges = Vec::with_capacity(loop_record.coedges.len());
1929        let mut first = 0;
1930        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1931            let curve = &coedge.pcurve;
1932            let [start, end] = curve.domain()?;
1933            let sample_count = trim_sample_count(curve);
1934            for index in 0..sample_count {
1935                let parameter = trim_station(start, end, index, sample_count);
1936                let parameter_end = if index + 1 < sample_count {
1937                    trim_station(start, end, index + 1, sample_count)
1938                } else {
1939                    end
1940                };
1941                chords.push(SegmentPrep {
1942                    coedge_index,
1943                    parameter_start: parameter,
1944                    parameter_end,
1945                });
1946            }
1947            coedges.push((slots[flat] as u64, first, sample_count));
1948            flat += 1;
1949            first += sample_count;
1950        }
1951        debug_assert_eq!(first, polygon.len());
1952        chord_count += chords.len();
1953        loops.push(LoopSamples { polygon, coedges });
1954        segments.push(chords);
1955    }
1956    containment_profile(|p| p.generic_chords += chord_count as u64);
1957    Ok(GenericPrep {
1958        loops,
1959        segments,
1960        chord_count,
1961        index: std::cell::OnceCell::new(),
1962    })
1963}
1964
1965/// One trim loop as [`parameter_point_in_face`] already sampled it: the closed
1966/// polygon it counts parity against, plus `(edge slot, first sample, sample count)`
1967/// per coedge in loop order (`coedge_slots`), which is all the spherical lane needs to drop a slit
1968/// and to rebuild the boundary as SEGMENTS rather than as one ring.
1969pub struct LoopSamples {
1970    polygon: std::rc::Rc<Vec<Vec2>>,
1971    coedges: Vec<(u64, usize, usize)>,
1972}
1973
1974/// Point-in-face for a SPHERICAL carrier, decided on the ball itself instead of
1975/// in its polar parameter domain — but ONLY in the far field, where the generic
1976/// path has nothing better than a parity count.
1977///
1978/// The generic classifier below does not really answer by parity.  Whenever the
1979/// query has a nearest trim segment whose foot is interior to that pcurve, it
1980/// answers by which SIDE of that curve the point is on, which is locally exact
1981/// and is what the imprint and the fragment builder are tuned against.  Parity is
1982/// its fallback for points further from every trim segment than that segment is
1983/// long — and parity is exactly what the polar domain breaks: a loop enclosing a
1984/// pole does not enclose it in `uv` (it wraps the domain instead), and a region
1985/// straddling the seam is not one polygon there at all.  Three separate special
1986/// cases in this file exist because of that.
1987///
1988/// So this lane engages on the complement of the refinement's condition: it
1989/// replaces the parity count and nothing else.  Material is the intersection of
1990/// the regions to the LEFT of each trim loop, and the side a point falls on is
1991/// the sign of the signed solid angle that loop subtends there — a question with
1992/// no parameter domain in it, so pole and seam need no mention.  A collapsed pole
1993/// loop has no area and a seam is traversed once each way; both cancel exactly.
1994///
1995/// [`crate::sphere_chart::SphericalRegion`] is the same classifier the chart
1996/// tessellation uses, so the trim query and the mesh cannot disagree about where
1997/// the material is.
1998fn sphere_chart_point_in_face(
1999    face: &FaceRecord,
2000    point: Vec2,
2001    prepared: &PreparedFace,
2002    sampled: &[LoopSamples],
2003) -> Result<Option<PolygonClass>, String> {
2004    let Some(atlas) = sphere_chart_atlas(face) else {
2005        return Ok(None);
2006    };
2007    if sphere_region_reduced_enabled() {
2008        let reduced = lane(&prepared.sphere_region_reduced, || build_sphere_region_reduced(face, &atlas, sampled))?;
2009        if let Some((region, margin)) = reduced {
2010            if !region.is_whole_sphere() && region.is_decidable() {
2011                let probe = face.surface.evaluate(point.x, point.y)?;
2012                if region.clear_of_boundary(atlas.centre, probe, *margin) {
2013                    return Ok(Some(if region.contains(atlas.centre, probe) {
2014                        PolygonClass::Inside
2015                    } else {
2016                        PolygonClass::Outside
2017                    }));
2018                }
2019            }
2020        }
2021    }
2022    let region = lane(&prepared.sphere_region, || build_sphere_region(face, &atlas, sampled))?;
2023    if region.is_whole_sphere() {
2024        return Ok(Some(PolygonClass::Inside));
2025    }
2026    if !region.is_decidable() {
2027        // No seed: decline to the generic path rather than answer Inside for
2028        // the whole ball.
2029        return Ok(None);
2030    }
2031    let probe = face.surface.evaluate(point.x, point.y)?;
2032    Ok(Some(if region.contains(atlas.centre, probe) {
2033        PolygonClass::Inside
2034    } else {
2035        PolygonClass::Outside
2036    }))
2037}
2038
2039/// `BREP_SPHERE_REGION_REDUCED` (default on, `=0` restores): see
2040/// [`build_sphere_region_reduced`].
2041fn sphere_region_reduced_enabled() -> bool {
2042    crate::switch!("BREP_SPHERE_REGION_REDUCED", true)
2043}
2044
2045/// Trims with fewer samples than this build only the full region.
2046const REDUCED_REGION_SAMPLES: usize = 4096;
2047
2048/// [`build_sphere_region`] from a reduced boundary, and the margin (radians on the
2049/// unit sphere) within which its answer may differ from the full region's.
2050///
2051/// The trim samples come from each pcurve's knots, not from the curve: a dimple's
2052/// rim on a ball, an exact circle, carries a fitted pcurve of 270 to 880 control
2053/// points and so 4 000 to 14 000 samples, and brep-bench boolean/golf-ball's ball
2054/// face after 54 cuts had 540 000, which every cut's imprint rebuilt the region
2055/// from (0.55 s a build, 50 of the case's 85 s). Each coedge's samples are kept
2056/// at a stride `k` counted from both of its ends (sample `i` stays when
2057/// `min(i, n - 1 - i)` is a multiple of `k`), so a coedge and its reverse keep the
2058/// same samples whatever their rounding; `k` is the largest of 32, 16, 8, 4, 2
2059/// whose dropped samples all lie within a tenth of the coedge's median chord
2060/// angle of the kept arcs, MEASURED. The regions differ only within the largest
2061/// such deviation of the kept arcs (plus the 1e-9 canonicalization of both), so a
2062/// point farther than twice it from every kept arc is material in one exactly
2063/// when it is in the other (`SphericalRegion::clear_of_boundary`); any other
2064/// point is read on the full region, built then.
2065pub fn build_sphere_region_reduced(
2066    face: &FaceRecord,
2067    atlas: &crate::sphere_chart::SphereAtlas,
2068    sampled: &[LoopSamples],
2069) -> Result<Option<(crate::sphere_chart::SphericalRegion, f64)>, String> {
2070    let total: usize = sampled.iter().map(|samples| samples.polygon.len()).sum();
2071    if total < REDUCED_REGION_SAMPLES {
2072        return Ok(None);
2073    }
2074    let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
2075    for slot in coedge_slots(face) {
2076        *uses.entry(slot as u64).or_insert(0) += 1;
2077    }
2078    let outward_face_normal = face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
2079    let memo = sphere_reduction_memo_enabled();
2080    let carrier = memo.then(|| {
2081        let mut lane = crate::mass_properties::TwoLane::new();
2082        crate::mass_properties::hash_surface(&mut lane, &face.surface);
2083        lane.finish()
2084    });
2085    let mut points: Vec<Vec3> = Vec::new();
2086    let mut spans: Vec<(usize, usize)> = Vec::new();
2087    let mut deviation = 0.0f64;
2088    for samples in sampled {
2089        let count = samples.polygon.len();
2090        if count < 2 {
2091            continue;
2092        }
2093        for &(edge_id, first, span) in &samples.coedges {
2094            if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
2095                continue;
2096            }
2097            let key = carrier.map(|carrier| {
2098                let mut lane = crate::mass_properties::TwoLane::new();
2099                lane.u64(carrier[0]);
2100                lane.u64(carrier[1]);
2101                lane.usize(span);
2102                for offset in 0..=span {
2103                    let uv = samples.polygon[(first + offset) % count];
2104                    lane.f64(uv.x);
2105                    lane.f64(uv.y);
2106                }
2107                lane.finish()
2108            });
2109            if let Some(served) = key.and_then(|key| SPHERE_REDUCTIONS.with(|memo| memo.borrow().get(&key).cloned())) {
2110                let Some((kept, kept_deviation)) = served else {
2111                    return Ok(None);
2112                };
2113                deviation = deviation.max(kept_deviation);
2114                let start = points.len();
2115                points.extend(kept.iter().copied());
2116                spans.push((start, points.len()));
2117                continue;
2118            }
2119            let reduced = reduce_sphere_coedge(face, atlas, &samples.polygon, first, span)?;
2120            if let Some(key) = key {
2121                SPHERE_REDUCTIONS.with(|memo| {
2122                    let mut memo = memo.borrow_mut();
2123                    if memo.len() >= SPHERE_REDUCTION_ENTRIES {
2124                        memo.clear();
2125                    }
2126                    memo.insert(key, reduced.clone());
2127                });
2128            }
2129            let Some((kept, kept_deviation)) = reduced else {
2130                return Ok(None);
2131            };
2132            deviation = deviation.max(kept_deviation);
2133            let start = points.len();
2134            points.extend(kept.iter().copied());
2135            spans.push((start, points.len()));
2136        }
2137    }
2138    if 2 * points.len() > total {
2139        return Ok(None);
2140    }
2141    crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2142    let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2143    for (first, last) in spans {
2144        for index in first..last.saturating_sub(1) {
2145            boundary.push((points[index], points[index + 1]));
2146        }
2147    }
2148    let region = crate::sphere_chart::SphericalRegion::from_segments(atlas.centre, &boundary, outward_face_normal);
2149    let rounding = 4e-9 / atlas.radius.max(f64::MIN_POSITIVE);
2150    Ok(Some((region, 2.0 * deviation + rounding)))
2151}
2152
2153/// One coedge's reduced boundary for [`build_sphere_region_reduced`]: its
2154/// samples `polygon[first..=first + span]` (cyclically) on the ball, kept at the
2155/// largest stride whose dropped samples lie within a tenth of the median chord
2156/// angle of the kept arcs, and that largest deviation; None when a sample is at
2157/// the centre. A function of the carrier and those samples alone.
2158fn reduce_sphere_coedge(
2159    face: &FaceRecord,
2160    atlas: &crate::sphere_chart::SphereAtlas,
2161    polygon: &[Vec2],
2162    first: usize,
2163    span: usize,
2164) -> Result<Option<(std::rc::Rc<Vec<Vec3>>, f64)>, String> {
2165    use crate::sphere_chart::{arc_distance, arc_normal};
2166    let count = polygon.len();
2167    let mut along: Vec<Vec3> = Vec::with_capacity(span + 1);
2168    for offset in 0..=span {
2169        let uv = polygon[(first + offset) % count];
2170        along.push(face.surface.evaluate(uv.x, uv.y)?);
2171    }
2172    let Ok(units) = along.iter().map(|p| p.sub(atlas.centre).normalized()).collect::<Result<Vec<_>, _>>() else {
2173        return Ok(None);
2174    };
2175    let last = along.len() - 1;
2176    let mut chords: Vec<f64> = units.windows(2).map(|pair| pair[0].sub(pair[1]).length()).collect();
2177    chords.sort_by(f64::total_cmp);
2178    let target = 0.1 * chords[chords.len() / 2];
2179    let mut kept: Vec<usize> = (0..=last).collect();
2180    let mut kept_deviation = 0.0f64;
2181    for stride in [32usize, 16, 8, 4, 2] {
2182        if last < 2 * stride {
2183            continue;
2184        }
2185        let indices: Vec<usize> = (0..=last).filter(|&i| i.min(last - i) % stride == 0).collect();
2186        let mut worst = 0.0f64;
2187        for pair in indices.windows(2) {
2188            let (a, b) = (units[pair[0]], units[pair[1]]);
2189            let normal = arc_normal(a, b);
2190            for j in pair[0] + 1..pair[1] {
2191                worst = worst.max(arc_distance(a, b, normal, units[j]));
2192            }
2193        }
2194        if worst <= target {
2195            kept = indices;
2196            kept_deviation = worst;
2197            break;
2198        }
2199    }
2200    Ok(Some((std::rc::Rc::new(kept.iter().map(|&i| along[i]).collect()), kept_deviation)))
2201}
2202
2203/// `BREP_SPHERE_REDUCTION_MEMO` (default on, `=0` reduces every coedge afresh):
2204/// [`build_sphere_region_reduced`] serves a coedge's reduction from
2205/// [`SPHERE_REDUCTIONS`]. brep-bench boolean/golf-ball: every cut changes the
2206/// ball face, so its first query rebuilt the reduced region from all 540 000
2207/// trim samples of its 55 dimple rims, 54 of them the previous cut's (4.3 s of
2208/// the case's 40 s); now each cut reduces its one new rim.
2209fn sphere_reduction_memo_enabled() -> bool {
2210    let enabled = crate::switch!("BREP_SPHERE_REDUCTION_MEMO", true);
2211    enabled
2212}
2213
2214
2215/// Bound on [`SPHERE_REDUCTIONS`]; the memo is emptied when it is reached.
2216const SPHERE_REDUCTION_ENTRIES: usize = 4096;
2217
2218thread_local! {
2219    /// [`reduce_sphere_coedge`]'s result per coedge, keyed by the carrier's
2220    /// identity (`hash_surface`, which fixes the atlas) and the bits of the
2221    /// coedge's samples, everything the reduction reads.
2222    pub static SPHERE_REDUCTIONS: std::cell::RefCell<std::collections::HashMap<[u64; 2], Option<(std::rc::Rc<Vec<Vec3>>, f64)>>> =
2223        std::cell::RefCell::new(std::collections::HashMap::new());
2224}
2225
2226/// The spherical region [`sphere_chart_point_in_face`] reads `face` against,
2227/// built ONCE per prepared face.
2228///
2229/// A region depends on the face's sphere, its orientation and its trim samples
2230/// — never on the query point — but the trim query is called once PER POINT
2231/// from the innermost loops of the imprint, the fragment builder and the
2232/// classifier's ray casts, and building one costs a surface evaluation per
2233/// boundary sample, a 27-cell canonicalization pass, two hash maps and a seed
2234/// search that can run two dozen crossing counts. Rebuilding that per query is
2235/// the whole cost of this lane; the query itself is one crossing count.
2236///
2237/// It lives on the [`PreparedFace`], whose cache key already holds everything
2238/// the region is built from. It used to have a four-entry cache of its own, and
2239/// a ray cast visits every face its segment's box touches in the same order
2240/// every time: a ball cut into seven faces by a helical tube (the 2026-09-26
2241/// coil fillet report) cycled that cache and missed on every query, 20-35 ms a
2242/// trim test, and the fillet's interference check ran 147 s instead of 30.
2243fn build_sphere_region(
2244    face: &FaceRecord,
2245    atlas: &crate::sphere_chart::SphereAtlas,
2246    sampled: &[LoopSamples],
2247) -> Result<crate::sphere_chart::SphericalRegion, String> {
2248    // An edge used TWICE by one face is a slit — the parametric seam of a ball
2249    // the trim never cut. It bounds no material, so it is left out of the region
2250    // rather than cancelled numerically afterwards.
2251    let mut uses: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
2252    for slot in coedge_slots(face) {
2253        *uses.entry(slot as u64).or_insert(0) += 1;
2254    }
2255    // Boundary SEGMENTS, not one polyline per loop.
2256    //
2257    // A ball drilled through carries BOTH rims in a single loop, joined by the
2258    // seam traversed once each way — a keyhole. Concatenating that loop's
2259    // surviving coedges and closing the ring would bridge rim to rim with two
2260    // chords that are not reverses of each other, and the winding of that figure
2261    // is not the winding of the two rims: on a through-drilled ball it comes out
2262    // exactly inverted. Handing the classifier the segments themselves lets it
2263    // cancel the seam and recover the two real rims.
2264    //
2265    // The samples are the CALLER's, taken once for its own parity count and its
2266    // own nearest-segment scan. Sampling the pcurves again here doubled the cost
2267    // of every query on a spherical face, and the caller only reaches this lane
2268    // when it would otherwise answer by parity — so that second pass was paid on
2269    // nearly every query and used on almost none of them.
2270    //
2271    // They are sampled in each coedge's own traversal direction, which is the
2272    // direction its pcurve is parameterized in: `forward` selects which end of
2273    // the EDGE's samples a traversal starts from, it does not reverse the
2274    // pcurve. A loop walked backwards puts the material on the wrong side of
2275    // every boundary.
2276    // The material-left convention is stated against the FACE normal, which the
2277    // generic path encodes as `(cross > 0) == same_sense` in uv: material is left
2278    // of the boundary seen from `same_sense ? Su x Sv : -(Su x Sv)`.
2279    let outward_face_normal =
2280        face.same_sense == atlas.parameterization_is_outward(&face.surface)?;
2281    let evaluate_started = containment_profile_started();
2282    let mut points: Vec<Vec3> = Vec::new();
2283    let mut spans: Vec<(usize, usize)> = Vec::new();
2284    for samples in sampled {
2285        let count = samples.polygon.len();
2286        if count < 2 {
2287            continue;
2288        }
2289        for &(edge_id, first, span) in &samples.coedges {
2290            if span == 0 || uses.get(&edge_id).copied().unwrap_or(0) >= 2 {
2291                continue;
2292            }
2293            // `span + 1` points: the coedge's own samples plus the first
2294            // sample of the next coedge, which is this one's END point. The
2295            // loop is closed, so the last coedge wraps back to `polygon[0]`.
2296            let start = points.len();
2297            for offset in 0..=span {
2298                let uv = samples.polygon[(first + offset) % count];
2299                points.push(face.surface.evaluate(uv.x, uv.y)?);
2300            }
2301            spans.push((start, points.len()));
2302        }
2303    }
2304    // One canonicalization over ALL the face's points: a vertex named by
2305    // two coedges is evaluated twice and the two answers agree only to
2306    // rounding, which the exact-reverse cancellation and the loop walk
2307    // both need collapsed.
2308    let evaluate_ms = containment_elapsed_ms(evaluate_started);
2309    let canonical_started = containment_profile_started();
2310    crate::sphere_chart::canonicalize_points(&mut points, 1e-9);
2311    let canonical_ms = containment_elapsed_ms(canonical_started);
2312    let segments_started = containment_profile_started();
2313    let mut boundary: Vec<(Vec3, Vec3)> = Vec::new();
2314    for (first, last) in spans {
2315        for index in first..last.saturating_sub(1) {
2316            boundary.push((points[index], points[index + 1]));
2317        }
2318    }
2319    let region = crate::sphere_chart::SphericalRegion::from_segments(
2320        atlas.centre,
2321        &boundary,
2322        outward_face_normal,
2323    );
2324    let segments_ms = containment_elapsed_ms(segments_started);
2325    containment_profile(|p| {
2326        p.region_builds += 1;
2327        p.region_evaluate_ms += evaluate_ms;
2328        p.region_canonical_ms += canonical_ms;
2329        p.region_segments_ms += segments_ms;
2330    });
2331    Ok(region)
2332}
2333
2334
2335/// The sphere the sphere-chart lane reads a face on: an analytic sphere, with
2336/// the lane's switches on ([`sphere_chart_trim_enabled`]).
2337pub fn sphere_chart_atlas(face: &FaceRecord) -> Option<crate::sphere_chart::SphereAtlas> {
2338    if !sphere_chart_trim_enabled() {
2339        return None;
2340    }
2341    crate::sphere_chart::SphereAtlas::of_surface(&face.surface)
2342}
2343
2344/// Whether `BREP_DEBUG_CONTAINMENT` is set, read once.  `parameter_point_in_face`
2345/// runs per ray-face intersection inside every boolean, so the cost when the
2346/// trace is off must be one `OnceLock` read, not an environment lookup per exit.
2347fn containment_trace_enabled() -> bool {
2348    debug_flag!("BREP_DEBUG_CONTAINMENT")
2349}
2350
2351/// Name the lane that answered, under `BREP_DEBUG_CONTAINMENT`.  This function
2352/// has seven exits and which one fired is the first thing any investigation of a
2353/// wrong containment verdict needs; reconstructing it from the outside means
2354/// re-deriving each lane's gate by hand.
2355fn trace_lane(face: &FaceRecord, point: Vec2, lane: &str, class: PolygonClass) {
2356    if containment_trace_enabled() {
2357        eprintln!(
2358            "containment face={} uv=({:.8},{:.8}) lane={lane} -> {class:?}",
2359            face.id, point.x, point.y
2360        );
2361    }
2362}
2363
2364
2365/// A lane [`parameter_point_in_face`] answers in, with what it prepared.
2366enum Lane<'a> {
2367    SeamBand(&'a SeamBandPrep),
2368    SphereCap(&'a SphereCapPrep),
2369    Horizon(&'a HorizonPrep),
2370    RimStrip(&'a RimStripPrep),
2371    Generic,
2372}
2373
2374/// The first lane at dispatch position `from` or later that is prepared to
2375/// answer `face`, and its position: 0 the seam band, 1 the sphere cap, 2 the
2376/// wrapped horizon, 3 the covering rim strip, 4 the generic scan. Each lane is
2377/// prepared (and its preparation's error surfaces) only when the walk reaches
2378/// it. [`parameter_point_in_face`] walks on from the next position when a lane
2379/// declines a query; [`containment_lane`] reports where the walk starts, so the
2380/// two cannot disagree about which lane a face is in.
2381fn lane_from<'a>(
2382    face: &FaceRecord,
2383    prepared: &'a PreparedFace,
2384    from: usize,
2385) -> Result<(usize, Lane<'a>), String> {
2386    if from == 0 {
2387        let band = timed_lane(&prepared.seam_band, || prepare_seam_band(face), |p, ms| {
2388            p.seam_band_preps += 1;
2389            p.seam_band_ms += ms;
2390        })?;
2391        if !matches!(band, SeamBandPrep::NotApplicable | SeamBandPrep::Declined) {
2392            return Ok((0, Lane::SeamBand(band)));
2393        }
2394    }
2395    if from <= 1 {
2396        if let Some(cap) = timed_lane(&prepared.sphere_cap, || prepare_winding_sphere_cap(face, prepared), |p, ms| {
2397            p.sphere_cap_preps += 1;
2398            p.sphere_cap_ms += ms;
2399        })? {
2400            return Ok((1, Lane::SphereCap(cap)));
2401        }
2402    }
2403    if from <= 2 {
2404        if let Some(horizon) = timed_lane(&prepared.horizon, || prepare_wrapped_horizon(face, prepared), |p, ms| {
2405            p.horizon_preps += 1;
2406            p.horizon_ms += ms;
2407        })? {
2408            return Ok((2, Lane::Horizon(horizon)));
2409        }
2410    }
2411    if from <= 3 {
2412        if let Some(strip) = timed_lane(&prepared.rim_strip, || prepare_covering_rim_strip(face), |p, ms| {
2413            p.rim_strip_preps += 1;
2414            p.rim_strip_ms += ms;
2415        })? {
2416            return Ok((3, Lane::RimStrip(strip)));
2417        }
2418    }
2419    Ok((4, Lane::Generic))
2420}
2421
2422/// Which lane of [`parameter_point_in_face`] a face's questions go to, read off
2423/// the face alone — the kernel's own lane selection, through the same prepared
2424/// data the query uses, for a caller that answers some containment questions
2425/// ahead of the kernel and must know which rule the kernel applies.
2426///
2427/// The lanes are tried in this order, and a face is in the first whose gates it
2428/// passes (each comparand is in the carrier's parameters unless stated):
2429///
2430/// 1. [`SeamBand`](ContainmentLane::SeamBand): `closed_directions() == (true, true)`, and
2431///    the seam-band preparation reads the face — every loop a collapsed
2432///    puncture (its trace within `1e-3` of the domain span in u and in v), one
2433///    seam-crossing loop unwrapped (unless [`SEAM_BAND_MERGED_SWITCH`]), two
2434///    loops the seam-band analysis reassembles, or two clean full-wrap rims (a
2435///    periodic extent of at least `0.6` period and a cross extent of at most
2436///    `0.05` of the cross span each).
2437/// 2. [`SphereCap`](ContainmentLane::SphereCap): an analytic sphere closed in exactly u
2438///    with two loops, each winding one period to within `0.05` period and the
2439///    two opposite, one flat (a v extent within `1e-6` of the v span) at a pole
2440///    (within `1e-6` of the v span of a v end).
2441/// 3. [`WrappedHorizon`](ContainmentLane::WrappedHorizon): closed in exactly u, at least
2442///    one loop, neither [`HORIZON_CONTAINMENT_SWITCH`] nor (for one or two
2443///    loops) [`HORIZON_SINGLE_LOOP_SWITCH`], some loop of three or more samples
2444///    stepping over the seam (a sample-to-sample u step more than a quarter
2445///    period from its period-folded value), and no loop winding the period (its
2446///    unwrapped first and last samples more than a quarter period apart).
2447/// 4. [`CoveringRimStrip`](ContainmentLane::CoveringRimStrip): closed in exactly u, two
2448///    loops, not [`COVERING_RIM_STRIP_SWITCH`], a sample beyond the u domain by
2449///    more than `1e-3` period, each loop travelling one period to within `2e-2`
2450///    period and closing in v to within `1e-3` of the v span, opposite
2451///    directions, v hulls apart by more than `1e-6` of the v span, and the lower
2452///    rim travelling +u exactly when the face is `same_sense`.
2453/// 5. [`Generic`](ContainmentLane::Generic): everything else.
2454///
2455/// Sampling is [`trim_sample_count`] chords per pcurve at [`trim_station`]
2456/// (the seam band: 24). `Err` is the error the face's first query would
2457/// return.
2458///
2459/// It reads the prepared data of a face a query has prepared, and otherwise
2460/// prepares what the walk reaches on the side, leaving the thread's
2461/// prepared-face cache as it was: asked for every face of a part, it would
2462/// otherwise push out the faces the queries are using.
2463pub fn containment_lane(face: &FaceRecord) -> Result<ContainmentLane, String> {
2464    let prepared = cached_prepared_face(face).unwrap_or_else(|| std::rc::Rc::new(PreparedFace::new()));
2465    Ok(match lane_from(face, &prepared, 0)?.1 {
2466        Lane::SeamBand(_) => ContainmentLane::SeamBand,
2467        Lane::SphereCap(_) => ContainmentLane::SphereCap,
2468        Lane::Horizon(horizon) => ContainmentLane::WrappedHorizon {
2469            loops: horizon.loops.clone(),
2470            u_period: horizon.u_period,
2471            cross_frame: horizon_cross_frame(),
2472        },
2473        Lane::RimStrip(_) => ContainmentLane::CoveringRimStrip,
2474        Lane::Generic => ContainmentLane::Generic {
2475            sphere_chart: sphere_chart_atlas(face).is_some(),
2476        },
2477    })
2478}
2479
2480/// The lane [`containment_lane`] finds a face in.
2481#[derive(Clone, Debug)]
2482pub enum ContainmentLane {
2483    /// The doubly-periodic seam-band lane: answers every point of the face.
2484    SeamBand,
2485    /// The winding sphere-cap lane: answers every point within the query's
2486    /// tolerance of a chord of the rim or whose u meets one; any other point
2487    /// goes on to the lanes after it.
2488    SphereCap,
2489    /// The wrapped-horizon lane: answers every point. Within the query's
2490    /// tolerance of a chord of `loops` at `u − u_period`, `u` or `u + u_period`
2491    /// it is `Boundary`; otherwise, with `cross_frame`, each loop's even-odd
2492    /// count (crossings of +u, half-open in v) at the three images summed mod
2493    /// 2, odd being `Inside`; without it ([`HORIZON_CROSS_FRAME_SWITCH`] = `"0"`
2494    /// when this was called), `Inside` when some image counts an odd total.
2495    WrappedHorizon {
2496        /// Each loop's samples, unwrapped sample to sample across the seam:
2497        /// the lane's own polygons, closed from last sample to first.
2498        loops: Vec<Vec<Vec2>>,
2499        u_period: f64,
2500        cross_frame: bool,
2501    },
2502    /// The covering-rim-strip lane: answers every point.
2503    CoveringRimStrip,
2504    /// The generic scan: `Boundary` within the tolerance of a chord; otherwise
2505    /// the side of the nearest pcurve where the nearest chord's foot lands
2506    /// inside it and the point is no farther from that chord than the chord is
2507    /// long; otherwise the even-odd count over every loop — for which, with
2508    /// `sphere_chart`, the sphere-chart lane substitutes where it can decide.
2509    Generic {
2510        /// An analytic sphere with the sphere-chart trim lane on
2511        /// ([`NO_SPHERE_CHART_TRIM_SWITCH`]), read when this was called.
2512        sphere_chart: bool,
2513    },
2514}
2515
2516pub fn parameter_point_in_face(
2517    face: &FaceRecord,
2518    point: Vec2,
2519    tolerance: f64,
2520) -> Result<PolygonClass, String> {
2521    point_in_face_scanned(face, point, tolerance, ChordScan::Auto)
2522}
2523
2524/// [`parameter_point_in_face`] with the generic scan and the wrapped-horizon
2525/// lane read through their chord index (`indexed`, on a face of any size) or
2526/// over every chord. The two give the same answer on every point; this exists
2527/// so a test can show it.
2528#[doc(hidden)]
2529pub fn parameter_point_in_face_scan(
2530    face: &FaceRecord,
2531    point: Vec2,
2532    tolerance: f64,
2533    indexed: bool,
2534) -> Result<PolygonClass, String> {
2535    let scan = if indexed {
2536        ChordScan::Indexed
2537    } else {
2538        ChordScan::Linear
2539    };
2540    point_in_face_scanned(face, point, tolerance, scan)
2541}
2542
2543fn point_in_face_scanned(
2544    face: &FaceRecord,
2545    point: Vec2,
2546    tolerance: f64,
2547    scan: ChordScan,
2548) -> Result<PolygonClass, String> {
2549    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
2550    let prepared = prepared_face(face);
2551    let mut from = 0;
2552    loop {
2553        let (position, lane) = lane_from(face, &prepared, from)?;
2554        let answer = match lane {
2555            Lane::SeamBand(band) => {
2556                seam_band_point_in_face(band, point, tolerance).map(|class| ("seam_band", class))
2557            }
2558            Lane::SphereCap(cap) => winding_sphere_cap_point_in_face(cap, point, tolerance)
2559                .map(|class| ("winding_sphere_cap", class)),
2560            Lane::Horizon(horizon) => wrapped_horizon_point_in_face(face, horizon, point, tolerance, scan)
2561                .map(|class| ("wrapped_horizon", class)),
2562            Lane::RimStrip(strip) => covering_rim_strip_point_in_face(strip, point, tolerance)
2563                .map(|class| ("covering_rim_strip", class)),
2564            Lane::Generic => break,
2565        };
2566        if let Some((name, class)) = answer {
2567            trace_lane(face, point, name, class);
2568            return Ok(class);
2569        }
2570        from = position + 1;
2571    }
2572    let generic = timed_lane(&prepared.generic, || prepare_generic(face, &prepared), |p, ms| {
2573        p.generic_preps += 1;
2574        p.generic_ms += ms;
2575    })?;
2576    let (crossings, boundary, nearest) = generic_scan(generic, point, tolerance, scan);
2577    if boundary {
2578        trace_lane(face, point, "polygon_boundary", PolygonClass::Boundary);
2579        return Ok(PolygonClass::Boundary);
2580    }
2581    let parity = if crossings % 2 == 1 {
2582        PolygonClass::Inside
2583    } else {
2584        PolygonClass::Outside
2585    };
2586    let chord = nearest.map(|(loop_index, index, distance)| {
2587        let polygon = &generic.loops[loop_index].polygon;
2588        let prep = generic.segments[loop_index][index];
2589        (
2590            polygon[index],
2591            polygon[(index + 1) % polygon.len()],
2592            &face.loops[loop_index].coedges[prep.coedge_index].pcurve,
2593            prep,
2594            distance,
2595        )
2596    });
2597    if containment_trace_enabled() {
2598        let (distance, length) = match chord.as_ref() {
2599            Some((start, end, _, _, distance)) => (*distance, end.sub(*start).length()),
2600            None => (f64::NAN, f64::NAN),
2601        };
2602        eprintln!(
2603            "containment face={} uv=({:.8},{:.8}) crossings={crossings} parity={parity:?} \
2604             nearest distance={distance:.3e} segment length={length:.3e}",
2605            face.id, point.x, point.y
2606        );
2607    }
2608    // The LAST of the special lanes, and the only one that engages here rather
2609    // than ahead of the scan: it substitutes for the parity count and for nothing
2610    // else. The four lanes above were each written for a shape the parity gets
2611    // wrong and are calibrated against real documents; pre-empting them would move
2612    // decisions this change has no business moving. Whenever the nearest-curve
2613    // refinement below can answer, it is more accurate than any global rule and is
2614    // what the imprint and the fragment builder are tuned against — so this asks
2615    // the sphere only on the complement of the refinement's own condition.
2616    let parity_decides = match chord.as_ref() {
2617        None => true,
2618        Some((start, end, _, _, distance)) => {
2619            let length = end.sub(*start).length();
2620            *distance > length || length <= 0.0
2621        }
2622    };
2623    if parity_decides {
2624        if let Some(class) = sphere_chart_point_in_face(face, point, &prepared, &generic.loops)? {
2625            trace_lane(face, point, "sphere_chart", class);
2626            return Ok(class);
2627        }
2628    }
2629    let Some((segment_start, segment_end, curve, prep, distance)) = chord else {
2630        trace_lane(face, point, "parity (no segment)", parity);
2631        return Ok(parity);
2632    };
2633    let segment_length = segment_end.sub(segment_start).length();
2634    if distance > segment_length || segment_length <= 0.0 {
2635        trace_lane(face, point, "parity (far from every segment)", parity);
2636        return Ok(parity);
2637    }
2638    let chord_parameter = prep.parameter_start
2639        + (prep.parameter_end - prep.parameter_start)
2640            * (point.sub(segment_start).dot(segment_end.sub(segment_start))
2641                / (segment_length * segment_length))
2642                .clamp(0.0, 1.0);
2643    let [domain_start, domain_end] = curve.domain()?;
2644    let small = crate::curve::small_curve_derivatives_enabled();
2645    let read = |parameter: f64, count: usize| -> Result<[Vec3; 3], String> {
2646        if small {
2647            return curve.derivatives_small(parameter, count);
2648        }
2649        let heap = curve.derivatives(parameter, count)?;
2650        let mut grid = [Vec3::default(); 3];
2651        grid[..heap.len()].copy_from_slice(&heap);
2652        Ok(grid)
2653    };
2654    use crate::projection::{curve_foot_newton, CurveFootPolicy, FootDomain, FootMode};
2655    let (parameter, _) = curve_foot_newton(curve, Vec3::new(point.x, point.y, 0.0),
2656        chord_parameter, [domain_start, domain_end], CurveFootPolicy {
2657            domain: FootDomain::Clamp,
2658            iterations: 12,
2659            slope_guard: 1e-30,
2660            step_limit: f64::INFINITY,
2661            parameter_tolerance: 1e-14 * (domain_end - domain_start + 1.0),
2662            mode: FootMode::Planar,
2663        })?;
2664    let margin = 1e-9 * (domain_end - domain_start);
2665    if parameter > domain_start + margin && parameter < domain_end - margin {
2666        let derivatives = read(parameter, 1)?;
2667        let on_curve = Vec2 {
2668            x: derivatives[0].x,
2669            y: derivatives[0].y,
2670        };
2671        let tangent = Vec2 {
2672            x: derivatives[1].x,
2673            y: derivatives[1].y,
2674        };
2675        let offset = point.sub(on_curve);
2676        if offset.length() <= tolerance {
2677            trace_lane(face, point, "nearest curve (on it)", PolygonClass::Boundary);
2678            return Ok(PolygonClass::Boundary);
2679        }
2680        let cross = tangent.x * offset.y - tangent.y * offset.x;
2681        if cross.abs() > 1e-30 {
2682            let class = if (cross > 0.0) == face.same_sense {
2683                PolygonClass::Inside
2684            } else {
2685                PolygonClass::Outside
2686            };
2687            trace_lane(face, point, "nearest curve (side)", class);
2688            return Ok(class);
2689        }
2690    }
2691    trace_lane(face, point, "parity (nearest curve declined)", parity);
2692    Ok(parity)
2693}
2694
2695