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        self.find_or_insert_where(point, nodes, |_| true)
143    }
144
145    /// [`Self::find_or_insert`] matching only nodes `accept` admits (lens
146    /// pairs kept apart, [`arrange_segments_lens_apart`]).
147    fn find_or_insert_where(&mut self, point: Vec2, nodes: &mut Vec<Node>, accept: impl Fn(usize) -> bool) -> usize {
148        let key = self.cells.as_ref().and_then(|_| self.key(point));
149        if key.is_none() {
150            // Once a point cannot be indexed, retain the scan for the rest of
151            // the stream, including comparisons against this newly added node.
152            self.cells = None;
153        }
154        let found = if let (Some(cells), Some([x, y])) = (&self.cells, key) {
155            let mut first = None;
156            for dx in -1..=1 {
157                for dy in -1..=1 {
158                    if let Some(indices) = cells.get(&[x + dx, y + dy]) {
159                        // Each bucket is in insertion order. Later nodes in
160                        // this bucket cannot beat an already earlier match.
161                        for &index in indices {
162                            if first.is_some_and(|first| index >= first) {
163                                break;
164                            }
165                            if nodes[index].point.distance(point) <= self.tolerance && accept(index) {
166                                first = Some(index);
167                                break;
168                            }
169                        }
170                    }
171                }
172            }
173            first
174        } else {
175            nodes
176                .iter()
177                .enumerate()
178                .position(|(index, node)| node.point.distance(point) <= self.tolerance && accept(index))
179        };
180        if let Some(index) = found {
181            return index;
182        }
183        let index = nodes.len();
184        nodes.push(Node {
185            point,
186            outgoing: Vec::new(),
187        });
188        if let (Some(cells), Some(key)) = (&mut self.cells, key) {
189            cells.entry(key).or_default().push(index);
190        }
191        index
192    }
193}
194
195fn tolerance_parameter(segment: &Segment2, tolerance: f64) -> f64 {
196    let length = segment.a.distance(segment.b);
197    if length <= tolerance {
198        0.5
199    } else {
200        tolerance / length
201    }
202}
203
204fn interpolate(a: Vec2, b: Vec2, parameter: f64) -> Vec2 {
205    Vec2 {
206        x: a.x + (b.x - a.x) * parameter,
207        y: a.y + (b.y - a.y) * parameter,
208    }
209}
210
211pub fn segment_intersection(
212    a1: Vec2,
213    b1: Vec2,
214    a2: Vec2,
215    b2: Vec2,
216    tolerance: f64,
217) -> Option<[f64; 2]> {
218    let d1 = b1.sub(a1);
219    let d2 = b2.sub(a2);
220    let denominator = d1.cross(d2);
221    let length1 = d1.length();
222    let length2 = d2.length();
223    if denominator.abs() <= PARALLEL_THRESHOLD * length1 * length2 {
224        return None;
225    }
226    let offset = a2.sub(a1);
227    let t1 = offset.cross(d2) / denominator;
228    let t2 = offset.cross(d1) / denominator;
229    let epsilon1 = tolerance / length1.max(tolerance);
230    let epsilon2 = tolerance / length2.max(tolerance);
231    if t1 < -epsilon1 || t1 > 1.0 + epsilon1 || t2 < -epsilon2 || t2 > 1.0 + epsilon2 {
232        None
233    } else {
234        Some([t1.clamp(0.0, 1.0), t2.clamp(0.0, 1.0)])
235    }
236}
237
238/// Where the ends of `end` touch the interior of `bar`, for a pair the line
239/// crossing rejected. `segment_intersection` measures its tolerance ALONG each
240/// segment, so a stem meeting a bar at a shallow angle overruns it: a gap `g`
241/// is `g / sin(angle)` along the stem. An end within tolerance of the bar then
242/// gets no node on it, keeps degree 1, and pruning removes the whole stem
243/// (a reported box and pin model: a 9.8e-8 gap at sin 0.035 against a 1.4e-6 tolerance).
244/// Parallel pairs stay excluded, as they are from the crossing test, and the
245/// caller keeps only an end no other segment shares: a chain's interior point
246/// riding within tolerance of a nearly collinear curve is not a T, and noding
247/// it would pinch the two together.
248/// `BREP_ARRANGE_END_ON_SEGMENT=0` turns this off.
249fn end_on_segment_parameters(end: &Segment2, bar: &Segment2, tolerance: f64) -> Vec<(Vec2, f64)> {
250    let (stem, span) = (end.b.sub(end.a), bar.b.sub(bar.a));
251    let squared = span.dot(span);
252    if squared <= 0.0 || stem.cross(span).abs() <= PARALLEL_THRESHOLD * stem.length() * span.length() {
253        return Vec::new();
254    }
255    let margin = tolerance_parameter(bar, tolerance);
256    [end.a, end.b]
257        .into_iter()
258        .filter_map(|point| {
259            let parameter = point.sub(bar.a).dot(span) / squared;
260            (parameter > margin
261                && parameter < 1.0 - margin
262                && point_segment_distance(point, bar.a, bar.b) <= tolerance)
263                .then_some((point, parameter))
264        })
265        .collect()
266}
267
268pub use crate::polygon::PolygonClass;
269
270fn point_segment_distance(point: Vec2, a: Vec2, b: Vec2) -> f64 {
271    point.distance_to_segment(a, b, 1e-300)
272}
273
274/// The hole assignment's box rejection (2026-11-02): a point
275/// beyond a region polygon's vertex box by more than the classifier's
276/// tolerance plus a rounding pad is classified Outside without the O(n) test,
277/// and the full classifier would say the same. Its boundary band cannot fire
278/// (every computed segment distance exceeds the tolerance: the clamped foot
279/// lies in the box up to rounding the pad covers). Its form-K parity reads
280/// Outside: above or below the box no edge straddles the ray; to the right no
281/// crossing lies right of the point; to the left every straddling edge crosses
282/// right of it, and a closed loop has an even number of them. The hole loop
283/// was 60-70% of the arrangement's time on the package models (one negative
284/// cycle tested node by node against every positive region's polygon).
285/// Returns `[min_x, min_y, max_x, max_y, reach]`; `reach` is NaN (never
286/// reject) for an empty or non-finite polygon.
287fn polygon_reject_box(polygon: &[Vec2], tolerance: f64) -> [f64; 5] {
288    let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
289    let mut magnitude = 1.0f64;
290    for point in polygon {
291        bounds[0] = bounds[0].min(point.x);
292        bounds[1] = bounds[1].min(point.y);
293        bounds[2] = bounds[2].max(point.x);
294        bounds[3] = bounds[3].max(point.y);
295        magnitude = magnitude.max(point.x.abs()).max(point.y.abs());
296    }
297    let finite = !polygon.is_empty() && bounds.iter().all(|value| value.is_finite()) && tolerance.is_finite() && tolerance >= 0.0;
298    let reach = if finite { tolerance * (1.0 + 1e-9) + 64.0 * f64::EPSILON * magnitude } else { f64::NAN };
299    [bounds[0], bounds[1], bounds[2], bounds[3], reach]
300}
301
302/// The classifier's boundary band, indexed (2026-11-02): a
303/// uniform grid over the polygon's vertex box whose cells list every edge whose
304/// box, widened by the tolerance plus a rounding pad, overlaps them. An edge
305/// whose computed distance to a point is within the tolerance has that point
306/// inside its widened box (the clamped foot lies in the edge's box up to
307/// rounding the pad covers), so the point's cell lists it; the band is an
308/// existence test, so testing the listed edges with the classifier's own
309/// distance gives the classifier's own answer. Parity is the original full
310/// scan. Why: a negative cycle that runs along a region's own boundary
311/// classifies Boundary at every node and goes on to the next, so the hole loop
312/// paid one full O(n) band scan per node.
313struct BoundaryBand {
314    origin: [f64; 2],
315    cell: [f64; 2],
316    side: usize,
317    starts: Vec<u32>,
318    items: Vec<u32>,
319    usable: bool,
320}
321
322impl BoundaryBand {
323    fn new(polygon: &[Vec2], tolerance: f64) -> Self {
324        let reject = polygon_reject_box(polygon, tolerance);
325        let reach = reject[4];
326        let count = polygon.len();
327        let usable = reach.is_finite() && count >= 16 && count <= (1 << 24);
328        let side = if usable { ((count as f64).sqrt() as usize).clamp(4, 512) } else { 0 };
329        let origin = [reject[0] - reach, reject[1] - reach];
330        let extent = [(reject[2] + reach) - origin[0], (reject[3] + reach) - origin[1]];
331        let cell = [(extent[0] / side.max(1) as f64).max(f64::MIN_POSITIVE), (extent[1] / side.max(1) as f64).max(f64::MIN_POSITIVE)];
332        let mut band = Self { origin, cell, side, starts: Vec::new(), items: Vec::new(), usable };
333        if !band.usable {
334            return band;
335        }
336        let mut counts = vec![0u32; side * side + 1];
337        let ranges: Vec<[usize; 4]> = (0..count)
338            .map(|index| {
339                let (a, b) = (polygon[index], polygon[(index + 1) % count]);
340                let pad = reach + 64.0 * f64::EPSILON * a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs());
341                [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)]
342            })
343            .collect();
344        for range in &ranges {
345            for y in range[2]..=range[3] {
346                for x in range[0]..=range[1] {
347                    counts[y * side + x + 1] += 1;
348                }
349            }
350        }
351        for index in 1..counts.len() {
352            counts[index] += counts[index - 1];
353        }
354        // Long edges cover many cells; past a budget the original scan is cheaper.
355        if counts[side * side] as usize > 64 * count + 4096 {
356            band.usable = false;
357            return band;
358        }
359        let mut cursor = counts.clone();
360        band.items = vec![0u32; counts[side * side] as usize];
361        for (edge, range) in ranges.iter().enumerate() {
362            for y in range[2]..=range[3] {
363                for x in range[0]..=range[1] {
364                    let slot = &mut cursor[y * side + x];
365                    band.items[*slot as usize] = edge as u32;
366                    *slot += 1;
367                }
368            }
369        }
370        band.starts = counts;
371        band
372    }
373    fn column(&self, x: f64) -> usize {
374        (((x - self.origin[0]) / self.cell[0]).floor().max(0.0) as usize).min(self.side - 1)
375    }
376    fn row(&self, y: f64) -> usize {
377        (((y - self.origin[1]) / self.cell[1]).floor().max(0.0) as usize).min(self.side - 1)
378    }
379    fn classify(&self, point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
380        if !self.usable || !point.x.is_finite() || !point.y.is_finite() {
381            return point_in_polygon_class(point, polygon, tolerance);
382        }
383        let cell = self.row(point.y) * self.side + self.column(point.x);
384        let count = polygon.len();
385        for &edge in &self.items[self.starts[cell] as usize..self.starts[cell + 1] as usize] {
386            let edge = edge as usize;
387            if point.distance_to_segment(polygon[edge], polygon[(edge + 1) % count], 1e-300) <= tolerance {
388                return PolygonClass::Boundary;
389            }
390        }
391        if crate::polygon::parity_inside([point.x, point.y], count, |i| [polygon[i].x, polygon[i].y]) {
392            PolygonClass::Inside
393        } else {
394            PolygonClass::Outside
395        }
396    }
397}
398
399fn outside_reject_box(point: Vec2, reject: &[f64; 5]) -> bool {
400    let reach = reject[4] + 64.0 * f64::EPSILON * point.x.abs().max(point.y.abs());
401    // NaN `reach` (or a NaN point) makes every comparison false: never reject.
402    point.x < reject[0] - reach || point.y < reject[1] - reach || point.x > reject[2] + reach || point.y > reject[3] + reach
403}
404
405/// `BREP_ARRANGE_DIGON_ORDER` (default on; `=0` restores insertion order for
406/// equal angles): see DIGON ORDER in [`arrange_segments`].
407fn digon_order_enabled() -> bool {
408    switch!("BREP_ARRANGE_DIGON_ORDER", true)
409}
410
411fn hole_box_reject_enabled() -> bool {
412    switch!("BREP_ARRANGE_HOLE_BOX", true)
413}
414
415
416fn point_in_polygon_class(point: Vec2, polygon: &[Vec2], tolerance: f64) -> PolygonClass {
417    crate::polygon::classify(point, polygon, tolerance, 1e-300)
418}
419
420pub fn point_in_polygon(point: Vec2, polygon: &[Vec2], tolerance: f64) -> &'static str {
421    match point_in_polygon_class(point, polygon, tolerance) {
422        PolygonClass::Inside => "in",
423        PolygonClass::Outside => "out",
424        PolygonClass::Boundary => "boundary",
425    }
426}
427
428// Arrangement decisions read endpoints and topology, never parent tags. Keep
429// the immutable source segment borrowed until a retained cycle needs an owned
430// output. The eager arm preserves the original allocation path for A/B.
431struct PieceInput<'a> {
432    a: Vec2,
433    b: Vec2,
434    parent: std::borrow::Cow<'a, Segment2>,
435}
436impl PieceInput<'_> {
437    fn materialize(&self, forward: bool) -> CycleUse {
438        CycleUse { piece: ArrangementPiece { a: self.a, b: self.b, parent: self.parent.as_ref().clone() }, forward }
439    }
440}
441
442#[derive(Clone)]
443enum CycleUses {
444    Eager(Vec<CycleUse>),
445    Deferred(Vec<usize>),
446}
447impl CycleUses {
448    fn push(&mut self, half: usize, pieces: &[PieceInput<'_>]) {
449        match self {
450            Self::Eager(uses) => uses.push(pieces[half >> 1].materialize(half % 2 == 0)),
451            Self::Deferred(halves) => halves.push(half),
452        }
453    }
454    fn into_uses(self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
455        match self {
456            Self::Eager(uses) => uses,
457            Self::Deferred(halves) => halves.into_iter().map(|h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
458        }
459    }
460    fn copy_uses(&self, pieces: &[PieceInput<'_>]) -> Vec<CycleUse> {
461        match self {
462            Self::Eager(uses) => uses.clone(),
463            Self::Deferred(halves) => halves.iter().map(|&h| pieces[h >> 1].materialize(h % 2 == 0)).collect(),
464        }
465    }
466}
467
468#[derive(Clone)]
469struct Cycle {
470    uses: CycleUses,
471    area: f64,
472    node_indices: Vec<usize>,
473}
474
475/// Visit a conservative subset of pairs in original input order. The narrow
476/// phase remains authoritative, including its endpoint tolerance and rounding.
477fn visit_segment_pairs(segments: &[Segment2], tolerance: f64, mut visit: impl FnMut(usize, usize)) {
478    let all_pairs = |visit: &mut dyn FnMut(usize, usize)| {
479        for first in 0..segments.len() {
480            for second in first + 1..segments.len() {
481                visit(first, second);
482            }
483        }
484    };
485    if segments.len() <= 32
486        || segments.len() > u32::MAX as usize
487        || !tolerance.is_finite()
488        || tolerance < 0.0
489        || tolerance > 1e100
490    {
491        all_pairs(&mut visit);
492        return;
493    }
494    let mut scale = 0.0f64;
495    let mut boxes = Vec::with_capacity(segments.len());
496    let mut extent = Aabb::empty();
497    for segment in segments {
498        let coordinates = [segment.a.x, segment.a.y, segment.b.x, segment.b.y];
499        let length = segment.a.distance(segment.b);
500        // Keep the legacy scan for numeric extremes: underflow/overflow or NaN
501        // in the narrow phase need not behave like geometric intersection.
502        if coordinates
503            .iter()
504            .any(|v| !v.is_finite() || v.abs() > 1e100)
505            || !(1e-100..=1e100).contains(&length)
506        {
507            all_pairs(&mut visit);
508            return;
509        }
510        for coordinate in coordinates {
511            scale = scale.max(coordinate.abs());
512        }
513        let bounds = Aabb {
514            minimum: Vec3::new(
515                segment.a.x.min(segment.b.x),
516                segment.a.y.min(segment.b.y),
517                0.0,
518            ),
519            maximum: Vec3::new(
520                segment.a.x.max(segment.b.x),
521                segment.a.y.max(segment.b.y),
522                0.0,
523            ),
524        };
525        extent.include(bounds);
526        boxes.push(bounds);
527    }
528    // Each accepted parameter may extend its segment by up to tolerance.
529    // Cross-product roundoff is amplified by up to 1/PARALLEL_THRESHOLD when
530    // solving the parameters. Bound it using the global coordinate magnitude
531    // (including translation), with headroom for subtraction, products, length
532    // and division rounding. This deliberately admits extra pairs near parallel
533    // lines instead of treating exact endpoint boxes as a bound on an inexact
534    // solve. The numeric guards above keep these operations in the normal range.
535    let padding = 2.0 * tolerance + 128.0 * f64::EPSILON / PARALLEL_THRESHOLD * scale;
536    // A large translation or tolerance can swallow the entire arrangement.
537    // An index cannot reject anything then, so avoid its query/sort overhead.
538    if padding >= extent.diagonal() {
539        all_pairs(&mut visit);
540        return;
541    }
542    let direction_tiers = direction_index_on();
543    // Row 29: the direction tiers' small-padding query is answered by a
544    // one-axis sweep instead of the tree, which is then not built (`None`
545    // from the sweep keeps the tree).
546    let small_padding = 2.0 * tolerance + 128.0 * f64::EPSILON / DIRECTION_SINE * scale;
547    let swept = if direction_tiers && arrange_sweep_on() { swept_pairs(&boxes, small_padding) } else { None };
548    let tree = swept.is_none().then(|| Bvh::build(&boxes));
549    let mut candidates = Vec::new();
550    if direction_tiers {
551        // DIRECTION TIERS (lane O, 2026-10-28). The padding above is what a
552        // pair as near-parallel as the narrow phase admits (`sin θ` down to
553        // PARALLEL_THRESHOLD) can need, and on a face whose uv sit far from
554        // the origin it reaches across most of the arrangement: the filleted
555        // box's outward offset sends a 252-segment quarter-arc chain through
556        // here twice per attempt and the index visited nearly all 37 000
557        // pairs (0.7 ms a face). The same rounding model bounds a pair whose
558        // directions differ by `sin θ ≥ s` with the padding at `s` in place of
559        // the threshold. So every pair is visited under that small padding,
560        // and a pair whose directions lie within one bucket of each other
561        // (width `2s`, wrapping at π) — the only pairs that can be nearer
562        // parallel than `s` — under the full padding as before. Visit order
563        // and the narrow phase are unchanged; the visited set still contains
564        // every pair the full padding could accept.
565        let width = 2.0 * DIRECTION_SINE;
566        let bucket_count = ((std::f64::consts::PI / width).ceil() as usize).max(1);
567        let mut buckets: FxHashMap<usize, Vec<usize>> = FxHashMap::default();
568        let bucket_of: Vec<usize> = segments
569            .iter()
570            .map(|segment| {
571                let angle = (segment.b.y - segment.a.y).atan2(segment.b.x - segment.a.x).rem_euclid(std::f64::consts::PI);
572                ((angle / width) as usize).min(bucket_count - 1)
573            })
574            .collect();
575        for (index, bucket) in bucket_of.iter().enumerate() {
576            buckets.entry(*bucket).or_default().push(index);
577        }
578        let near = |a: &Aabb, b: &Aabb| {
579            a.minimum.x - padding <= b.maximum.x
580                && b.minimum.x - padding <= a.maximum.x
581                && a.minimum.y - padding <= b.maximum.y
582                && b.minimum.y - padding <= a.maximum.y
583        };
584        for (first, &bounds) in boxes.iter().enumerate() {
585            candidates.clear();
586            match (&swept, &tree) {
587                (Some(lists), _) => candidates.extend_from_slice(&lists[first]),
588                (None, Some(tree)) => tree.overlapping(bounds, small_padding, &mut candidates),
589                (None, None) => unreachable!("the tree is built whenever the sweep is not"),
590            }
591            let bucket = bucket_of[first];
592            for neighbour in [(bucket + bucket_count - 1) % bucket_count, bucket, (bucket + 1) % bucket_count] {
593                if let Some(members) = buckets.get(&neighbour) {
594                    candidates.extend(members.iter().copied().filter(|&second| second > first && near(&bounds, &boxes[second])));
595                }
596                if bucket_count < 3 {
597                    break;
598                }
599            }
600            candidates.retain(|&second| second > first);
601            candidates.sort_unstable();
602            candidates.dedup();
603            for &second in &candidates {
604                visit(first, second);
605            }
606        }
607        return;
608    }
609    let Some(tree) = tree else { unreachable!("the sweep runs only under the direction tiers") };
610    for (first, &bounds) in boxes.iter().enumerate() {
611        candidates.clear();
612        tree.overlapping(bounds, padding, &mut candidates);
613        candidates.retain(|&second| second > first);
614        candidates.sort_unstable();
615        for &second in &candidates {
616            visit(first, second);
617        }
618    }
619}
620
621/// The direction sine above which [`visit_segment_pairs`] pads a pair with
622/// the small padding (see DIRECTION TIERS there).
623const DIRECTION_SINE: f64 = 1e-3;
624
625/// Lane O row 29 (2026-10-30, `BREP_ARRANGE_SWEEP`, default on since batch 12;
626/// `0`/`off` restores the tree): for each box `first`, every `second > first` whose box passes
627/// the tree's own leaf test `boxes[second].intersects(boxes[first], padding)`
628/// — the set [`Bvh::overlapping`] returns past `second > first`, since a node
629/// box contains its items' boxes — in ascending order. The candidates come
630/// from a sweep over the boxes sorted by their minimum on one axis, each
631/// scanning forward while the next minimum is within its maximum plus twice
632/// the padding: a pair the leaf test admits lies within the padding plus one
633/// rounding of either subtraction there, and the padding (at least
634/// 128 ε / DIRECTION_SINE of the largest coordinate) exceeds that rounding.
635///
636/// The axis is the one whose sweep windows (counted by binary search before
637/// any test runs) are fewer in total; when even those exceed 32 a box, the
638/// boxes overlap along both axes and `None` hands the query back to the tree,
639/// which prunes on both at once (a guard: of the D1, inward opposed and
640/// outward 3-adjacent shell cases probed, only D1 reaches the sweep, and
641/// never the fallback). D1's two 272-segment faces spent 0.38 ms a run
642/// building and querying the tree for 570 narrow-phase pairs that cost
643/// 0.04 ms.
644fn swept_pairs(boxes: &[Aabb], padding: f64) -> Option<Vec<Vec<usize>>> {
645    let reach = 2.0 * padding;
646    let low = |index: usize, axis: usize| if axis == 0 { boxes[index].minimum.x } else { boxes[index].minimum.y };
647    let high = |index: usize, axis: usize| if axis == 0 { boxes[index].maximum.x } else { boxes[index].maximum.y };
648    let mut best: Option<(usize, Vec<usize>, usize)> = None;
649    for axis in [0, 1] {
650        let mut order: Vec<usize> = (0..boxes.len()).collect();
651        order.sort_by(|&a, &b| low(a, axis).total_cmp(&low(b, axis)));
652        let lows: Vec<f64> = order.iter().map(|&index| low(index, axis)).collect();
653        let windows: usize = order
654            .iter()
655            .enumerate()
656            .map(|(position, &a)| {
657                let limit = high(a, axis) + reach;
658                lows.partition_point(|&value| value <= limit).saturating_sub(position + 1)
659            })
660            .sum();
661        if best.as_ref().is_none_or(|(least, _, _)| windows < *least) {
662            best = Some((windows, order, axis));
663        }
664    }
665    let (windows, order, axis) = best?;
666    if windows > 32 * boxes.len() {
667        return None;
668    }
669    let mut lists = vec![Vec::new(); boxes.len()];
670    for (position, &a) in order.iter().enumerate() {
671        let limit = high(a, axis) + reach;
672        for &b in &order[position + 1..] {
673            if low(b, axis) > limit {
674                break;
675            }
676            let (first, second) = if a < b { (a, b) } else { (b, a) };
677            if boxes[second].intersects(boxes[first], padding) {
678                lists[first].push(second);
679            }
680        }
681    }
682    for list in &mut lists {
683        list.sort_unstable();
684    }
685    Some(lists)
686}
687
688/// Row 29's switch ([`swept_pairs`]), read once.
689fn arrange_sweep_on() -> bool {
690    switch!("BREP_ARRANGE_SWEEP", true)
691}
692
693
694/// The direction tiers of [`visit_segment_pairs`], on unless
695/// `BREP_ARRANGE_DIRECTION_INDEX` is `0`/`off` (the A/B lever). Read once.
696fn direction_index_on() -> bool {
697    switch!("BREP_ARRANGE_DIRECTION_INDEX", true)
698}
699
700pub fn arrange_segments(
701    segments: &[Segment2],
702    tolerance: f64,
703) -> Result<Vec<ArrangementRegion>, String> {
704    arrange_segments_impl(segments, tolerance, true, true, None)
705}
706
707/// One lens pair an arrangement keeps apart: chains `first` and `second`,
708/// which share both ends. `ends` holds, for each shared end, its point, the
709/// radius within which the two meet there (their ends' match), and the
710/// radius of the zone beside it where their polylines stand within the
711/// tolerance of each other (out to the first sample parting by more).
712pub struct LensPair {
713    pub first: u64,
714    pub second: u64,
715    pub ends: [(Vec2, f64, f64); 2],
716}
717
718impl LensPair {
719    fn joins(&self, a: u64, b: u64) -> bool {
720        a != b && ((self.first == a && self.second == b) || (self.first == b && self.second == a))
721    }
722
723    /// Whether `point` stands in one of the pair's end zones, off the end
724    /// itself: there the two never cross nor share a node.
725    fn suppressed(&self, point: Vec2) -> bool {
726        self.ends.iter().any(|&(end, meet, zone)| {
727            let distance = end.distance(point);
728            distance > meet && distance <= zone
729        })
730    }
731}
732
733/// Lens pairs kept apart: `chain_of[i]` is segment `i`'s chain.
734pub struct LensApart<'a> {
735    pub chain_of: &'a [u64],
736    pub pairs: &'a [LensPair],
737}
738
739impl LensApart<'_> {
740    /// Whether a crossing or a shared node of chains `a` and `b` at `point`
741    /// is suppressed: some pair of the two holds it in an end zone.
742    fn suppressed(&self, a: u64, b: u64, point: Vec2) -> bool {
743        self.pairs.iter().any(|pair| pair.joins(a, b) && pair.suppressed(point))
744    }
745}
746
747/// The representative of each node once the `bridges` (pairs of nodes within
748/// the tolerance, in the order found) are merged: union-find to the lower
749/// index, each group keeping the box of its members, and a union declined
750/// when any corner of the combined box would stand farther than twice the
751/// tolerance from the new representative. A chain of nodes each beside the
752/// next never grows into a group spread over more than that, whatever order
753/// the bridges come in (root to root distances alone allow 2.7 tolerances).
754fn merge_bridged(points: &[Vec2], bridges: &[(usize, usize)], tolerance: f64) -> Vec<usize> {
755    let mut root: Vec<usize> = (0..points.len()).collect();
756    let mut boxes: Vec<[f64; 4]> = points.iter().map(|p| [p.x, p.y, p.x, p.y]).collect();
757    fn find(root: &mut [usize], mut index: usize) -> usize {
758        while root[index] != index {
759            root[index] = root[root[index]];
760            index = root[index];
761        }
762        index
763    }
764    let reach = 2.0 * tolerance;
765    for &(first, second) in bridges {
766        let (a, b) = (find(&mut root, first), find(&mut root, second));
767        if a == b {
768            continue;
769        }
770        let (keep, gone) = (a.min(b), a.max(b));
771        let joined = [
772            boxes[keep][0].min(boxes[gone][0]),
773            boxes[keep][1].min(boxes[gone][1]),
774            boxes[keep][2].max(boxes[gone][2]),
775            boxes[keep][3].max(boxes[gone][3]),
776        ];
777        let centre = points[keep];
778        let far_x = (joined[0] - centre.x).abs().max((joined[2] - centre.x).abs());
779        let far_y = (joined[1] - centre.y).abs().max((joined[3] - centre.y).abs());
780        if far_x.hypot(far_y) > reach {
781            continue;
782        }
783        root[gone] = keep;
784        boxes[keep] = joined;
785    }
786    (0..points.len()).map(|index| find(&mut root, index)).collect()
787}
788
789/// [`arrange_segments`] with lens pairs kept apart near their ends: two
790/// chains a hair apart between two shared ends (a cap's rim and a section
791/// 1e-6 inside it, sampled at the same stations) run within the tolerance of
792/// each other beside each end, where a plain arrangement nodes them together
793/// (two samples within the tolerance, or two chords crossing at a grazing
794/// angle) a chord away from the true crossing. In those end zones they meet
795/// only at the end; elsewhere they are arranged as ever.
796pub fn arrange_segments_lens_apart(
797    segments: &[Segment2],
798    tolerance: f64,
799    apart: &LensApart,
800) -> Result<Vec<ArrangementRegion>, String> {
801    if apart.chain_of.len() != segments.len() {
802        return Err("arrange_segments_lens_apart: one chain per segment".into());
803    }
804    arrange_segments_impl(segments, tolerance, true, true, Some(apart))
805}
806
807fn arrange_segments_impl(
808    segments: &[Segment2],
809    tolerance: f64,
810    indexed: bool,
811    indexed_nodes: bool,
812    apart: Option<&LensApart>,
813) -> Result<Vec<ArrangementRegion>, String> {
814
815    let defer_tags = switch!("BREP_ARRANGE_DEFER_TAGS", true);
816    let end_on_segment = switch!("BREP_ARRANGE_END_ON_SEGMENT", true);
817    let mut cuts = vec![Vec::<f64>::new(); segments.len()];
818    let mut intersect_pair = |first: usize, second: usize| {
819        if let Some(apart) = apart {
820            let (chain_a, chain_b) = (apart.chain_of[first], apart.chain_of[second]);
821            if apart.pairs.iter().any(|pair| pair.joins(chain_a, chain_b)) {
822                // A crossing (or an end resting on the other's segment) in
823                // an end zone of the pair is not one.
824                let crossing = segment_intersection(segments[first].a, segments[first].b, segments[second].a, segments[second].b, tolerance)
825                    .map(|[t, _]| interpolate(segments[first].a, segments[first].b, t));
826                // Without a crossing, the ends resting on the other segment
827                // (where `end_on_segment_parameters` would node them).
828                let (one, two) = (&segments[first], &segments[second]);
829                let resting = [(one.a, two), (one.b, two), (two.a, one), (two.b, one)];
830                if crossing.is_some_and(|point| apart.suppressed(chain_a, chain_b, point))
831                    || (crossing.is_none()
832                        && resting.iter().any(|&(point, bar)| point_segment_distance(point, bar.a, bar.b) <= tolerance && apart.suppressed(chain_a, chain_b, point)))
833                {
834                    return;
835                }
836            }
837        }
838        let Some([first_parameter, second_parameter]) = segment_intersection(
839            segments[first].a,
840            segments[first].b,
841            segments[second].a,
842            segments[second].b,
843            tolerance,
844        ) else {
845            if end_on_segment {
846                for (end, bar) in [(first, second), (second, first)] {
847                    for (point, parameter) in end_on_segment_parameters(&segments[end], &segments[bar], tolerance) {
848                        let shared = segments.iter().enumerate().any(|(index, other)| {
849                            index != end && (other.a.distance(point) <= tolerance || other.b.distance(point) <= tolerance)
850                        });
851                        if !shared {
852                            cuts[bar].push(parameter);
853                        }
854                    }
855                }
856            }
857            return;
858        };
859        let first_tolerance = tolerance_parameter(&segments[first], tolerance);
860        let second_tolerance = tolerance_parameter(&segments[second], tolerance);
861        if first_parameter > first_tolerance && first_parameter < 1.0 - first_tolerance {
862            cuts[first].push(first_parameter);
863        }
864        if second_parameter > second_tolerance && second_parameter < 1.0 - second_tolerance {
865            cuts[second].push(second_parameter);
866        }
867    };
868    if indexed {
869        visit_segment_pairs(segments, tolerance, &mut intersect_pair);
870    } else {
871        for first in 0..segments.len() {
872            for second in first + 1..segments.len() {
873                intersect_pair(first, second);
874            }
875        }
876    }
877
878    let mut pieces = Vec::new();
879    let mut piece_chain: Vec<u64> = Vec::new();
880    for (index, segment) in segments.iter().enumerate() {
881        let mut parameters = vec![0.0];
882        cuts[index].sort_by(f64::total_cmp);
883        parameters.extend(cuts[index].iter().copied());
884        parameters.push(1.0);
885        let parameter_tolerance = tolerance_parameter(segment, tolerance);
886        let mut deduplicated: Vec<f64> = Vec::new();
887        for parameter in parameters {
888            if deduplicated
889                .last()
890                .is_none_or(|previous| parameter - *previous > parameter_tolerance)
891            {
892                deduplicated.push(parameter);
893            } else if parameter == 1.0 {
894                *deduplicated.last_mut().unwrap() = 1.0;
895            }
896        }
897        for pair in deduplicated.windows(2) {
898            let a = interpolate(segment.a, segment.b, pair[0]);
899            let b = interpolate(segment.a, segment.b, pair[1]);
900            if a.distance(b) <= tolerance {
901                continue;
902            }
903            pieces.push(PieceInput {
904                a,
905                b,
906                parent: if defer_tags { std::borrow::Cow::Borrowed(segment) } else { std::borrow::Cow::Owned(segment.clone()) },
907            });
908            if let Some(apart) = apart {
909                piece_chain.push(apart.chain_of[index]);
910            }
911        }
912    }
913
914    let mut nodes: Vec<Node> = Vec::new();
915    let mut lookup = NodeLookup::new(tolerance, indexed_nodes && pieces.len() > 64);
916    let mut piece_start = Vec::with_capacity(pieces.len());
917    let mut piece_end = Vec::with_capacity(pieces.len());
918    if let Some(apart) = apart {
919        // Each node's chains: a lens pair's two chains share none in an end
920        // zone.
921        let mut node_chains: Vec<Vec<u64>> = Vec::new();
922        // The pieces of chains in no pair are noded first: a paired chain
923        // then finds a third chain's junction already there and joins it,
924        // whatever order the segments came in.
925        let paired = |chain: u64| apart.pairs.iter().any(|pair| pair.first == chain || pair.second == chain);
926        let mut order: Vec<usize> = (0..pieces.len()).filter(|&index| !paired(piece_chain[index])).collect();
927        order.extend((0..pieces.len()).filter(|&index| paired(piece_chain[index])));
928        piece_start.resize(pieces.len(), 0);
929        piece_end.resize(pieces.len(), 0);
930        for index in order {
931            let piece = &pieces[index];
932            let chain = piece_chain[index];
933            let mut ends = [0usize; 2];
934            for (slot, point) in [piece.a, piece.b].into_iter().enumerate() {
935                // Never one node with a chain this one pairs with, where
936                // that pair holds the point in an end zone: a node every
937                // other chain of which is such a partner is refused. A node
938                // a third chain holds too (a section across the lens near
939                // its end) is that chain's junction with both, and joined.
940                let node = lookup.find_or_insert_where(point, &mut nodes, |node| {
941                    let Some(chains) = node_chains.get(node) else { return true };
942                    let others: Vec<u64> = chains.iter().copied().filter(|&other| other != chain).collect();
943                    others.is_empty() || !others.iter().all(|&other| apart.suppressed(other, chain, point))
944                });
945                if node_chains.len() < nodes.len() {
946                    node_chains.resize(nodes.len(), Vec::new());
947                }
948                if !node_chains[node].contains(&chain) {
949                    node_chains[node].push(chain);
950                }
951                ends[slot] = node;
952            }
953            piece_start[index] = ends[0];
954            piece_end[index] = ends[1];
955        }
956        // Whatever order the chains were noded in, two nodes within the
957        // tolerance whose chains include two not kept apart there (a third
958        // chain's junction beside one arc's node and the other's) are one:
959        // the merge is closed over chains bridging nodes, so a paired
960        // section noded after both arcs still joins them. A group's members
961        // stand within twice the tolerance of its first node
962        // ([`merge_bridged`]).
963        let width = 2.0 * tolerance;
964        let mut cells: FxHashMap<[i64; 2], Vec<usize>> = FxHashMap::default();
965        let cell = |point: Vec2| -> Option<[i64; 2]> {
966            let q = [point.x / width, point.y / width];
967            q.iter().all(|v| v.is_finite() && v.abs() <= (1u64 << 48) as f64).then(|| q.map(|v| v.floor() as i64))
968        };
969        for (index, node) in nodes.iter().enumerate() {
970            if let Some(key) = cell(node.point) {
971                cells.entry(key).or_default().push(index);
972            }
973        }
974        let mut bridges: Vec<(usize, usize)> = Vec::new();
975        for index in 0..nodes.len() {
976            let Some([x, y]) = cell(nodes[index].point) else { continue };
977            for dx in -1..=1 {
978                for dy in -1..=1 {
979                    let Some(others) = cells.get(&[x + dx, y + dy]) else { continue };
980                    for &other in others {
981                        if other <= index || nodes[other].point.distance(nodes[index].point) > tolerance {
982                            continue;
983                        }
984                        let point = nodes[index].point;
985                        let bridged = node_chains.get(index).is_some_and(|mine| {
986                            node_chains.get(other).is_some_and(|theirs| {
987                                mine.iter().any(|&a| theirs.iter().any(|&b| a == b || !apart.suppressed(a, b, point)))
988                            })
989                        });
990                        if bridged {
991                            bridges.push((index, other));
992                        }
993                    }
994                }
995            }
996        }
997        let points: Vec<Vec2> = nodes.iter().map(|node| node.point).collect();
998        let root = merge_bridged(&points, &bridges, tolerance);
999        for index in 0..pieces.len() {
1000            piece_start[index] = root[piece_start[index]];
1001            piece_end[index] = root[piece_end[index]];
1002        }
1003    } else {
1004        for piece in &pieces {
1005            piece_start.push(lookup.find_or_insert(piece.a, &mut nodes));
1006            piece_end.push(lookup.find_or_insert(piece.b, &mut nodes));
1007        }
1008    }
1009
1010    let mut alive = vec![true; pieces.len()];
1011    loop {
1012        let mut pruned = false;
1013        let mut degree = vec![0usize; nodes.len()];
1014        for index in 0..pieces.len() {
1015            if !alive[index] {
1016                continue;
1017            }
1018            if piece_start[index] == piece_end[index] {
1019                alive[index] = false;
1020                pruned = true;
1021                continue;
1022            }
1023            degree[piece_start[index]] += 1;
1024            degree[piece_end[index]] += 1;
1025        }
1026        for index in 0..pieces.len() {
1027            if alive[index] && (degree[piece_start[index]] == 1 || degree[piece_end[index]] == 1) {
1028                alive[index] = false;
1029                pruned = true;
1030            }
1031        }
1032        if !pruned {
1033            break;
1034        }
1035    }
1036
1037    let half_tail = |half_edge: usize| {
1038        if half_edge % 2 == 0 {
1039            piece_start[half_edge >> 1]
1040        } else {
1041            piece_end[half_edge >> 1]
1042        }
1043    };
1044    let half_head = |half_edge: usize| {
1045        if half_edge % 2 == 0 {
1046            piece_end[half_edge >> 1]
1047        } else {
1048            piece_start[half_edge >> 1]
1049        }
1050    };
1051    for node in &mut nodes {
1052        node.outgoing.clear();
1053    }
1054    for index in 0..pieces.len() {
1055        if !alive[index] {
1056            continue;
1057        }
1058        nodes[piece_start[index]].outgoing.push(index * 2);
1059        nodes[piece_end[index]].outgoing.push(index * 2 + 1);
1060    }
1061    let angles: Vec<f64> = (0..pieces.len() * 2)
1062        .map(|half_edge| {
1063            let tail = nodes[half_tail(half_edge)].point;
1064            let head = nodes[half_head(half_edge)].point;
1065            (head.y - tail.y).atan2(head.x - tail.x)
1066        })
1067        .collect();
1068    // DIGON ORDER: two pieces joining the SAME two nodes (a cut lying along a
1069    // trim edge for its last stretch, merged onto the edge's nodes) leave
1070    // the same angle at both ends, and a sort by angle alone keeps them in
1071    // insertion order at BOTH nodes, which no planar embedding has: the walk
1072    // then crosses between the two sides of the pair and stitches the region
1073    // beside it into the outer cycle, so the region is lost (an offset
1074    // fillet's skin vanished at a miter corner, 2026-11-07). Equal
1075    // angles are ordered by piece index, reversed at the higher node, so the
1076    // pair bounds an empty digon and both neighbours close.
1077    let digon_order = digon_order_enabled();
1078    for node in &mut nodes {
1079        node.outgoing.sort_by(|a, b| {
1080            angles[*a].total_cmp(&angles[*b]).then_with(|| {
1081                if !digon_order {
1082                    return std::cmp::Ordering::Equal;
1083                }
1084                let rank = |half_edge: usize| {
1085                    let piece = (half_edge >> 1) as i64;
1086                    if half_tail(half_edge) < half_head(half_edge) {
1087                        piece
1088                    } else {
1089                        -piece
1090                    }
1091                };
1092                rank(*a).cmp(&rank(*b))
1093            })
1094        });
1095    }
1096
1097    let mut visited = rustc_hash::FxHashSet::default();
1098    let mut positive = Vec::new();
1099    let mut negative = Vec::new();
1100    for index in 0..pieces.len() {
1101        if !alive[index] {
1102            continue;
1103        }
1104        for start in [index * 2, index * 2 + 1] {
1105            if visited.contains(&start) {
1106                continue;
1107            }
1108            let mut uses = if defer_tags { CycleUses::Deferred(Vec::new()) } else { CycleUses::Eager(Vec::new()) };
1109            let mut node_indices = Vec::new();
1110            let mut area = 0.0;
1111            let mut half_edge = start;
1112            let mut guard = 0;
1113            loop {
1114                visited.insert(half_edge);
1115                uses.push(half_edge, &pieces);
1116                let tail_index = half_tail(half_edge);
1117                let head_index = half_head(half_edge);
1118                let tail = nodes[tail_index].point;
1119                let head = nodes[head_index].point;
1120                area += 0.5 * (tail.x * head.y - head.x * tail.y);
1121                node_indices.push(tail_index);
1122                let reverse = half_edge ^ 1;
1123                let outgoing = &nodes[head_index].outgoing;
1124                let reverse_index = outgoing
1125                    .iter()
1126                    .position(|candidate| *candidate == reverse)
1127                    .ok_or_else(|| "arrangeSegments: reverse half-edge missing".to_string())?;
1128                half_edge = outgoing[(reverse_index + outgoing.len() - 1) % outgoing.len()];
1129                guard += 1;
1130                if guard > pieces.len() * 4 + 8 {
1131                    return Err("arrangeSegments: face walk did not terminate".into());
1132                }
1133                if half_edge == start {
1134                    break;
1135                }
1136            }
1137            let cycle = Cycle {
1138                uses,
1139                area,
1140                node_indices,
1141            };
1142            if area > tolerance * tolerance {
1143                positive.push(cycle);
1144            } else if area < -tolerance * tolerance {
1145                negative.push(cycle);
1146            }
1147        }
1148    }
1149
1150    positive.sort_by(|a, b| a.area.total_cmp(&b.area));
1151    let mut regions: Vec<(ArrangementRegion, Vec<Vec2>)> = positive
1152        .into_iter()
1153        .map(|cycle| {
1154            let polygon = cycle
1155                .node_indices
1156                .iter()
1157                .map(|index| nodes[*index].point)
1158                .collect();
1159            (
1160                ArrangementRegion {
1161                    outer: cycle.uses.into_uses(&pieces),
1162                    holes: Vec::new(),
1163                    area: cycle.area,
1164                    outer_area: cycle.area,
1165                },
1166                polygon,
1167            )
1168        })
1169        .collect();
1170    let hole_boxes = hole_box_reject_enabled();
1171    let boxes: Vec<[f64; 5]> = if hole_boxes {
1172        regions.iter().map(|(_, polygon)| polygon_reject_box(polygon, tolerance)).collect()
1173    } else {
1174        Vec::new()
1175    };
1176    let mut bands: Vec<Option<BoundaryBand>> = (0..regions.len()).map(|_| None).collect();
1177    for cycle in negative {
1178        for (region_index, (region, polygon)) in regions.iter_mut().enumerate() {
1179            let mut inside = false;
1180            let mut on_boundary = false;
1181            for node_index in &cycle.node_indices {
1182                let point = nodes[*node_index].point;
1183                let class = if hole_boxes && outside_reject_box(point, &boxes[region_index]) {
1184                    PolygonClass::Outside
1185                } else if hole_boxes {
1186                    let band = bands[region_index].get_or_insert_with(|| BoundaryBand::new(polygon, tolerance));
1187                    band.classify(point, polygon, tolerance)
1188                } else {
1189                    point_in_polygon_class(point, polygon, tolerance)
1190                };
1191                match class {
1192                    PolygonClass::Boundary => {
1193                        on_boundary = true;
1194                        continue;
1195                    }
1196                    PolygonClass::Inside => {
1197                        inside = true;
1198                        on_boundary = false;
1199                        break;
1200                    }
1201                    PolygonClass::Outside => {
1202                        inside = false;
1203                        on_boundary = false;
1204                        break;
1205                    }
1206                }
1207            }
1208            if on_boundary {
1209                continue;
1210            }
1211            if inside {
1212                region.holes.push(cycle.uses.copy_uses(&pieces));
1213                region.area += cycle.area;
1214                break;
1215            }
1216        }
1217    }
1218    if crate::profile::profile_enabled() {
1219        let holes: usize = regions.iter().flat_map(|(r, _)| r.holes.iter()).map(Vec::len).sum();
1220        let returned: usize = holes + regions.iter().map(|(r, _)| r.outer.len()).sum::<usize>();
1221        let clones = if defer_tags { returned } else { pieces.len() + visited.len() + holes };
1222        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()));
1223    }
1224    Ok(regions.into_iter().map(|(region, _)| region).collect())
1225}
1226
1227
1228