Skip to main content

brep_geometry/intersect/
arrangement.rs

1use crate::spatial::{Aabb, Bvh};
2use crate::Vec3;
3use rustc_hash::FxHashMap;
4use serde::{Deserialize, Serialize};
5
6const PARALLEL_THRESHOLD: f64 = 1e-12;
7
8#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
9pub struct Vec2 {
10    pub x: f64,
11    pub y: f64,
12}
13
14impl Vec2 {
15    /// Distance to a segment. `guard` is the caller's squared-length threshold.
16    #[inline]
17    pub fn distance_to_segment(self, start: Self, end: Self, guard: f64) -> f64 {
18        let segment = end.sub(start);
19        let length_squared = segment.dot(segment);
20        if length_squared <= guard {
21            return self.sub(start).length();
22        }
23        let parameter = (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0);
24        self.sub(start.add(segment.scale(parameter))).length()
25    }
26
27    /// Squared distance, retaining the seed sweep's projection on zero-length segments.
28    #[inline]
29    pub fn distance_to_segment_squared(self, start: Self, end: Self) -> f64 {
30        let segment = end.sub(start);
31        let length_squared = segment.dot(segment);
32        let parameter = if length_squared > 0.0 {
33            (self.sub(start).dot(segment) / length_squared).clamp(0.0, 1.0)
34        } else {
35            0.0
36        };
37        let residual = self.sub(start.add(segment.scale(parameter)));
38        residual.dot(residual)
39    }
40
41    pub fn sub(self, other: Self) -> Self {
42        Self {
43            x: self.x - other.x,
44            y: self.y - other.y,
45        }
46    }
47    pub fn add(self, other: Self) -> Self {
48        Self {
49            x: self.x + other.x,
50            y: self.y + other.y,
51        }
52    }
53    pub fn scale(self, factor: f64) -> Self {
54        Self {
55            x: self.x * factor,
56            y: self.y * factor,
57        }
58    }
59    fn distance(self, other: Self) -> f64 {
60        self.sub(other).length()
61    }
62    pub fn length(self) -> f64 {
63        (self.x * self.x + self.y * self.y).sqrt()
64    }
65    fn cross(self, other: Self) -> f64 {
66        self.x * other.y - self.y * other.x
67    }
68    pub fn dot(self, other: Self) -> f64 {
69        self.x * other.x + self.y * other.y
70    }
71}
72
73#[derive(Clone, Debug, Deserialize, Serialize)]
74pub struct Segment2 {
75    pub a: Vec2,
76    pub b: Vec2,
77    #[serde(default)]
78    pub tag: serde_json::Value,
79}
80
81#[derive(Clone, Debug, Serialize)]
82pub struct ArrangementPiece {
83    pub a: Vec2,
84    pub b: Vec2,
85    pub parent: Segment2,
86}
87
88#[derive(Clone, Debug, Serialize)]
89pub struct CycleUse {
90    pub piece: ArrangementPiece,
91    pub forward: bool,
92}
93
94#[derive(Clone, Debug, Serialize)]
95pub struct ArrangementRegion {
96    pub outer: Vec<CycleUse>,
97    pub holes: Vec<Vec<CycleUse>>,
98    pub area: f64,
99    /// The outer cycle's area alone, the key regions are returned by
100    /// (ascending); `area` nets the holes out.
101    pub outer_area: f64,
102}
103
104#[derive(Clone)]
105struct Node {
106    point: Vec2,
107    outgoing: Vec<usize>,
108}
109
110/// Append-only node lookup. A match always selects the lowest existing node
111/// index, exactly like the original linear `.position` scan, not the nearest
112/// point or the first occupied neighboring cell.
113struct NodeLookup {
114    tolerance: f64,
115    width: f64,
116    cells: Option<FxHashMap<[i64; 2], Vec<usize>>>,
117}
118
119impl NodeLookup {
120    fn new(tolerance: f64, indexed: bool) -> Self {
121        let width = tolerance * 2.0;
122        Self {
123            tolerance,
124            width,
125            // Squared distances can underflow and accept farther points at
126            // tiny tolerances. Preserve that legacy behavior with a scan.
127            cells: (indexed && tolerance >= 1e-150 && width.is_finite()).then(FxHashMap::default),
128        }
129    }
130
131    fn key(&self, point: Vec2) -> Option<[i64; 2]> {
132        let q = [point.x / self.width, point.y / self.width];
133        // Two-radius cells leave half a cell of rounding headroom. Bound the
134        // quotient so division rounding cannot consume it, or integer neighbors
135        // overflow. This also rejects non-finite coordinates.
136        q.iter()
137            .all(|v| v.is_finite() && v.abs() <= (1u64 << 48) as f64)
138            .then(|| q.map(|v| v.floor() as i64))
139    }
140
141    fn find_or_insert(&mut self, point: Vec2, nodes: &mut Vec<Node>) -> usize {
142        let key = self.cells.as_ref().and_then(|_| self.key(point));
143        if key.is_none() {
144            // Once a point cannot be indexed, retain the scan for the rest of
145            // the stream, including comparisons against this newly added node.
146            self.cells = None;
147        }
148        let found = if let (Some(cells), Some([x, y])) = (&self.cells, key) {
149            let mut first = None;
150            for dx in -1..=1 {
151                for dy in -1..=1 {
152                    if let Some(indices) = cells.get(&[x + dx, y + dy]) {
153                        // Each bucket is in insertion order. Later nodes in
154                        // this bucket cannot beat an already earlier match.
155                        for &index in indices {
156                            if first.is_some_and(|first| index >= first) {
157                                break;
158                            }
159                            if nodes[index].point.distance(point) <= self.tolerance {
160                                first = Some(index);
161                                break;
162                            }
163                        }
164                    }
165                }
166            }
167            first
168        } else {
169            nodes
170                .iter()
171                .position(|node| node.point.distance(point) <= self.tolerance)
172        };
173        if let Some(index) = found {
174            return index;
175        }
176        let index = nodes.len();
177        nodes.push(Node {
178            point,
179            outgoing: Vec::new(),
180        });
181        if let (Some(cells), Some(key)) = (&mut self.cells, key) {
182            cells.entry(key).or_default().push(index);
183        }
184        index
185    }
186}
187
188fn tolerance_parameter(segment: &Segment2, tolerance: f64) -> f64 {
189    let length = segment.a.distance(segment.b);
190    if length <= tolerance {
191        0.5
192    } else {
193        tolerance / length
194    }
195}
196
197fn interpolate(a: Vec2, b: Vec2, parameter: f64) -> Vec2 {
198    Vec2 {
199        x: a.x + (b.x - a.x) * parameter,
200        y: a.y + (b.y - a.y) * parameter,
201    }
202}
203
204pub fn segment_intersection(
205    a1: Vec2,
206    b1: Vec2,
207    a2: Vec2,
208    b2: Vec2,
209    tolerance: f64,
210) -> Option<[f64; 2]> {
211    let d1 = b1.sub(a1);
212    let d2 = b2.sub(a2);
213    let denominator = d1.cross(d2);
214    let length1 = d1.length();
215    let length2 = d2.length();
216    if denominator.abs() <= PARALLEL_THRESHOLD * length1 * length2 {
217        return None;
218    }
219    let offset = a2.sub(a1);
220    let t1 = offset.cross(d2) / denominator;
221    let t2 = offset.cross(d1) / denominator;
222    let epsilon1 = tolerance / length1.max(tolerance);
223    let epsilon2 = tolerance / length2.max(tolerance);
224    if t1 < -epsilon1 || t1 > 1.0 + epsilon1 || t2 < -epsilon2 || t2 > 1.0 + epsilon2 {
225        None
226    } else {
227        Some([t1.clamp(0.0, 1.0), t2.clamp(0.0, 1.0)])
228    }
229}
230
231/// Where the ends of `end` touch the interior of `bar`, for a pair the line
232/// crossing rejected. `segment_intersection` measures its tolerance ALONG each
233/// segment, so a stem meeting a bar at a shallow angle overruns it: a gap `g`
234/// is `g / sin(angle)` along the stem. An end within tolerance of the bar then
235/// gets no node on it, keeps degree 1, and pruning removes the whole stem
236/// (a reported box and pin model: a 9.8e-8 gap at sin 0.035 against a 1.4e-6 tolerance).
237/// Parallel pairs stay excluded, as they are from the crossing test, and the
238/// caller keeps only an end no other segment shares: a chain's interior point
239/// riding within tolerance of a nearly collinear curve is not a T, and noding
240/// it would pinch the two together.
241/// `BREP_ARRANGE_END_ON_SEGMENT=0` turns this off.
242fn end_on_segment_parameters(end: &Segment2, bar: &Segment2, tolerance: f64) -> Vec<(Vec2, f64)> {
243    let (stem, span) = (end.b.sub(end.a), bar.b.sub(bar.a));
244    let squared = span.dot(span);
245    if squared <= 0.0 || stem.cross(span).abs() <= PARALLEL_THRESHOLD * stem.length() * span.length() {
246        return Vec::new();
247    }
248    let margin = tolerance_parameter(bar, tolerance);
249    [end.a, end.b]
250        .into_iter()
251        .filter_map(|point| {
252            let parameter = point.sub(bar.a).dot(span) / squared;
253            (parameter > margin
254                && parameter < 1.0 - margin
255                && point_segment_distance(point, bar.a, bar.b) <= tolerance)
256                .then_some((point, parameter))
257        })
258        .collect()
259}
260
261pub use crate::polygon::PolygonClass;
262
263fn point_segment_distance(point: Vec2, a: Vec2, b: Vec2) -> f64 {
264    point.distance_to_segment(a, b, 1e-300)
265}
266
267/// The hole assignment's box rejection (2026-11-02): a point
268/// beyond a region polygon's vertex box by more than the classifier's
269/// tolerance plus a rounding pad is classified Outside without the O(n) test,
270/// and the full classifier would say the same. Its boundary band cannot fire
271/// (every computed segment distance exceeds the tolerance: the clamped foot
272/// lies in the box up to rounding the pad covers). Its form-K parity reads
273/// Outside: above or below the box no edge straddles the ray; to the right no
274/// crossing lies right of the point; to the left every straddling edge crosses
275/// right of it, and a closed loop has an even number of them. The hole loop
276/// was 60-70% of the arrangement's time on the package models (one negative
277/// cycle tested node by node against every positive region's polygon).
278/// Returns `[min_x, min_y, max_x, max_y, reach]`; `reach` is NaN (never
279/// reject) for an empty or non-finite polygon.
280fn polygon_reject_box(polygon: &[Vec2], tolerance: f64) -> [f64; 5] {
281    let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
282    let mut magnitude = 1.0f64;
283    for point in polygon {
284        bounds[0] = bounds[0].min(point.x);
285        bounds[1] = bounds[1].min(point.y);
286        bounds[2] = bounds[2].max(point.x);
287        bounds[3] = bounds[3].max(point.y);
288        magnitude = magnitude.max(point.x.abs()).max(point.y.abs());
289    }
290    let finite = !polygon.is_empty() && bounds.iter().all(|value| value.is_finite()) && tolerance.is_finite() && tolerance >= 0.0;
291    let reach = if finite { tolerance * (1.0 + 1e-9) + 64.0 * f64::EPSILON * magnitude } else { f64::NAN };
292    [bounds[0], bounds[1], bounds[2], bounds[3], reach]
293}
294
295/// The classifier's boundary band, indexed (2026-11-02): a
296/// uniform grid over the polygon's vertex box whose cells list every edge whose
297/// box, widened by the tolerance plus a rounding pad, overlaps them. An edge
298/// whose computed distance to a point is within the tolerance has that point
299/// inside its widened box (the clamped foot lies in the edge's box up to
300/// rounding the pad covers), so the point's cell lists it; the band is an
301/// existence test, so testing the listed edges with the classifier's own
302/// distance gives the classifier's own answer. Parity is the original full
303/// scan. Why: a negative cycle that runs along a region's own boundary
304/// classifies Boundary at every node and goes on to the next, so the hole loop
305/// paid one full O(n) band scan per node.
306struct BoundaryBand {
307    origin: [f64; 2],
308    cell: [f64; 2],
309    side: usize,
310    starts: Vec<u32>,
311    items: Vec<u32>,
312    usable: bool,
313}
314
315impl BoundaryBand {
316    fn new(polygon: &[Vec2], tolerance: f64) -> Self {
317        let reject = polygon_reject_box(polygon, tolerance);
318        let reach = reject[4];
319        let count = polygon.len();
320        let usable = reach.is_finite() && count >= 16 && count <= (1 << 24);
321        let side = if usable { ((count as f64).sqrt() as usize).clamp(4, 512) } else { 0 };
322        let origin = [reject[0] - reach, reject[1] - reach];
323        let extent = [(reject[2] + reach) - origin[0], (reject[3] + reach) - origin[1]];
324        let cell = [(extent[0] / side.max(1) as f64).max(f64::MIN_POSITIVE), (extent[1] / side.max(1) as f64).max(f64::MIN_POSITIVE)];
325        let mut band = Self { origin, cell, side, starts: Vec::new(), items: Vec::new(), usable };
326        if !band.usable {
327            return band;
328        }
329        let mut counts = vec![0u32; side * side + 1];
330        let ranges: Vec<[usize; 4]> = (0..count)
331            .map(|index| {
332                let (a, b) = (polygon[index], polygon[(index + 1) % count]);
333                let pad = reach + 64.0 * f64::EPSILON * a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs());
334                [band.column(a.x.min(b.x) - pad), band.column(a.x.max(b.x) + pad), band.row(a.y.min(b.y) - pad), band.row(a.y.max(b.y) + pad)]
335            })
336            .collect();
337        for range in &ranges {
338            for y in range[2]..=range[3] {
339                for x in range[0]..=range[1] {
340                    counts[y * side + x + 1] += 1;
341                }
342            }
343        }
344        for index in 1..counts.len() {
345            counts[index] += counts[index - 1];
346        }
347        // Long edges cover many cells; past a budget the original scan is cheaper.
348        if counts[side * side] as usize > 64 * count + 4096 {
349            band.usable = false;
350            return band;
351        }
352        let mut cursor = counts.clone();
353        band.items = vec![0u32; counts[side * side] as usize];
354        for (edge, range) in ranges.iter().enumerate() {
355            for y in range[2]..=range[3] {
356                for x in range[0]..=range[1] {
357                    let slot = &mut cursor[y * side + x];
358                    band.items[*slot as usize] = edge as u32;
359                    *slot += 1;
360                }
361            }
362        }
363        band.starts = counts;
364        band
365    }
366    fn column(&self, x: f64) -> usize {
367        (((x - self.origin[0]) / self.cell[0]).floor().max(0.0) as usize).min(self.side - 1)
368    }
369    fn row(&self, y: f64) -> usize {
370        (((y - self.origin[1]) / self.cell[1]).floor().max(0.0) as usize).min(self.side - 1)
371    }
372    fn classify(&self, point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
373        if !self.usable || !point.x.is_finite() || !point.y.is_finite() {
374            return point_in_polygon_class(point, polygon, tolerance);
375        }
376        let cell = self.row(point.y) * self.side + self.column(point.x);
377        let count = polygon.len();
378        for &edge in &self.items[self.starts[cell] as usize..self.starts[cell + 1] as usize] {
379            let edge = edge as usize;
380            if point.distance_to_segment(polygon[edge], polygon[(edge + 1) % count], 1e-300) <= tolerance {
381                return PolygonClass::Boundary;
382            }
383        }
384        if crate::polygon::parity_inside([point.x, point.y], count, |i| [polygon[i].x, polygon[i].y]) {
385            PolygonClass::Inside
386        } else {
387            PolygonClass::Outside
388        }
389    }
390}
391
392fn outside_reject_box(point: Vec2, reject: &[f64; 5]) -> bool {
393    let reach = reject[4] + 64.0 * f64::EPSILON * point.x.abs().max(point.y.abs());
394    // NaN `reach` (or a NaN point) makes every comparison false: never reject.
395    point.x < reject[0] - reach || point.y < reject[1] - reach || point.x > reject[2] + reach || point.y > reject[3] + reach
396}
397
398/// `BREP_ARRANGE_DIGON_ORDER` (default on; `=0` restores insertion order for
399/// equal angles): see DIGON ORDER in [`arrange_segments`].
400fn digon_order_enabled() -> bool {
401    switch!("BREP_ARRANGE_DIGON_ORDER", true)
402}
403
404fn hole_box_reject_enabled() -> bool {
405    switch!("BREP_ARRANGE_HOLE_BOX", true)
406}
407
408
409fn point_in_polygon_class(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
410    crate::polygon::classify(point, polygon, tolerance, 1e-300)
411}
412
413pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> &'static str {
414    match point_in_polygon_class(point, polygon, tolerance) {
415        PolygonClass::Inside => "in",
416        PolygonClass::Outside => "out",
417        PolygonClass::Boundary => "boundary",
418    }
419}
420
421// Arrangement decisions read endpoints and topology, never parent tags. Keep
422// the immutable source segment borrowed until a retained cycle needs an owned
423// output. The eager arm preserves the original allocation path for A/B.
424struct PieceInput<'a> {
425    a: Vec2,
426    b: Vec2,
427    parent: std::borrow::Cow<'a, Segment2>,
428}
429impl PieceInput<'_> {
430    fn materialize(&self, forward: bool) -> CycleUse {
431        CycleUse { piece: ArrangementPiece { a: self.a, b: self.b, parent: self.parent.as_ref().clone() }, forward }
432    }
433}
434
435#[derive(Clone)]
436enum CycleUses {
437    Eager(Vec<CycleUse>),
438    Deferred(Vec<usize>),
439}
440impl CycleUses {
441    fn push(&mut self, half: usize, pieces: &[PieceInput<'_>]) {
442        match self {
443            Self::Eager(uses) => uses.push(pieces[half >> 1].materialize(half % 2 == 0)),
444            Self::Deferred(halves) => halves.push(half),
445        }
446    }
447    fn into_uses(self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
448        match self {
449            Self::Eager(uses) => uses,
450            Self::Deferred(halves) => halves.into_iter().map(|h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
451        }
452    }
453    fn copy_uses(&self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
454        match self {
455            Self::Eager(uses) => uses.clone(),
456            Self::Deferred(halves) => halves.iter().map(|&h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
457        }
458    }
459}
460
461#[derive(Clone)]
462struct Cycle {
463    uses: CycleUses,
464    area: f64,
465    node_indices: Vec<usize>,
466}
467
468/// Visit a conservative subset of pairs in original input order. The narrow
469/// phase remains authoritative, including its endpoint tolerance and rounding.
470fn visit_segment_pairs(segments: &[Segment2], tolerance: f64, mut visit: impl FnMut(usize, usize)) {
471    let all_pairs = |visit: &mut dyn FnMut(usize, usize)| {
472        for first in 0..segments.len() {
473            for second in first + 1..segments.len() {
474                visit(first, second);
475            }
476        }
477    };
478    if segments.len() <= 32
479        || segments.len() > u32::MAX as usize
480        || !tolerance.is_finite()
481        || tolerance < 0.0
482        || tolerance > 1e100
483    {
484        all_pairs(&mut visit);
485        return;
486    }
487    let mut scale = 0.0f64;
488    let mut boxes = Vec::with_capacity(segments.len());
489    let mut extent = Aabb::empty();
490    for segment in segments {
491        let coordinates = [segment.a.x, segment.a.y, segment.b.x, segment.b.y];
492        let length = segment.a.distance(segment.b);
493        // Keep the legacy scan for numeric extremes: underflow/overflow or NaN
494        // in the narrow phase need not behave like geometric intersection.
495        if coordinates
496            .iter()
497            .any(|v| !v.is_finite() || v.abs() > 1e100)
498            || !(1e-100..=1e100).contains(&length)
499        {
500            all_pairs(&mut visit);
501            return;
502        }
503        for coordinate in coordinates {
504            scale = scale.max(coordinate.abs());
505        }
506        let bounds = Aabb {
507            minimum: Vec3::new(
508                segment.a.x.min(segment.b.x),
509                segment.a.y.min(segment.b.y),
510                0.0,
511            ),
512            maximum: Vec3::new(
513                segment.a.x.max(segment.b.x),
514                segment.a.y.max(segment.b.y),
515                0.0,
516            ),
517        };
518        extent.include(bounds);
519        boxes.push(bounds);
520    }
521    // Each accepted parameter may extend its segment by up to tolerance.
522    // Cross-product roundoff is amplified by up to 1/PARALLEL_THRESHOLD when
523    // solving the parameters. Bound it using the global coordinate magnitude
524    // (including translation), with headroom for subtraction, products, length
525    // and division rounding. This deliberately admits extra pairs near parallel
526    // lines instead of treating exact endpoint boxes as a bound on an inexact
527    // solve. The numeric guards above keep these operations in the normal range.
528    let padding = 2.0 * tolerance + 128.0 * f64::EPSILON / PARALLEL_THRESHOLD * scale;
529    // A large translation or tolerance can swallow the entire arrangement.
530    // An index cannot reject anything then, so avoid its query/sort overhead.
531    if padding >= extent.diagonal() {
532        all_pairs(&mut visit);
533        return;
534    }
535    let direction_tiers = direction_index_on();
536    // Row 29: the direction tiers' small-padding query is answered by a
537    // one-axis sweep instead of the tree, which is then not built (`None`
538    // from the sweep keeps the tree).
539    let small_padding = 2.0 * tolerance + 128.0 * f64::EPSILON / DIRECTION_SINE * scale;
540    let swept = if direction_tiers && arrange_sweep_on() { swept_pairs(&boxes, small_padding) } else { None };
541    let tree = swept.is_none().then(|| Bvh::build(&boxes));
542    let mut candidates = Vec::new();
543    if direction_tiers {
544        // DIRECTION TIERS (lane O, 2026-10-28). The padding above is what a
545        // pair as near-parallel as the narrow phase admits (`sin θ` down to
546        // PARALLEL_THRESHOLD) can need, and on a face whose uv sit far from
547        // the origin it reaches across most of the arrangement: the filleted
548        // box's outward offset sends a 252-segment quarter-arc chain through
549        // here twice per attempt and the index visited nearly all 37 000
550        // pairs (0.7 ms a face). The same rounding model bounds a pair whose
551        // directions differ by `sin θ ≥ s` with the padding at `s` in place of
552        // the threshold. So every pair is visited under that small padding,
553        // and a pair whose directions lie within one bucket of each other
554        // (width `2s`, wrapping at π) — the only pairs that can be nearer
555        // parallel than `s` — under the full padding as before. Visit order
556        // and the narrow phase are unchanged; the visited set still contains
557        // every pair the full padding could accept.
558        let width = 2.0 * DIRECTION_SINE;
559        let bucket_count = ((std::f64::consts::PI / width).ceil() as usize).max(1);
560        let mut buckets: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
561        let bucket_of: Vec<usize> = segments
562            .iter()
563            .map(|segment| {
564                let angle = (segment.b.y - segment.a.y).atan2(segment.b.x - segment.a.x).rem_euclid(std::f64::consts::PI);
565                ((angle / width) as usize).min(bucket_count - 1)
566            })
567            .collect();
568        for (index, bucket) in bucket_of.iter().enumerate() {
569            buckets.entry(*bucket).or_default().push(index);
570        }
571        let near = |a: &Aabb, b: &Aabb| {
572            a.minimum.x - padding <= b.maximum.x
573                && b.minimum.x - padding <= a.maximum.x
574                && a.minimum.y - padding <= b.maximum.y
575                && b.minimum.y - padding <= a.maximum.y
576        };
577        for (first, &bounds) in boxes.iter().enumerate() {
578            candidates.clear();
579            match (&swept, &tree) {
580                (Some(lists), _) => candidates.extend_from_slice(&lists[first]),
581                (None, Some(tree)) => tree.overlapping(bounds, small_padding, &mut candidates),
582                (None, None) => unreachable!("the tree is built whenever the sweep is not"),
583            }
584            let bucket = bucket_of[first];
585            for neighbour in [(bucket + bucket_count - 1) % bucket_count, bucket, (bucket + 1) % bucket_count] {
586                if let Some(members) = buckets.get(&neighbour) {
587                    candidates.extend(members.iter().copied().filter(|&second| second > first && near(&bounds, &boxes[second])));
588                }
589                if bucket_count < 3 {
590                    break;
591                }
592            }
593            candidates.retain(|&second| second > first);
594            candidates.sort_unstable();
595            candidates.dedup();
596            for &second in &candidates {
597                visit(first, second);
598            }
599        }
600        return;
601    }
602    let Some(tree) = tree else { unreachable!("the sweep runs only under the direction tiers") };
603    for (first, &bounds) in boxes.iter().enumerate() {
604        candidates.clear();
605        tree.overlapping(bounds, padding, &mut candidates);
606        candidates.retain(|&second| second > first);
607        candidates.sort_unstable();
608        for &second in &candidates {
609            visit(first, second);
610        }
611    }
612}
613
614/// The direction sine above which [`visit_segment_pairs`] pads a pair with
615/// the small padding (see DIRECTION TIERS there).
616const DIRECTION_SINE: f64 = 1e-3;
617
618/// Lane O row 29 (2026-10-30, `BREP_ARRANGE_SWEEP`, default on since batch 12;
619/// `0`/`off` restores the tree): for each box `first`, every `second > first` whose box passes
620/// the tree's own leaf test `boxes[second].intersects(boxes[first], padding)`
621/// — the set [`Bvh::overlapping`] returns past `second > first`, since a node
622/// box contains its items' boxes — in ascending order. The candidates come
623/// from a sweep over the boxes sorted by their minimum on one axis, each
624/// scanning forward while the next minimum is within its maximum plus twice
625/// the padding: a pair the leaf test admits lies within the padding plus one
626/// rounding of either subtraction there, and the padding (at least
627/// 128 ε / DIRECTION_SINE of the largest coordinate) exceeds that rounding.
628///
629/// The axis is the one whose sweep windows (counted by binary search before
630/// any test runs) are fewer in total; when even those exceed 32 a box, the
631/// boxes overlap along both axes and `None` hands the query back to the tree,
632/// which prunes on both at once (a guard: of the D1, inward opposed and
633/// outward 3-adjacent shell cases probed, only D1 reaches the sweep, and
634/// never the fallback). D1's two 272-segment faces spent 0.38 ms a run
635/// building and querying the tree for 570 narrow-phase pairs that cost
636/// 0.04 ms.
637fn swept_pairs(boxes: &[Aabb], padding: f64) -> Option<Vec<Vec<usize>>> {
638    let reach = 2.0 * padding;
639    let low = |index: usize, axis: usize| if axis == 0 { boxes[index].minimum.x } else { boxes[index].minimum.y };
640    let high = |index: usize, axis: usize| if axis == 0 { boxes[index].maximum.x } else { boxes[index].maximum.y };
641    let mut best: Option<(usize, Vec<usize>, usize)> = None;
642    for axis in [0, 1] {
643        let mut order: Vec<usize> = (0..boxes.len()).collect();
644        order.sort_by(|&a, &b| low(a, axis).total_cmp(&low(b, axis)));
645        let lows: Vec<f64> = order.iter().map(|&index| low(index, axis)).collect();
646        let windows: usize = order
647            .iter()
648            .enumerate()
649            .map(|(position, &a)| {
650                let limit = high(a, axis) + reach;
651                lows.partition_point(|&value| value <= limit).saturating_sub(position + 1)
652            })
653            .sum();
654        if best.as_ref().is_none_or(|(least, _, _)| windows < *least) {
655            best = Some((windows, order, axis));
656        }
657    }
658    let (windows, order, axis) = best?;
659    if windows > 32 * boxes.len() {
660        return None;
661    }
662    let mut lists = vec![Vec::new(); boxes.len()];
663    for (position, &a) in order.iter().enumerate() {
664        let limit = high(a, axis) + reach;
665        for &b in &order[position + 1..] {
666            if low(b, axis) > limit {
667                break;
668            }
669            let (first, second) = if a < b { (a, b) } else { (b, a) };
670            if boxes[second].intersects(boxes[first], padding) {
671                lists[first].push(second);
672            }
673        }
674    }
675    for list in &mut lists {
676        list.sort_unstable();
677    }
678    Some(lists)
679}
680
681/// Row 29's switch ([`swept_pairs`]), read once.
682fn arrange_sweep_on() -> bool {
683    switch!("BREP_ARRANGE_SWEEP", true)
684}
685
686
687/// The direction tiers of [`visit_segment_pairs`], on unless
688/// `BREP_ARRANGE_DIRECTION_INDEX` is `0`/`off` (the A/B lever). Read once.
689fn direction_index_on() -> bool {
690    switch!("BREP_ARRANGE_DIRECTION_INDEX", true)
691}
692
693pub fn arrange_segments(
694    segments: &[Segment2],
695    tolerance: f64,
696) -> Result<Vec<ArrangementRegion>, String> {
697    arrange_segments_impl(segments, tolerance, true, true)
698}
699
700fn arrange_segments_impl(
701    segments: &[Segment2],
702    tolerance: f64,
703    indexed: bool,
704    indexed_nodes: bool,
705) -> Result<Vec<ArrangementRegion>, String> {
706    let defer_tags = switch!("BREP_ARRANGE_DEFER_TAGS", true);
707    let end_on_segment = switch!("BREP_ARRANGE_END_ON_SEGMENT", true);
708    let mut cuts = vec![Vec::<f64>::new(); segments.len()];
709    let mut intersect_pair = |first: usize, second: usize| {
710        let Some([first_parameter, second_parameter]) = segment_intersection(
711            segments[first].a,
712            segments[first].b,
713            segments[second].a,
714            segments[second].b,
715            tolerance,
716        ) else {
717            if end_on_segment {
718                for (end, bar) in [(first, second), (second, first)] {
719                    for (point, parameter) in end_on_segment_parameters(&segments[end], &segments[bar], tolerance) {
720                        let shared = segments.iter().enumerate().any(|(index, other)| {
721                            index != end && (other.a.distance(point) <= tolerance || other.b.distance(point) <= tolerance)
722                        });
723                        if !shared {
724                            cuts[bar].push(parameter);
725                        }
726                    }
727                }
728            }
729            return;
730        };
731        let first_tolerance = tolerance_parameter(&segments[first], tolerance);
732        let second_tolerance = tolerance_parameter(&segments[second], tolerance);
733        if first_parameter > first_tolerance && first_parameter < 1.0 - first_tolerance {
734            cuts[first].push(first_parameter);
735        }
736        if second_parameter > second_tolerance && second_parameter < 1.0 - second_tolerance {
737            cuts[second].push(second_parameter);
738        }
739    };
740    if indexed {
741        visit_segment_pairs(segments, tolerance, &mut intersect_pair);
742    } else {
743        for first in 0..segments.len() {
744            for second in first + 1..segments.len() {
745                intersect_pair(first, second);
746            }
747        }
748    }
749
750    let mut pieces = Vec::new();
751    for (index, segment) in segments.iter().enumerate() {
752        let mut parameters = vec![0.0];
753        cuts[index].sort_by(f64::total_cmp);
754        parameters.extend(cuts[index].iter().copied());
755        parameters.push(1.0);
756        let parameter_tolerance = tolerance_parameter(segment, tolerance);
757        let mut deduplicated: Vec<f64> = Vec::new();
758        for parameter in parameters {
759            if deduplicated
760                .last()
761                .is_none_or(|previous| parameter - *previous > parameter_tolerance)
762            {
763                deduplicated.push(parameter);
764            } else if parameter == 1.0 {
765                *deduplicated.last_mut().unwrap() = 1.0;
766            }
767        }
768        for pair in deduplicated.windows(2) {
769            let a = interpolate(segment.a, segment.b, pair[0]);
770            let b = interpolate(segment.a, segment.b, pair[1]);
771            if a.distance(b) <= tolerance {
772                continue;
773            }
774            pieces.push(PieceInput {
775                a,
776                b,
777                parent: if defer_tags { std::borrow::Cow::Borrowed(segment) } else { std::borrow::Cow::Owned(segment.clone()) },
778            });
779        }
780    }
781
782    let mut nodes: Vec<Node> = Vec::new();
783    let mut lookup = NodeLookup::new(tolerance, indexed_nodes && pieces.len() > 64);
784    let mut piece_start = Vec::with_capacity(pieces.len());
785    let mut piece_end = Vec::with_capacity(pieces.len());
786    for piece in &pieces {
787        piece_start.push(lookup.find_or_insert(piece.a, &mut nodes));
788        piece_end.push(lookup.find_or_insert(piece.b, &mut nodes));
789    }
790
791    let mut alive = vec![true; pieces.len()];
792    loop {
793        let mut pruned = false;
794        let mut degree = vec![0usize; nodes.len()];
795        for index in 0..pieces.len() {
796            if !alive[index] {
797                continue;
798            }
799            if piece_start[index] == piece_end[index] {
800                alive[index] = false;
801                pruned = true;
802                continue;
803            }
804            degree[piece_start[index]] += 1;
805            degree[piece_end[index]] += 1;
806        }
807        for index in 0..pieces.len() {
808            if alive[index] && (degree[piece_start[index]] == 1 || degree[piece_end[index]] == 1) {
809                alive[index] = false;
810                pruned = true;
811            }
812        }
813        if !pruned {
814            break;
815        }
816    }
817
818    let half_tail = |half_edge: usize| {
819        if half_edge % 2 == 0 {
820            piece_start[half_edge >> 1]
821        } else {
822            piece_end[half_edge >> 1]
823        }
824    };
825    let half_head = |half_edge: usize| {
826        if half_edge % 2 == 0 {
827            piece_end[half_edge >> 1]
828        } else {
829            piece_start[half_edge >> 1]
830        }
831    };
832    for node in &mut nodes {
833        node.outgoing.clear();
834    }
835    for index in 0..pieces.len() {
836        if !alive[index] {
837            continue;
838        }
839        nodes[piece_start[index]].outgoing.push(index * 2);
840        nodes[piece_end[index]].outgoing.push(index * 2 + 1);
841    }
842    let angles: Vec<f64> = (0..pieces.len() * 2)
843        .map(|half_edge| {
844            let tail = nodes[half_tail(half_edge)].point;
845            let head = nodes[half_head(half_edge)].point;
846            (head.y - tail.y).atan2(head.x - tail.x)
847        })
848        .collect();
849    // DIGON ORDER: two pieces joining the SAME two nodes (a cut lying along a
850    // trim edge for its last stretch, merged onto the edge's nodes) leave
851    // the same angle at both ends, and a sort by angle alone keeps them in
852    // insertion order at BOTH nodes, which no planar embedding has: the walk
853    // then crosses between the two sides of the pair and stitches the region
854    // beside it into the outer cycle, so the region is lost (an offset
855    // fillet's skin vanished at a miter corner, 2026-11-07). Equal
856    // angles are ordered by piece index, reversed at the higher node, so the
857    // pair bounds an empty digon and both neighbours close.
858    let digon_order = digon_order_enabled();
859    for node in &mut nodes {
860        node.outgoing.sort_by(|a, b| {
861            angles[*a].total_cmp(&angles[*b]).then_with(|| {
862                if !digon_order {
863                    return std::cmp::Ordering::Equal;
864                }
865                let rank = |half_edge: usize| {
866                    let piece = (half_edge >> 1) as i64;
867                    if half_tail(half_edge) < half_head(half_edge) {
868                        piece
869                    } else {
870                        -piece
871                    }
872                };
873                rank(*a).cmp(&rank(*b))
874            })
875        });
876    }
877
878    let mut visited = rustc_hash::FxHashSet::default();
879    let mut positive = Vec::new();
880    let mut negative = Vec::new();
881    for index in 0..pieces.len() {
882        if !alive[index] {
883            continue;
884        }
885        for start in [index * 2, index * 2 + 1] {
886            if visited.contains(&start) {
887                continue;
888            }
889            let mut uses = if defer_tags { CycleUses::Deferred(Vec::new()) } else { CycleUses::Eager(Vec::new()) };
890            let mut node_indices = Vec::new();
891            let mut area = 0.0;
892            let mut half_edge = start;
893            let mut guard = 0;
894            loop {
895                visited.insert(half_edge);
896                uses.push(half_edge, &pieces);
897                let tail_index = half_tail(half_edge);
898                let head_index = half_head(half_edge);
899                let tail = nodes[tail_index].point;
900                let head = nodes[head_index].point;
901                area += 0.5 * (tail.x * head.y - head.x * tail.y);
902                node_indices.push(tail_index);
903                let reverse = half_edge ^ 1;
904                let outgoing = &nodes[head_index].outgoing;
905                let reverse_index = outgoing
906                    .iter()
907                    .position(|candidate| *candidate == reverse)
908                    .ok_or_else(|| "arrangeSegments: reverse half-edge missing".to_string())?;
909                half_edge = outgoing[(reverse_index + outgoing.len() - 1) % outgoing.len()];
910                guard += 1;
911                if guard > pieces.len() * 4 + 8 {
912                    return Err("arrangeSegments: face walk did not terminate".into());
913                }
914                if half_edge == start {
915                    break;
916                }
917            }
918            let cycle = Cycle {
919                uses,
920                area,
921                node_indices,
922            };
923            if area > tolerance * tolerance {
924                positive.push(cycle);
925            } else if area < -tolerance * tolerance {
926                negative.push(cycle);
927            }
928        }
929    }
930
931    positive.sort_by(|a, b| a.area.total_cmp(&b.area));
932    let mut regions: Vec<(ArrangementRegion, Vec<Vec2>)> = positive
933        .into_iter()
934        .map(|cycle| {
935            let polygon = cycle
936                .node_indices
937                .iter()
938                .map(|index| nodes[*index].point)
939                .collect();
940            (
941                ArrangementRegion {
942                    outer: cycle.uses.into_uses(&pieces),
943                    holes: Vec::new(),
944                    area: cycle.area,
945                    outer_area: cycle.area,
946                },
947                polygon,
948            )
949        })
950        .collect();
951    let hole_boxes = hole_box_reject_enabled();
952    let boxes: Vec<[f64; 5]> = if hole_boxes {
953        regions.iter().map(|(_, polygon)| polygon_reject_box(polygon, tolerance)).collect()
954    } else {
955        Vec::new()
956    };
957    let mut bands: Vec<Option<BoundaryBand>> = (0..regions.len()).map(|_| None).collect();
958    for cycle in negative {
959        for (region_index, (region, polygon)) in regions.iter_mut().enumerate() {
960            let mut inside = false;
961            let mut on_boundary = false;
962            for node_index in &cycle.node_indices {
963                let point = nodes[*node_index].point;
964                let class = if hole_boxes && outside_reject_box(point, &boxes[region_index]) {
965                    PolygonClass::Outside
966                } else if hole_boxes {
967                    let band = bands[region_index].get_or_insert_with(|| BoundaryBand::new(polygon, tolerance));
968                    band.classify(point, polygon, tolerance)
969                } else {
970                    point_in_polygon_class(point, polygon, tolerance)
971                };
972                match class {
973                    PolygonClass::Boundary => {
974                        on_boundary = true;
975                        continue;
976                    }
977                    PolygonClass::Inside => {
978                        inside = true;
979                        on_boundary = false;
980                        break;
981                    }
982                    PolygonClass::Outside => {
983                        inside = false;
984                        on_boundary = false;
985                        break;
986                    }
987                }
988            }
989            if on_boundary {
990                continue;
991            }
992            if inside {
993                region.holes.push(cycle.uses.copy_uses(&pieces));
994                region.area += cycle.area;
995                break;
996            }
997        }
998    }
999    if crate::profile::profile_enabled() {
1000        let holes: usize = regions.iter().flat_map(|(r, _)| r.holes.iter()).map(Vec::len).sum();
1001        let returned: usize = holes + regions.iter().map(|(r, _)| r.outer.len()).sum::<usize>();
1002        let clones = if defer_tags { returned } else { pieces.len() + visited.len() + holes };
1003        crate::profile::profile_emit(format_args!("arrange.tags segments={} pieces={} walked={} returned={returned} parent_clones={clones} deferred={defer_tags}", segments.len(), pieces.len(), visited.len()));
1004    }
1005    Ok(regions.into_iter().map(|(region, _)| region).collect())
1006}
1007
1008