Skip to main content

brep_kernel/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(crate) fn sub(self, other: Self) -> Self {
42        Self {
43            x: self.x - other.x,
44            y: self.y - other.y,
45        }
46    }
47    pub(crate) fn add(self, other: Self) -> Self {
48        Self {
49            x: self.x + other.x,
50            y: self.y + other.y,
51        }
52    }
53    pub(crate) 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(crate) 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(crate) 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
231pub use crate::polygon::PolygonClass;
232
233fn point_segment_distance(point: Vec2, a: Vec2, b: Vec2) -> f64 {
234    point.distance_to_segment(a, b, 1e-300)
235}
236
237/// The hole assignment's box rejection (2026-11-02): a point
238/// beyond a region polygon's vertex box by more than the classifier's
239/// tolerance plus a rounding pad is classified Outside without the O(n) test,
240/// and the full classifier would say the same. Its boundary band cannot fire
241/// (every computed segment distance exceeds the tolerance: the clamped foot
242/// lies in the box up to rounding the pad covers). Its form-K parity reads
243/// Outside: above or below the box no edge straddles the ray; to the right no
244/// crossing lies right of the point; to the left every straddling edge crosses
245/// right of it, and a closed loop has an even number of them. The hole loop
246/// was 60-70% of the arrangement's time on the package models (one negative
247/// cycle tested node by node against every positive region's polygon).
248/// Returns `[min_x, min_y, max_x, max_y, reach]`; `reach` is NaN (never
249/// reject) for an empty or non-finite polygon.
250fn polygon_reject_box(polygon: &[Vec2], tolerance: f64) -> [f64; 5] {
251    let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
252    let mut magnitude = 1.0f64;
253    for point in polygon {
254        bounds[0] = bounds[0].min(point.x);
255        bounds[1] = bounds[1].min(point.y);
256        bounds[2] = bounds[2].max(point.x);
257        bounds[3] = bounds[3].max(point.y);
258        magnitude = magnitude.max(point.x.abs()).max(point.y.abs());
259    }
260    let finite = !polygon.is_empty() && bounds.iter().all(|value| value.is_finite()) && tolerance.is_finite() && tolerance >= 0.0;
261    let reach = if finite { tolerance * (1.0 + 1e-9) + 64.0 * f64::EPSILON * magnitude } else { f64::NAN };
262    [bounds[0], bounds[1], bounds[2], bounds[3], reach]
263}
264
265/// The classifier's boundary band, indexed (2026-11-02): a
266/// uniform grid over the polygon's vertex box whose cells list every edge whose
267/// box, widened by the tolerance plus a rounding pad, overlaps them. An edge
268/// whose computed distance to a point is within the tolerance has that point
269/// inside its widened box (the clamped foot lies in the edge's box up to
270/// rounding the pad covers), so the point's cell lists it; the band is an
271/// existence test, so testing the listed edges with the classifier's own
272/// distance gives the classifier's own answer. Parity is the original full
273/// scan. Why: a negative cycle that runs along a region's own boundary
274/// classifies Boundary at every node and goes on to the next, so the hole loop
275/// paid one full O(n) band scan per node.
276struct BoundaryBand {
277    origin: [f64; 2],
278    cell: [f64; 2],
279    side: usize,
280    reach: f64,
281    starts: Vec<u32>,
282    items: Vec<u32>,
283    usable: bool,
284}
285
286impl BoundaryBand {
287    fn new(polygon: &[Vec2], tolerance: f64) -> Self {
288        let reject = polygon_reject_box(polygon, tolerance);
289        let reach = reject[4];
290        let count = polygon.len();
291        let usable = reach.is_finite() && count >= 16 && count <= (1 << 24);
292        let side = if usable { ((count as f64).sqrt() as usize).clamp(4, 512) } else { 0 };
293        let origin = [reject[0] - reach, reject[1] - reach];
294        let extent = [(reject[2] + reach) - origin[0], (reject[3] + reach) - origin[1]];
295        let cell = [(extent[0] / side.max(1) as f64).max(f64::MIN_POSITIVE), (extent[1] / side.max(1) as f64).max(f64::MIN_POSITIVE)];
296        let mut band = Self { origin, cell, side, reach, starts: Vec::new(), items: Vec::new(), usable };
297        if !band.usable {
298            return band;
299        }
300        let mut counts = vec![0u32; side * side + 1];
301        let ranges: Vec<[usize; 4]> = (0..count)
302            .map(|index| {
303                let (a, b) = (polygon[index], polygon[(index + 1) % count]);
304                let pad = reach + 64.0 * f64::EPSILON * a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs());
305                [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)]
306            })
307            .collect();
308        for range in &ranges {
309            for y in range[2]..=range[3] {
310                for x in range[0]..=range[1] {
311                    counts[y * side + x + 1] += 1;
312                }
313            }
314        }
315        for index in 1..counts.len() {
316            counts[index] += counts[index - 1];
317        }
318        // Long edges cover many cells; past a budget the original scan is cheaper.
319        if counts[side * side] as usize > 64 * count + 4096 {
320            band.usable = false;
321            return band;
322        }
323        let mut cursor = counts.clone();
324        band.items = vec![0u32; counts[side * side] as usize];
325        for (edge, range) in ranges.iter().enumerate() {
326            for y in range[2]..=range[3] {
327                for x in range[0]..=range[1] {
328                    let slot = &mut cursor[y * side + x];
329                    band.items[*slot as usize] = edge as u32;
330                    *slot += 1;
331                }
332            }
333        }
334        band.starts = counts;
335        band
336    }
337    fn column(&self, x: f64) -> usize {
338        (((x - self.origin[0]) / self.cell[0]).floor().max(0.0) as usize).min(self.side - 1)
339    }
340    fn row(&self, y: f64) -> usize {
341        (((y - self.origin[1]) / self.cell[1]).floor().max(0.0) as usize).min(self.side - 1)
342    }
343    fn classify(&self, point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
344        if !self.usable || !point.x.is_finite() || !point.y.is_finite() {
345            return point_in_polygon_class(point, polygon, tolerance);
346        }
347        let cell = self.row(point.y) * self.side + self.column(point.x);
348        let count = polygon.len();
349        for &edge in &self.items[self.starts[cell] as usize..self.starts[cell + 1] as usize] {
350            let edge = edge as usize;
351            if point.distance_to_segment(polygon[edge], polygon[(edge + 1) % count], 1e-300) <= tolerance {
352                return PolygonClass::Boundary;
353            }
354        }
355        if crate::polygon::parity_inside([point.x, point.y], count, |i| [polygon[i].x, polygon[i].y]) {
356            PolygonClass::Inside
357        } else {
358            PolygonClass::Outside
359        }
360    }
361}
362
363fn outside_reject_box(point: Vec2, reject: &[f64; 5]) -> bool {
364    let reach = reject[4] + 64.0 * f64::EPSILON * point.x.abs().max(point.y.abs());
365    // NaN `reach` (or a NaN point) makes every comparison false: never reject.
366    point.x < reject[0] - reach || point.y < reject[1] - reach || point.x > reject[2] + reach || point.y > reject[3] + reach
367}
368
369fn hole_box_reject_enabled() -> bool {
370    switch!("BREP_ARRANGE_HOLE_BOX", true)
371}
372
373
374fn point_in_polygon_class(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
375    crate::polygon::classify(point, polygon, tolerance, 1e-300)
376}
377
378pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> &'static str {
379    match point_in_polygon_class(point, polygon, tolerance) {
380        PolygonClass::Inside => "in",
381        PolygonClass::Outside => "out",
382        PolygonClass::Boundary => "boundary",
383    }
384}
385
386#[derive(Clone)]
387struct Cycle {
388    uses: Vec<CycleUse>,
389    area: f64,
390    node_indices: Vec<usize>,
391}
392
393/// Visit a conservative subset of pairs in original input order. The narrow
394/// phase remains authoritative, including its endpoint tolerance and rounding.
395fn visit_segment_pairs(segments: &[Segment2], tolerance: f64, mut visit: impl FnMut(usize, usize)) {
396    let all_pairs = |visit: &mut dyn FnMut(usize, usize)| {
397        for first in 0..segments.len() {
398            for second in first + 1..segments.len() {
399                visit(first, second);
400            }
401        }
402    };
403    if segments.len() <= 32
404        || segments.len() > u32::MAX as usize
405        || !tolerance.is_finite()
406        || tolerance < 0.0
407        || tolerance > 1e100
408    {
409        all_pairs(&mut visit);
410        return;
411    }
412    let mut scale = 0.0f64;
413    let mut boxes = Vec::with_capacity(segments.len());
414    let mut extent = Aabb::empty();
415    for segment in segments {
416        let coordinates = [segment.a.x, segment.a.y, segment.b.x, segment.b.y];
417        let length = segment.a.distance(segment.b);
418        // Keep the legacy scan for numeric extremes: underflow/overflow or NaN
419        // in the narrow phase need not behave like geometric intersection.
420        if coordinates
421            .iter()
422            .any(|v| !v.is_finite() || v.abs() > 1e100)
423            || !(1e-100..=1e100).contains(&length)
424        {
425            all_pairs(&mut visit);
426            return;
427        }
428        for coordinate in coordinates {
429            scale = scale.max(coordinate.abs());
430        }
431        let bounds = Aabb {
432            minimum: Vec3::new(
433                segment.a.x.min(segment.b.x),
434                segment.a.y.min(segment.b.y),
435                0.0,
436            ),
437            maximum: Vec3::new(
438                segment.a.x.max(segment.b.x),
439                segment.a.y.max(segment.b.y),
440                0.0,
441            ),
442        };
443        extent.include(bounds);
444        boxes.push(bounds);
445    }
446    // Each accepted parameter may extend its segment by up to tolerance.
447    // Cross-product roundoff is amplified by up to 1/PARALLEL_THRESHOLD when
448    // solving the parameters. Bound it using the global coordinate magnitude
449    // (including translation), with headroom for subtraction, products, length
450    // and division rounding. This deliberately admits extra pairs near parallel
451    // lines instead of treating exact endpoint boxes as a bound on an inexact
452    // solve. The numeric guards above keep these operations in the normal range.
453    let padding = 2.0 * tolerance + 128.0 * f64::EPSILON / PARALLEL_THRESHOLD * scale;
454    // A large translation or tolerance can swallow the entire arrangement.
455    // An index cannot reject anything then, so avoid its query/sort overhead.
456    if padding >= extent.diagonal() {
457        all_pairs(&mut visit);
458        return;
459    }
460    let direction_tiers = direction_index_on();
461    // Row 29: the direction tiers' small-padding query is answered by a
462    // one-axis sweep instead of the tree, which is then not built (`None`
463    // from the sweep keeps the tree).
464    let small_padding = 2.0 * tolerance + 128.0 * f64::EPSILON / DIRECTION_SINE * scale;
465    let swept = if direction_tiers && arrange_sweep_on() { swept_pairs(&boxes, small_padding) } else { None };
466    let tree = swept.is_none().then(|| Bvh::build(&boxes));
467    let mut candidates = Vec::new();
468    if direction_tiers {
469        // DIRECTION TIERS (lane O, 2026-10-28). The padding above is what a
470        // pair as near-parallel as the narrow phase admits (`sin θ` down to
471        // PARALLEL_THRESHOLD) can need, and on a face whose uv sit far from
472        // the origin it reaches across most of the arrangement: the filleted
473        // box's outward offset sends a 252-segment quarter-arc chain through
474        // here twice per attempt and the index visited nearly all 37 000
475        // pairs (0.7 ms a face). The same rounding model bounds a pair whose
476        // directions differ by `sin θ ≥ s` with the padding at `s` in place of
477        // the threshold. So every pair is visited under that small padding,
478        // and a pair whose directions lie within one bucket of each other
479        // (width `2s`, wrapping at π) — the only pairs that can be nearer
480        // parallel than `s` — under the full padding as before. Visit order
481        // and the narrow phase are unchanged; the visited set still contains
482        // every pair the full padding could accept.
483        let width = 2.0 * DIRECTION_SINE;
484        let bucket_count = ((std::f64::consts::PI / width).ceil() as usize).max(1);
485        let mut buckets: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
486        let bucket_of: Vec<usize> = segments
487            .iter()
488            .map(|segment| {
489                let angle = (segment.b.y - segment.a.y).atan2(segment.b.x - segment.a.x).rem_euclid(std::f64::consts::PI);
490                ((angle / width) as usize).min(bucket_count - 1)
491            })
492            .collect();
493        for (index, bucket) in bucket_of.iter().enumerate() {
494            buckets.entry(*bucket).or_default().push(index);
495        }
496        let near = |a: &Aabb, b: &Aabb| {
497            a.minimum.x - padding <= b.maximum.x
498                && b.minimum.x - padding <= a.maximum.x
499                && a.minimum.y - padding <= b.maximum.y
500                && b.minimum.y - padding <= a.maximum.y
501        };
502        for (first, &bounds) in boxes.iter().enumerate() {
503            candidates.clear();
504            match (&swept, &tree) {
505                (Some(lists), _) => candidates.extend_from_slice(&lists[first]),
506                (None, Some(tree)) => tree.overlapping(bounds, small_padding, &mut candidates),
507                (None, None) => unreachable!("the tree is built whenever the sweep is not"),
508            }
509            let bucket = bucket_of[first];
510            for neighbour in [(bucket + bucket_count - 1) % bucket_count, bucket, (bucket + 1) % bucket_count] {
511                if let Some(members) = buckets.get(&neighbour) {
512                    candidates.extend(members.iter().copied().filter(|&second| second > first && near(&bounds, &boxes[second])));
513                }
514                if bucket_count < 3 {
515                    break;
516                }
517            }
518            candidates.retain(|&second| second > first);
519            candidates.sort_unstable();
520            candidates.dedup();
521            for &second in &candidates {
522                visit(first, second);
523            }
524        }
525        return;
526    }
527    let Some(tree) = tree else { unreachable!("the sweep runs only under the direction tiers") };
528    for (first, &bounds) in boxes.iter().enumerate() {
529        candidates.clear();
530        tree.overlapping(bounds, padding, &mut candidates);
531        candidates.retain(|&second| second > first);
532        candidates.sort_unstable();
533        for &second in &candidates {
534            visit(first, second);
535        }
536    }
537}
538
539/// The direction sine above which [`visit_segment_pairs`] pads a pair with
540/// the small padding (see DIRECTION TIERS there).
541const DIRECTION_SINE: f64 = 1e-3;
542
543/// Lane O row 29 (2026-10-30, `BREP_ARRANGE_SWEEP`, default on since batch 12;
544/// `0`/`off` restores the tree): for each box `first`, every `second > first` whose box passes
545/// the tree's own leaf test `boxes[second].intersects(boxes[first], padding)`
546/// — the set [`Bvh::overlapping`] returns past `second > first`, since a node
547/// box contains its items' boxes — in ascending order. The candidates come
548/// from a sweep over the boxes sorted by their minimum on one axis, each
549/// scanning forward while the next minimum is within its maximum plus twice
550/// the padding: a pair the leaf test admits lies within the padding plus one
551/// rounding of either subtraction there, and the padding (at least
552/// 128 ε / DIRECTION_SINE of the largest coordinate) exceeds that rounding.
553///
554/// The axis is the one whose sweep windows (counted by binary search before
555/// any test runs) are fewer in total; when even those exceed 32 a box, the
556/// boxes overlap along both axes and `None` hands the query back to the tree,
557/// which prunes on both at once (a guard: of the D1, inward opposed and
558/// outward 3-adjacent shell cases probed, only D1 reaches the sweep, and
559/// never the fallback). D1's two 272-segment faces spent 0.38 ms a run
560/// building and querying the tree for 570 narrow-phase pairs that cost
561/// 0.04 ms.
562fn swept_pairs(boxes: &[Aabb], padding: f64) -> Option<Vec<Vec<usize>>> {
563    let reach = 2.0 * padding;
564    let low = |index: usize, axis: usize| if axis == 0 { boxes[index].minimum.x } else { boxes[index].minimum.y };
565    let high = |index: usize, axis: usize| if axis == 0 { boxes[index].maximum.x } else { boxes[index].maximum.y };
566    let mut best: Option<(usize, Vec<usize>, usize)> = None;
567    for axis in [0, 1] {
568        let mut order: Vec<usize> = (0..boxes.len()).collect();
569        order.sort_by(|&a, &b| low(a, axis).total_cmp(&low(b, axis)));
570        let lows: Vec<f64> = order.iter().map(|&index| low(index, axis)).collect();
571        let windows: usize = order
572            .iter()
573            .enumerate()
574            .map(|(position, &a)| {
575                let limit = high(a, axis) + reach;
576                lows.partition_point(|&value| value <= limit).saturating_sub(position + 1)
577            })
578            .sum();
579        if best.as_ref().is_none_or(|(least, _, _)| windows < *least) {
580            best = Some((windows, order, axis));
581        }
582    }
583    let (windows, order, axis) = best?;
584    if windows > 32 * boxes.len() {
585        return None;
586    }
587    let mut lists = vec![Vec::new(); boxes.len()];
588    for (position, &a) in order.iter().enumerate() {
589        let limit = high(a, axis) + reach;
590        for &b in &order[position + 1..] {
591            if low(b, axis) > limit {
592                break;
593            }
594            let (first, second) = if a < b { (a, b) } else { (b, a) };
595            if boxes[second].intersects(boxes[first], padding) {
596                lists[first].push(second);
597            }
598        }
599    }
600    for list in &mut lists {
601        list.sort_unstable();
602    }
603    Some(lists)
604}
605
606/// Row 29's switch ([`swept_pairs`]), read once.
607fn arrange_sweep_on() -> bool {
608    switch!("BREP_ARRANGE_SWEEP", true)
609}
610
611
612/// The direction tiers of [`visit_segment_pairs`], on unless
613/// `BREP_ARRANGE_DIRECTION_INDEX` is `0`/`off` (the A/B lever). Read once.
614fn direction_index_on() -> bool {
615    switch!("BREP_ARRANGE_DIRECTION_INDEX", true)
616}
617
618pub fn arrange_segments(
619    segments: &[Segment2],
620    tolerance: f64,
621) -> Result<Vec<ArrangementRegion>, String> {
622    arrange_segments_impl(segments, tolerance, true, true)
623}
624
625fn arrange_segments_impl(
626    segments: &[Segment2],
627    tolerance: f64,
628    indexed: bool,
629    indexed_nodes: bool,
630) -> Result<Vec<ArrangementRegion>, String> {
631    let mut cuts = vec![Vec::<f64>::new(); segments.len()];
632    let mut intersect_pair = |first: usize, second: usize| {
633        let Some([first_parameter, second_parameter]) = segment_intersection(
634            segments[first].a,
635            segments[first].b,
636            segments[second].a,
637            segments[second].b,
638            tolerance,
639        ) else {
640            return;
641        };
642        let first_tolerance = tolerance_parameter(&segments[first], tolerance);
643        let second_tolerance = tolerance_parameter(&segments[second], tolerance);
644        if first_parameter > first_tolerance && first_parameter < 1.0 - first_tolerance {
645            cuts[first].push(first_parameter);
646        }
647        if second_parameter > second_tolerance && second_parameter < 1.0 - second_tolerance {
648            cuts[second].push(second_parameter);
649        }
650    };
651    if indexed {
652        visit_segment_pairs(segments, tolerance, &mut intersect_pair);
653    } else {
654        for first in 0..segments.len() {
655            for second in first + 1..segments.len() {
656                intersect_pair(first, second);
657            }
658        }
659    }
660
661    let mut pieces = Vec::new();
662    for (index, segment) in segments.iter().enumerate() {
663        let mut parameters = vec![0.0];
664        cuts[index].sort_by(f64::total_cmp);
665        parameters.extend(cuts[index].iter().copied());
666        parameters.push(1.0);
667        let parameter_tolerance = tolerance_parameter(segment, tolerance);
668        let mut deduplicated: Vec<f64> = Vec::new();
669        for parameter in parameters {
670            if deduplicated
671                .last()
672                .is_none_or(|previous| parameter - *previous > parameter_tolerance)
673            {
674                deduplicated.push(parameter);
675            } else if parameter == 1.0 {
676                *deduplicated.last_mut().unwrap() = 1.0;
677            }
678        }
679        for pair in deduplicated.windows(2) {
680            let a = interpolate(segment.a, segment.b, pair[0]);
681            let b = interpolate(segment.a, segment.b, pair[1]);
682            if a.distance(b) <= tolerance {
683                continue;
684            }
685            pieces.push(ArrangementPiece {
686                a,
687                b,
688                parent: segment.clone(),
689            });
690        }
691    }
692
693    let mut nodes: Vec<Node> = Vec::new();
694    let mut lookup = NodeLookup::new(tolerance, indexed_nodes && pieces.len() > 64);
695    let mut piece_start = Vec::with_capacity(pieces.len());
696    let mut piece_end = Vec::with_capacity(pieces.len());
697    for piece in &pieces {
698        piece_start.push(lookup.find_or_insert(piece.a, &mut nodes));
699        piece_end.push(lookup.find_or_insert(piece.b, &mut nodes));
700    }
701
702    let mut alive = vec![true; pieces.len()];
703    loop {
704        let mut pruned = false;
705        let mut degree = vec![0usize; nodes.len()];
706        for index in 0..pieces.len() {
707            if !alive[index] {
708                continue;
709            }
710            if piece_start[index] == piece_end[index] {
711                alive[index] = false;
712                pruned = true;
713                continue;
714            }
715            degree[piece_start[index]] += 1;
716            degree[piece_end[index]] += 1;
717        }
718        for index in 0..pieces.len() {
719            if alive[index] && (degree[piece_start[index]] == 1 || degree[piece_end[index]] == 1) {
720                alive[index] = false;
721                pruned = true;
722            }
723        }
724        if !pruned {
725            break;
726        }
727    }
728
729    let half_tail = |half_edge: usize| {
730        if half_edge % 2 == 0 {
731            piece_start[half_edge >> 1]
732        } else {
733            piece_end[half_edge >> 1]
734        }
735    };
736    let half_head = |half_edge: usize| {
737        if half_edge % 2 == 0 {
738            piece_end[half_edge >> 1]
739        } else {
740            piece_start[half_edge >> 1]
741        }
742    };
743    for node in &mut nodes {
744        node.outgoing.clear();
745    }
746    for index in 0..pieces.len() {
747        if !alive[index] {
748            continue;
749        }
750        nodes[piece_start[index]].outgoing.push(index * 2);
751        nodes[piece_end[index]].outgoing.push(index * 2 + 1);
752    }
753    let angles: Vec<f64> = (0..pieces.len() * 2)
754        .map(|half_edge| {
755            let tail = nodes[half_tail(half_edge)].point;
756            let head = nodes[half_head(half_edge)].point;
757            (head.y - tail.y).atan2(head.x - tail.x)
758        })
759        .collect();
760    for node in &mut nodes {
761        node.outgoing
762            .sort_by(|a, b| angles[*a].total_cmp(&angles[*b]));
763    }
764
765    let mut visited = rustc_hash::FxHashSet::default();
766    let mut positive = Vec::new();
767    let mut negative = Vec::new();
768    for index in 0..pieces.len() {
769        if !alive[index] {
770            continue;
771        }
772        for start in [index * 2, index * 2 + 1] {
773            if visited.contains(&start) {
774                continue;
775            }
776            let mut uses = Vec::new();
777            let mut node_indices = Vec::new();
778            let mut area = 0.0;
779            let mut half_edge = start;
780            let mut guard = 0;
781            loop {
782                visited.insert(half_edge);
783                let piece_index = half_edge >> 1;
784                uses.push(CycleUse {
785                    piece: pieces[piece_index].clone(),
786                    forward: half_edge % 2 == 0,
787                });
788                let tail_index = half_tail(half_edge);
789                let head_index = half_head(half_edge);
790                let tail = nodes[tail_index].point;
791                let head = nodes[head_index].point;
792                area += 0.5 * (tail.x * head.y - head.x * tail.y);
793                node_indices.push(tail_index);
794                let reverse = half_edge ^ 1;
795                let outgoing = &nodes[head_index].outgoing;
796                let reverse_index = outgoing
797                    .iter()
798                    .position(|candidate| *candidate == reverse)
799                    .ok_or_else(|| "arrangeSegments: reverse half-edge missing".to_string())?;
800                half_edge = outgoing[(reverse_index + outgoing.len() - 1) % outgoing.len()];
801                guard += 1;
802                if guard > pieces.len() * 4 + 8 {
803                    return Err("arrangeSegments: face walk did not terminate".into());
804                }
805                if half_edge == start {
806                    break;
807                }
808            }
809            let cycle = Cycle {
810                uses,
811                area,
812                node_indices,
813            };
814            if area > tolerance * tolerance {
815                positive.push(cycle);
816            } else if area < -tolerance * tolerance {
817                negative.push(cycle);
818            }
819        }
820    }
821
822    positive.sort_by(|a, b| a.area.total_cmp(&b.area));
823    let mut regions: Vec<(ArrangementRegion, Vec<Vec2>)> = positive
824        .into_iter()
825        .map(|cycle| {
826            let polygon = cycle
827                .node_indices
828                .iter()
829                .map(|index| nodes[*index].point)
830                .collect();
831            (
832                ArrangementRegion {
833                    outer: cycle.uses,
834                    holes: Vec::new(),
835                    area: cycle.area,
836                    outer_area: cycle.area,
837                },
838                polygon,
839            )
840        })
841        .collect();
842    let hole_boxes = hole_box_reject_enabled();
843    let boxes: Vec<[f64; 5]> = if hole_boxes {
844        regions.iter().map(|(_, polygon)| polygon_reject_box(polygon, tolerance)).collect()
845    } else {
846        Vec::new()
847    };
848    let mut bands: Vec<Option<BoundaryBand>> = (0..regions.len()).map(|_| None).collect();
849    for cycle in negative {
850        for (region_index, (region, polygon)) in regions.iter_mut().enumerate() {
851            let mut inside = false;
852            let mut on_boundary = false;
853            for node_index in &cycle.node_indices {
854                let point = nodes[*node_index].point;
855                let class = if hole_boxes && outside_reject_box(point, &boxes[region_index]) {
856                    PolygonClass::Outside
857                } else if hole_boxes {
858                    let band = bands[region_index].get_or_insert_with(|| BoundaryBand::new(polygon, tolerance));
859                    band.classify(point, polygon, tolerance)
860                } else {
861                    point_in_polygon_class(point, polygon, tolerance)
862                };
863                match class {
864                    PolygonClass::Boundary => {
865                        on_boundary = true;
866                        continue;
867                    }
868                    PolygonClass::Inside => {
869                        inside = true;
870                        on_boundary = false;
871                        break;
872                    }
873                    PolygonClass::Outside => {
874                        inside = false;
875                        on_boundary = false;
876                        break;
877                    }
878                }
879            }
880            if on_boundary {
881                continue;
882            }
883            if inside {
884                region.holes.push(cycle.uses.clone());
885                region.area += cycle.area;
886                break;
887            }
888        }
889    }
890    Ok(regions.into_iter().map(|(region, _)| region).collect())
891}
892