Skip to main content

map_tile_toolkit/
polygon.rs

1//! Polygon slicing for [`Slicer`](crate::Slicer): [`Slicer::polygon`](crate::Slicer::polygon)
2//! yields every piece of a polygon in every tile it reaches, and
3//! [`Slicer::tile_polygon`](crate::Slicer::tile_polygon) its piece in one tile.
4//!
5//! A polygon inside one tile's inner box is yielded whole, and one smaller than a tile with few vertices
6//! (a building) by a walk over the few tiles it reaches, each given what
7//! [`Slicer::tile_polygon`](crate::Slicer::tile_polygon) gives it: no tile it reaches can be covered, and
8//! the sweep's setup would cost more than the clips. Both lend a lone ring that lies inside a tile's
9//! buffered box as it is, without clipping it (most of OSM's polygons are rings of 4 to 8 vertices).
10//! Any other polygon is sliced lazily by a row-by-row scanline:
11//!
12//! 1. **Prepare** - one pass over the polygon's rings, borrowing them in place: drop degenerate rings,
13//!    take the bounding box, and record the `y`-range of every run of [`CHUNK`] consecutive edges. A
14//!    polygon inside one tile's inner box is yielded whole, without the rest.
15//! 2. **Scan rows** top to bottom. A row looks only at the chunks whose `y`-range reaches it: their
16//!    edges that touch the row's buffered slab give the row's tile spans, and those crossing the row's
17//!    center line `y = cy` give its crossings. The center line carries the winding ray of every tile in
18//!    the row, so the crossings answer both remaining questions: how far an excursion outside a tile
19//!    winds around it (the detour's shape), and whether a ring with no edge in a tile contains it.
20//! 3. **Sweep** the row left to right over its edge tiles, closing every touching ring's arcs with
21//!    the clip's shared core ([`ClipScratch::close_ring`]), and yielding the covered spans between
22//!    them as [`FillRun`]s. A Fenwick tree over the row's crossings (in edge order) answers "signed
23//!    crossings right of this tile among edges `i..j`" in `O(log n)`.
24//!
25//! Nothing outside the current row is kept, and a piece is built in one reused buffer, in the global
26//! frame: [`Local`] moves it into the tile's frame as it is read.
27//!
28//! A piece is a valid polygon whenever the input is: the plain clip is kept if its outside segments
29//! (those with an endpoint outside the box) are planar, which [`planar`](crate::planar) checks, and
30//! otherwise rebuilt by the cheapest repair that is: [`repair`] runs the search for both slicers, each
31//! building the attempts its own way (from the sweep's hits, or by clipping the rings).
32//!
33//! Unclipped ([`ClipMode::Unclipped`]), the sweep is the same but builds nothing: each edge tile that
34//! would get a piece, and each tile of a fill run, gets the whole polygon, lent from the input.
35
36use core::cmp::Ordering;
37use core::iter;
38use core::ops::{Range, RangeInclusive};
39
40use geo_types::Coord;
41
42use crate::TileError;
43use crate::clip_polygon::{
44    ClipScratch, Closed, PieceBuf, Probe, RingClip, RingPlan, arcs_points, clip_ring, clip_ring_planned, convex_hull,
45    fill_box, keep_edge, lane_bounds, push_distinct, ring_meets_box, scan_arcs,
46};
47use crate::clip_polyline::to_local;
48use crate::geom::{crossing_x_ceil, ring_orientation};
49use crate::grid::{Grid, Seg, ring_within};
50use crate::planar::{PAIR_BUDGET, PlanarScratch, Verdict, is_planar};
51use crate::slicer::{ClipMode, Local};
52use crate::tile::TileId;
53use crate::vertex::{PolyVertex, Vertex};
54
55/// Edges per chunk of the row index: a chunk's `y`-range decides which rows look at its edges.
56const CHUNK: usize = 32;
57
58/// How many tiles of one row an edge must touch to be kept as a single [`Span`] for the row rather
59/// than one [`Hit`] per tile.
60const LONG_EDGE: i64 = 4;
61
62/// A horizontal run of tiles lying **entirely inside** the polygon: row `y`, columns `x.start..x.end`.
63///
64/// No ring edge touches these tiles' buffered boxes, so each is uniformly covered: in each of them,
65/// [`Slicer::tile_polygon`](crate::Slicer::tile_polygon) yields this polygon as a single
66/// all-synthetic box ring around the buffered box, which [`PolygonSlices::fill_ring`] (or
67/// [`Slicer::fill_ring`](crate::Slicer::fill_ring)) returns - the same tile-local ring for every tile
68/// of the run. Runs are maximal, and never overlap the polygon's edge tiles.
69#[derive(Debug, Clone, PartialEq, Eq, Hash)]
70#[non_exhaustive]
71pub struct FillRun {
72    /// The tile row.
73    pub y: i32,
74    /// The tile columns, end-exclusive.
75    pub x: Range<i32>,
76    /// The polygon's exterior winding, which its fill ring follows.
77    orient: Ordering,
78}
79
80/// One slice of a polygon.
81#[derive(Debug)]
82pub enum PolygonSlice<'a, V, R> {
83    /// One polygon's piece in one tile.
84    Piece(PolygonPiece<'a, V, R>),
85    /// Tiles a polygon covers entirely, whose content is [`PolygonSlices::fill_ring`] in each.
86    Run(FillRun),
87}
88
89/// One polygon's rings in one tile: exterior first, then its holes that reach the tile (all of them,
90/// and each whole, when unclipped).
91#[derive(Debug)]
92pub struct PolygonPiece<'a, V, R> {
93    tile: TileId,
94    rings: PieceRings<'a, V, R>,
95}
96
97#[derive(Debug)]
98enum PieceRings<'a, V, R> {
99    /// Clipped rings in the piece buffer (global, each closed), ending at `ends`, and the tile
100    /// origin.
101    Built {
102        verts: &'a [V],
103        ends: &'a [u32],
104        origin: Coord<i32>,
105    },
106    /// The whole polygon - lying in the tile, or unclipped: its kept rings, lent from the input (or
107    /// the copy of a ring that had duplicate vertices).
108    Whole {
109        rings: &'a [RingInfo],
110        input: &'a [R],
111        copies: &'a [V],
112        origin: Coord<i32>,
113    },
114}
115
116// Borrowed views: `Clone`/`Copy` without requiring them of the vertex or ring types.
117impl<V, R> Clone for PieceRings<'_, V, R> {
118    fn clone(&self) -> Self {
119        *self
120    }
121}
122impl<V, R> Copy for PieceRings<'_, V, R> {}
123impl<V, R> Clone for PolygonPiece<'_, V, R> {
124    fn clone(&self) -> Self {
125        *self
126    }
127}
128impl<V, R> Copy for PolygonPiece<'_, V, R> {}
129
130impl<'a, V: Vertex, R: AsRef<[V]>> PolygonPiece<'a, V, R> {
131    /// The tile this piece belongs to.
132    #[must_use]
133    pub fn tile(&self) -> TileId {
134        self.tile
135    }
136
137    /// The piece's rings, exterior first, each closed and in the tile's local frame.
138    pub fn rings(&self) -> impl Iterator<Item = Local<'a, V>> + use<'a, V, R> {
139        let rings = self.rings;
140        let n = match rings {
141            PieceRings::Built { ends, .. } => ends.len(),
142            PieceRings::Whole { rings, .. } => rings.len(),
143        };
144        (0..n).map(move |i| match rings {
145            PieceRings::Built { verts, ends, origin } => {
146                let start = i.checked_sub(1).map_or(0, |p| ends[p] as usize);
147                Local::ring(&verts[start..ends[i] as usize], origin, true)
148            }
149            PieceRings::Whole {
150                rings,
151                input,
152                copies,
153                origin,
154            } => Local::ring(rings[i].pts(input, copies), origin, false),
155        })
156    }
157}
158
159/// Where one kept ring's distinct vertices are.
160#[derive(Debug, Clone, Copy)]
161enum Src {
162    /// The first `len` vertices of the input ring.
163    Input,
164    /// `copies[start..start + len]`, the ring with its duplicate vertices dropped.
165    Copy(usize),
166}
167
168/// One kept ring (at least three distinct vertices) of the polygon being sliced: ring 0 is its
169/// exterior. Edge `i` runs from vertex `i` to vertex `(i + 1) % len`, and is edge `edge0 + i` of the
170/// polygon.
171#[derive(Debug, Clone, Copy)]
172struct RingInfo {
173    input: u32,
174    src: Src,
175    len: u32,
176    edge0: u32,
177}
178
179impl RingInfo {
180    fn pts<'a, V, R: AsRef<[V]>>(&self, input: &'a [R], copies: &'a [V]) -> &'a [V] {
181        let len = self.len as usize;
182        match self.src {
183            Src::Input => &input[self.input as usize].as_ref()[..len],
184            Src::Copy(start) => &copies[start..start + len],
185        }
186    }
187}
188
189/// [`CHUNK`] consecutive edges of one ring, and the tile rows their buffered `y`-range reaches.
190#[derive(Debug, Clone, Copy)]
191struct Chunk {
192    ring: u32,
193    first: u32,
194    count: u32,
195    rows: (i64, i64),
196}
197
198/// A ring edge touching tile `tx` of the current row. An edge touching fewer than [`LONG_EDGE`]
199/// tiles there has one hit per tile, so a tile's hits are one contiguous run, used as is.
200#[derive(Debug, Clone, Copy)]
201struct Hit {
202    tx: i32,
203    edge: u32,
204    ring: u32,
205}
206
207/// A long edge touching tiles `first..=last` of the current row: one entry for the row, so a row
208/// costs memory per edge, never per tile, however far an edge runs along it.
209#[derive(Debug, Clone, Copy)]
210struct Span {
211    first: i32,
212    last: i32,
213    edge: u32,
214    ring: u32,
215}
216
217/// A ring edge crossing the current row's center line, the line of every winding ray in that row
218/// (half-open in `y`, so each crossing is counted once). The crossing lies right of tile `tx`'s
219/// buffered box - on its winding ray - iff `tx <= right_of`.
220#[derive(Debug, Clone, Copy)]
221struct Crossing {
222    edge: u32,
223    ring: u32,
224    up: bool,
225    right_of: i64,
226}
227
228impl Crossing {
229    fn sign(self) -> i64 {
230        if self.up { 1 } else { -1 }
231    }
232}
233
234/// Row `ty`'s center line: the midpoint of its buffered box `[ty·e - b, ty·e + e - 1 + b]`, rounded
235/// toward zero, as the clip computes it with `midpoint` - in closed form: the buffer cancels, and the
236/// sum `2·ty·e + e - 1` is negative exactly when `ty < 0`, where rounding toward zero rounds up.
237fn row_center(ty: i64, extent: i64) -> i64 {
238    ty * extent + if ty < 0 { extent / 2 } else { (extent - 1) / 2 }
239}
240
241/// Rebuild `tree` as a Fenwick (binary indexed) tree over `values`, in `O(n)`.
242fn fenwick_build(tree: &mut Vec<i64>, values: impl Iterator<Item = i64>) {
243    tree.clear();
244    tree.extend(values);
245    for i in 0..tree.len() {
246        let parent = i | (i + 1);
247        if parent < tree.len() {
248            tree[parent] += tree[i];
249        }
250    }
251}
252
253/// Add `delta` at position `i`.
254fn fenwick_add(tree: &mut [i64], mut i: usize, delta: i64) {
255    while i < tree.len() {
256        tree[i] += delta;
257        i |= i + 1;
258    }
259}
260
261/// Sum of the first `end` positions.
262fn fenwick_prefix(tree: &[i64], mut end: usize) -> i64 {
263    let mut sum = 0;
264    while end > 0 {
265        sum += tree[end - 1];
266        end &= end - 1;
267    }
268    sum
269}
270
271/// Sort one row's `hits` by `(tx, edge)`. They arrive in ascending edge order, so a stable counting
272/// sort by column finishes the job in `O(n + columns)`; a column range much wider than the hits are
273/// many falls back to a comparison sort. `tmp` and `counts` are reused scratch.
274fn sort_hits(hits: &mut [Hit], tmp: &mut Vec<Hit>, counts: &mut Vec<usize>) {
275    let Some(head) = hits.first() else {
276        return;
277    };
278    let (lo, hi) = hits
279        .iter()
280        .fold((head.tx, head.tx), |(lo, hi), h| (lo.min(h.tx), hi.max(h.tx)));
281    let columns = hi.abs_diff(lo) as usize + 1;
282    if columns == 1 {
283        // One column: already in edge order.
284    } else if hits.len() < 16 || columns > hits.len().saturating_mul(4) {
285        hits.sort_unstable_by_key(|h| (h.tx, h.edge));
286    } else {
287        counts.clear();
288        counts.resize(columns, 0);
289        for h in hits.iter() {
290            counts[h.tx.abs_diff(lo) as usize] += 1;
291        }
292        // Exclusive prefix sums: where each column starts.
293        let mut start = 0;
294        for c in counts.iter_mut() {
295            (*c, start) = (start, start + *c);
296        }
297        tmp.clear();
298        tmp.extend_from_slice(hits);
299        for h in tmp.iter() {
300            let at = &mut counts[h.tx.abs_diff(lo) as usize];
301            hits[*at] = *h;
302            *at += 1;
303        }
304    }
305    debug_assert!(hits.is_sorted_by_key(|h| (h.tx, h.edge)));
306}
307
308/// Check that freshly written vertices fit the tile-local frame of `origin`, as [`Local`] lends them.
309fn check_local<V: Vertex>(verts: &[V], origin: Coord<i32>) -> Result<(), TileError> {
310    for &v in verts {
311        to_local(v, origin)?;
312    }
313    Ok(())
314}
315
316/// Restore edge order to `spans`, whose first `kept` are in edge order and the rest were appended (in
317/// first-column order, so in edge order too when they all start in the same column): sort the
318/// appended part only if needed, then merge the two in one pass through `tmp`.
319fn merge_by_edge<T: Copy>(spans: &mut Vec<T>, kept: usize, tmp: &mut Vec<T>, edge: impl Fn(&T) -> u32) {
320    let added = &mut spans[kept..];
321    if !added.is_sorted_by_key(&edge) {
322        added.sort_unstable_by_key(&edge);
323    }
324    if kept == 0 || kept == spans.len() || edge(&spans[kept - 1]) < edge(&spans[kept]) {
325        return;
326    }
327    tmp.clear();
328    let (old, new) = spans.split_at(kept);
329    let (mut i, mut j) = (0, 0);
330    while i < old.len() && j < new.len() {
331        if edge(&old[i]) < edge(&new[j]) {
332            tmp.push(old[i]);
333            i += 1;
334        } else {
335            tmp.push(new[j]);
336            j += 1;
337        }
338    }
339    tmp.extend_from_slice(&old[i..]);
340    tmp.extend_from_slice(&new[j..]);
341    core::mem::swap(spans, tmp);
342}
343
344/// `hits` (the spans covering one tile, in edge order, so each ring's are contiguous) split into runs
345/// of the same ring.
346fn ring_groups(mut hits: &[Hit]) -> impl Iterator<Item = &[Hit]> {
347    iter::from_fn(move || {
348        let ring = hits.first()?.ring;
349        let (group, rest) = hits.split_at(hits.partition_point(|x| x.ring == ring));
350        hits = rest;
351        Some(group)
352    })
353}
354
355/// Signed crossings, right of the current tile, of `ring`'s `count` edges from local edge `first`
356/// (cyclically): the row's still-active crossings in that edge range, summed by the Fenwick tree.
357fn excursion_winding(cs: &[Crossing], fenwick: &[i64], ring: RingInfo, first: usize, count: usize) -> i64 {
358    let (start, len) = (ring.edge0 as usize, ring.len as usize);
359    let sum = |lo: usize, hi: usize| {
360        let i = cs.partition_point(|c| (c.edge as usize) < lo);
361        let j = cs.partition_point(|c| (c.edge as usize) < hi);
362        fenwick_prefix(fenwick, j) - fenwick_prefix(fenwick, i)
363    };
364    if first + count <= len {
365        sum(start + first, start + first + count)
366    } else {
367        sum(start + first, start + len) + sum(start, start + first + count - len)
368    }
369}
370
371/// Reusable working memory for polygon slicing, kept in the [`Slicer`](crate::Slicer) between
372/// features (see [`Scratch`]): only its capacity survives a call.
373pub(crate) struct PolyScratch<V> {
374    /// The current polygon's kept rings, copies of rings that had duplicate vertices, and chunks.
375    rings: Vec<RingInfo>,
376    copies: Vec<V>,
377    chunks: Vec<Chunk>,
378    /// Chunk ids by first row, and the chunks reaching the current row (ascending, so edge order).
379    order: Vec<u32>,
380    active: Vec<u32>,
381    /// The current row: its per-tile spans of short edges (by column, then edge), the spans of its
382    /// long edges (by first column, then edge), the long ones covering the sweep's current tile (by
383    /// edge), and a tile's merged spans when a long edge crosses it. Then its crossings (by edge), the
384    /// crossings by `right_of`, and the Fenwick tree of the signs of those still right of the sweep.
385    hits: Vec<Hit>,
386    long: Vec<Span>,
387    long_cover: Vec<Span>,
388    covering: Vec<Hit>,
389    crossings: Vec<Crossing>,
390    by_x: Vec<u32>,
391    /// Sorting scratch for the row's spans.
392    hits_tmp: Vec<Hit>,
393    spans_tmp: Vec<Span>,
394    counts: Vec<usize>,
395    fenwick: Vec<i64>,
396    /// Per ring: odd crossings right of the current tile.
397    inside: Vec<bool>,
398    /// The piece being yielded.
399    piece: PieceBuf<V>,
400    arcs: Vec<(usize, usize)>,
401    clip: ClipScratch<V>,
402    /// Working memory of the piece's planarity check.
403    segs: PlanarScratch,
404    /// A repair's frame: the outside points it is built around, and their convex hull.
405    probe: Probe,
406    frame_hull: Vec<Coord<i32>>,
407    /// How many vertices a frame keeps past each tip of each bridge, and each input ring's first
408    /// bridge (see [`RingPlan::depths`]).
409    depths: Vec<(u32, u32)>,
410    ring_bases: Vec<usize>,
411    /// Each input ring's arcs for the tile, scanned once for the rounds of a frame's probe.
412    probe_arcs: Vec<(usize, usize)>,
413    probe_rings: Vec<Option<(usize, Range<usize>)>>,
414}
415
416impl<V> PolyScratch<V> {
417    pub(crate) const fn new() -> Self {
418        Self {
419            rings: Vec::new(),
420            copies: Vec::new(),
421            chunks: Vec::new(),
422            order: Vec::new(),
423            active: Vec::new(),
424            hits: Vec::new(),
425            long: Vec::new(),
426            long_cover: Vec::new(),
427            covering: Vec::new(),
428            crossings: Vec::new(),
429            by_x: Vec::new(),
430            hits_tmp: Vec::new(),
431            spans_tmp: Vec::new(),
432            counts: Vec::new(),
433            fenwick: Vec::new(),
434            inside: Vec::new(),
435            piece: PieceBuf::new(),
436            arcs: Vec::new(),
437            clip: ClipScratch::new(),
438            segs: PlanarScratch::new(),
439            probe: Probe::new(),
440            frame_hull: Vec::new(),
441            depths: Vec::new(),
442            ring_bases: Vec::new(),
443            probe_arcs: Vec::new(),
444            probe_rings: Vec::new(),
445        }
446    }
447}
448
449/// The [`Slicer`](crate::Slicer)'s polygon working memory, allocated by its first polygon, so a
450/// slicer used only for lines and points never builds it. It holds nothing between calls that affects
451/// results: it compares equal, clones empty, and only its capacity survives a call.
452pub(crate) struct Scratch<V>(Option<Box<PolyState<V>>>);
453
454/// The working memory, and the state of the current polygon's sweep (kept out of the iterator, so the
455/// iterator stays small to move).
456pub(crate) struct PolyState<V> {
457    pub(crate) scratch: PolyScratch<V>,
458    sweep: Option<Sweep>,
459    /// The walk over the few tiles of a small polygon.
460    small: Option<SmallWalk>,
461}
462
463impl<V> Scratch<V> {
464    pub(crate) const fn new() -> Self {
465        Self(None)
466    }
467
468    /// The working memory, allocated on first use.
469    #[inline]
470    pub(crate) fn get(&mut self) -> &mut PolyState<V> {
471        #[cold]
472        fn alloc<V>() -> Box<PolyState<V>> {
473            Box::new(PolyState {
474                scratch: PolyScratch::new(),
475                sweep: None,
476                small: None,
477            })
478        }
479        self.0.get_or_insert_with(alloc)
480    }
481}
482
483impl<V> Clone for Scratch<V> {
484    fn clone(&self) -> Self {
485        Self::new()
486    }
487}
488
489impl<V> PartialEq for Scratch<V> {
490    fn eq(&self, _: &Self) -> bool {
491        true
492    }
493}
494
495impl<V> Eq for Scratch<V> {}
496
497impl<V> core::fmt::Debug for Scratch<V> {
498    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
499        f.debug_struct("PolyScratch").finish_non_exhaustive()
500    }
501}
502
503/// The fill ring of `run` on `grid`: tile (0, 0)'s buffered box `[-buffer, extent - 1 + buffer]`
504/// grown by one unit, wound like the run's polygon - the same in every tile's local frame. It fits
505/// `i32` because [`Grid::new`] keeps `extent + buffer` within it.
506pub(crate) fn fill_ring<V: PolyVertex>(grid: Grid, run: &FillRun) -> [V; 5] {
507    let (extent, buffer) = (grid.extent_i32(), grid.buffer_i32());
508    let sw = Coord {
509        x: -buffer - 1,
510        y: -buffer - 1,
511    };
512    let ne = Coord {
513        x: extent + buffer,
514        y: extent + buffer,
515    };
516    fill_box(run.orient, sw, ne).map(V::synthetic_at)
517}
518
519/// What the next slice is; the borrowed view is built from it.
520enum Event {
521    /// The whole current polygon, for `tile`: it lies in the tile's inner box, or is unclipped.
522    Whole {
523        tile: TileId,
524        origin: Coord<i32>,
525    },
526    /// A piece built into the piece buffer, for the tile at `origin`.
527    Built {
528        tile: TileId,
529        origin: Coord<i32>,
530    },
531    Run(FillRun),
532}
533
534/// The row sweep of the current polygon.
535struct Sweep {
536    /// The rows not yet loaded.
537    rows: RangeInclusive<i64>,
538    /// Chunks not yet active, as an index into the by-first-row order.
539    next_chunk: usize,
540    /// Whether a row is loaded, and the sweep's place in it: the next crossing (by `right_of`), the
541    /// next short-edge span, the next long-edge span, and the first tile not yet yielded or filled.
542    in_row: bool,
543    ty: i32,
544    k: usize,
545    h: usize,
546    lh: usize,
547    next: i64,
548    /// The spans of the current tile: its short-edge spans as they are (`Some`, the usual case: no
549    /// copy), or merged with the long edges crossing it into the scratch's `covering` (`None`).
550    cover: Option<Range<usize>>,
551    /// The last column a long edge covering the sweep reaches (`i64::MIN` when none does).
552    long_last: i64,
553    /// How many holes have odd parity right of the sweep.
554    holes_in: u32,
555    /// A covered span of the current row not yet yielded (it may still grow), as `start..end`.
556    pending: Option<(i64, i64)>,
557    /// A run to yield before anything else, and an edge tile to build after it (from the spans
558    /// covering it).
559    ready: Option<FillRun>,
560    tile_ready: Option<i32>,
561    /// The exterior's winding, once a fill needs it.
562    orient: Option<Ordering>,
563    /// The columns yielded: see [`PolygonSlices::within`].
564    cols: RangeInclusive<i32>,
565}
566
567/// Lazy iterator over the slices of a polygon in every tile it reaches; see
568/// [`Slicer::polygon`](crate::Slicer::polygon).
569///
570/// A **lending** iterator: a [`PolygonPiece`] borrows the iterator's piece buffer, so it is valid
571/// until the next call to [`next`](Self::next). Loop with `while let Some(slice) = slices.next()`.
572pub struct PolygonSlices<'s, V, R> {
573    grid: Grid,
574    /// [`ClipMode::Unclipped`]: every tile gets the whole polygon.
575    whole: bool,
576    rings: &'s [R],
577    s: &'s mut PolyScratch<V>,
578    /// How the polygon starts, until the first step; then its sweep, if it has one.
579    start: Option<Start>,
580    sweep: &'s mut Option<Sweep>,
581    small: &'s mut Option<SmallWalk>,
582    done: bool,
583    /// The columns and rows yielded: see [`Self::within`].
584    cols: RangeInclusive<i32>,
585    rows: RangeInclusive<i32>,
586}
587
588/// How a loaded polygon starts: small, so the iterator can be built in place, its sweep only on the
589/// first step.
590enum Start {
591    /// It lies wholly in `tile`'s inner box.
592    Whole { tile: TileId, origin: Coord<i32> },
593    /// It is swept over `rows`.
594    Sweep { rows: RangeInclusive<i64> },
595    /// It is smaller than a tile, so no tile is covered: each of the tiles `x0..=x1` by `y0..=y1`
596    /// its buffered box reaches gets what [`clip_polygon_to_tile`] gives it, with no sweep.
597    Small { x0: i32, x1: i32, y0: i32, y1: i32 },
598}
599
600/// The walk over a small polygon's tiles: the next tile, and the columns and last row to go.
601#[derive(Clone, Copy)]
602struct SmallWalk {
603    x: i32,
604    y: i32,
605    x0: i32,
606    x1: i32,
607    y1: i32,
608}
609
610/// The most vertices of a polygon walked tile by tile (each tile scans all of them) rather than swept.
611const SMALL_VERTICES: u32 = 128;
612
613impl<'s, V: PolyVertex, R: AsRef<[V]>> PolygonSlices<'s, V, R> {
614    /// Load the polygon `rings`, bounding and indexing it.
615    #[cfg_attr(feature = "hotpath", hotpath::measure)]
616    #[inline]
617    pub(crate) fn new(
618        grid: Grid,
619        mode: ClipMode,
620        rings: &'s [R],
621        state: &'s mut PolyState<V>,
622    ) -> Result<Self, TileError> {
623        let PolyState {
624            scratch: s,
625            sweep,
626            small,
627        } = state;
628        *sweep = None;
629        *small = None;
630        let whole = mode == ClipMode::Unclipped;
631        let start = prepare(grid, rings, s, !whole)?;
632        Ok(Self {
633            grid,
634            whole,
635            rings,
636            s,
637            start,
638            sweep,
639            small,
640            done: false,
641            cols: i32::MIN..=i32::MAX,
642            rows: i32::MIN..=i32::MAX,
643        })
644    }
645
646    /// Yield only the slices in tiles `min..=max` (columns `min.x..=max.x`, rows `min.y..=max.y`).
647    /// Needs to be called before [`next`](Self::next).
648    #[must_use]
649    pub fn within(mut self, min: TileId, max: TileId) -> Self {
650        debug_assert!(self.sweep.is_none(), "within() before the first next()");
651        self.cols = min.x..=max.x;
652        self.rows = min.y..=max.y;
653        self
654    }
655
656    /// The next slice, or `None` when the polygon is done. An error ends the iteration: only
657    /// [`TileError::GeometryTooLarge`], for a piece of more than `u32::MAX` vertices, since
658    /// [`Slicer::polygon`](crate::Slicer::polygon) settled every overflow up front.
659    #[expect(
660        clippy::should_implement_trait,
661        reason = "a lending iterator: each item borrows the iterator"
662    )]
663    pub fn next(&mut self) -> Option<Result<PolygonSlice<'_, V, R>, TileError>> {
664        if self.done {
665            return None;
666        }
667        // A polygon inside one tile's inner box (most of them) is that tile's only slice.
668        if let Some(&Start::Whole { tile, origin }) = self.start.as_ref() {
669            self.start = None;
670            self.done = true;
671            let inside = self.cols.contains(&tile.x) && self.rows.contains(&tile.y);
672            return inside.then(|| Ok(self.view(Event::Whole { tile, origin })));
673        }
674        match self.step() {
675            Ok(Some(event)) => Some(Ok(self.view(event))),
676            Ok(None) => {
677                self.done = true;
678                None
679            }
680            Err(e) => {
681                self.done = true;
682                Some(Err(e))
683            }
684        }
685    }
686
687    /// The ring [`Slicer::tile_polygon`](crate::Slicer::tile_polygon) yields for `run`'s polygon in
688    /// each tile of the run: the tile's buffered box grown by one unit, tile-local and closed (its
689    /// first vertex repeated), all synthetic vertices, wound like the polygon's exterior. It is the
690    /// polygon's only ring there. The same as [`Slicer::fill_ring`](crate::Slicer::fill_ring), for use
691    /// while the iterator borrows the slicer.
692    #[must_use]
693    pub fn fill_ring(&self, run: &FillRun) -> [V; 5] {
694        fill_ring(self.grid, run)
695    }
696
697    fn view(&self, event: Event) -> PolygonSlice<'_, V, R> {
698        let (tile, rings) = match event {
699            Event::Run(run) => return PolygonSlice::Run(run),
700            Event::Built { tile, origin } => (
701                tile,
702                PieceRings::Built {
703                    verts: self.s.piece.verts(),
704                    ends: self.s.piece.ring_ends(),
705                    origin,
706                },
707            ),
708            Event::Whole { tile, origin } => (
709                tile,
710                PieceRings::Whole {
711                    rings: &self.s.rings,
712                    input: self.rings,
713                    copies: &self.s.copies,
714                    origin,
715                },
716            ),
717        };
718        PolygonSlice::Piece(PolygonPiece { tile, rings })
719    }
720
721    /// The next tile of a small polygon's walk ([`Start::Small`]).
722    #[inline(always)]
723    #[expect(
724        clippy::inline_always,
725        reason = "the walk of most polygons that cross a tile edge; out of line it costs them ~2%"
726    )]
727    fn step_small(&mut self) -> Result<Option<Event>, TileError> {
728        let Some(walk) = self.small.as_mut() else {
729            return Ok(None);
730        };
731        while walk.y <= walk.y1 {
732            let tile = TileId::new(walk.x, walk.y);
733            if walk.x < walk.x1 {
734                walk.x += 1;
735            } else {
736                (walk.x, walk.y) = (walk.x0, walk.y + 1);
737            }
738            // (`prepare` proved the box of every tile the polygon reaches fits `i32`.)
739            let (min, max) = self.grid.tile_box(tile);
740            // A lone ring inside the tile's buffered box (a building near a tile edge) is its
741            // piece there as it is: lent, not clipped.
742            if let [info] = self.s.rings[..]
743                // (The box's side may pass `i32::MAX`, but fits `u32`.)
744                && let span = max.x.wrapping_sub(min.x).cast_unsigned()
745                && ring_within(info.pts(self.rings, &self.s.copies), min, span).is_some()
746            {
747                let origin = self.grid.origin_of(min);
748                return Ok(Some(Event::Whole { tile, origin }));
749            }
750            let built = build_tile_piece(self.grid, min, max, self.rings, self.s)?;
751            if let Some(origin) = built {
752                return Ok(Some(Event::Built { tile, origin }));
753            }
754        }
755        *self.small = None;
756        Ok(None)
757    }
758
759    fn step(&mut self) -> Result<Option<Event>, TileError> {
760        match self.start.take() {
761            // (`next` yields a polygon that starts whole itself.)
762            Some(Start::Whole { .. }) | None => {}
763            Some(Start::Sweep { rows }) => {
764                let first = (*rows.start()).max(i64::from(*self.rows.start()));
765                let last = (*rows.end()).min(i64::from(*self.rows.end()));
766                *self.sweep = Some(Sweep::new(first..=last, self.cols.clone()));
767            }
768            Some(Start::Small { x0, x1, y0, y1 }) => {
769                let (x0, x1) = (x0.max(*self.cols.start()), x1.min(*self.cols.end()));
770                let (y0, y1) = (y0.max(*self.rows.start()), y1.min(*self.rows.end()));
771                if x0 <= x1 {
772                    *self.small = Some(SmallWalk {
773                        x: x0,
774                        y: y0,
775                        x0,
776                        x1,
777                        y1,
778                    });
779                }
780            }
781        }
782        // (No sweep: a small polygon's walk, if any.)
783        let Some(sw) = self.sweep.as_mut() else {
784            return self.step_small();
785        };
786        let mut cx = Cx {
787            grid: self.grid,
788            s: &mut *self.s,
789            rings: self.rings,
790        };
791        if self.whole {
792            sw.step_whole(&mut cx)
793        } else {
794            sw.step::<false, V, R>(&mut cx)
795        }
796    }
797}
798
799/// The most vertices of a ring [`Grid::inner_tile_of_ring`] is asked about: a building, not a coastline.
800const LONE_RING: usize = 16;
801
802/// Load the polygon `rings` into `s`: how it starts, or `None` if there is nothing to slice (a
803/// degenerate exterior). Every overflow the slicing could meet is settled here, from the polygon's
804/// bounds.
805// Once per polygon: inlined into `PolygonSlices::new`, it costs small polygons ~4%.
806#[inline(never)]
807fn prepare<V: PolyVertex, R: AsRef<[V]>>(
808    grid: Grid,
809    rings: &[R],
810    s: &mut PolyScratch<V>,
811    allow_small: bool,
812) -> Result<Option<Start>, TileError> {
813    let (extent, buffer) = (i64::from(grid.extent()), i64::from(grid.buffer()));
814    s.rings.clear();
815    s.copies.clear();
816    // The usual polygon is one small ring with no repeated vertex (a building, most often four
817    // corners) lying inside a tile's inner box: found in one pass, with none of the loop's bookkeeping.
818    if let [ring] = rings
819        && let ring = ring.as_ref()
820        && (3..=LONE_RING).contains(&ring.len())
821        && let Some((tile, origin, vertices)) = grid.inner_tile_of_ring(ring)
822    {
823        s.rings.push(RingInfo {
824            input: 0,
825            src: Src::Input,
826            len: u32::try_from(vertices).unwrap_or(0),
827            edge0: 0,
828        });
829        return Ok(Some(Start::Whole { tile, origin }));
830    }
831    u32::try_from(rings.len()).map_err(|_too_large| TileError::GeometryTooLarge)?;
832    let mut lo = Coord {
833        x: i32::MAX,
834        y: i32::MAX,
835    };
836    let mut hi = Coord {
837        x: i32::MIN,
838        y: i32::MIN,
839    };
840    let mut edges = 0_u32;
841    for (index, ring) in (0_u32..).zip(rings) {
842        let Some((info, rlo, rhi)) = load_ring(s, index, ring.as_ref(), edges)? else {
843            if index == 0 {
844                return Ok(None); // a degenerate exterior drops the polygon
845            }
846            continue;
847        };
848        edges = edges.checked_add(info.len).ok_or(TileError::GeometryTooLarge)?;
849        s.rings.push(info);
850        (lo.x, lo.y) = (lo.x.min(rlo.x), lo.y.min(rlo.y));
851        (hi.x, hi.y) = (hi.x.max(rhi.x), hi.y.max(rhi.y));
852    }
853
854    // A polygon inside one tile's inner box touches only that tile, whose box `inner_tile` proved
855    // fits: it goes there whole, lent as it is, with nothing else to check.
856    if let Some((tile, origin)) = grid.inner_tile(lo, hi) {
857        return Ok(Some(Start::Whole { tile, origin }));
858    }
859    grid.check_polygon_bounds(lo, hi)?;
860
861    // A polygon smaller than a tile, with few vertices (a building): no tile it reaches is covered,
862    // so each gets its edge piece from the one-tile clip, which costs less than the sweep's setup.
863    if allow_small
864        && edges <= SMALL_VERTICES
865        && i64::from(hi.x) - i64::from(lo.x) < extent
866        && i64::from(hi.y) - i64::from(lo.y) < extent
867    {
868        let tile = |c: i32, d: i64| {
869            // The tile index of `c + d`: it fits `i32` (`check_polygon_bounds` proved the boxes do).
870            i32::try_from((i64::from(c) + d).div_euclid(extent)).unwrap_or(0)
871        };
872        return Ok(Some(Start::Small {
873            x0: tile(lo.x, -buffer),
874            x1: tile(hi.x, buffer),
875            y0: tile(lo.y, -buffer),
876            y1: tile(hi.y, buffer),
877        }));
878    }
879
880    s.chunks.clear();
881    index_chunks(s, rings, extent, buffer);
882    s.order.clear();
883    #[expect(clippy::cast_possible_truncation, reason = "at most one chunk per edge")]
884    s.order.extend(0..s.chunks.len() as u32);
885    let chunks = &s.chunks;
886    s.order.sort_unstable_by_key(|&c| chunks[c as usize].rows.0);
887    s.active.clear();
888    s.inside.clear();
889    s.inside.resize(s.rings.len(), false);
890    let first = (i64::from(lo.y) - buffer).div_euclid(extent);
891    let last = (i64::from(hi.y) + buffer).div_euclid(extent);
892    Ok(Some(Start::Sweep { rows: first..=last }))
893}
894
895/// What the sweep reads besides its own state: the grid, the scratch, and the polygon being swept.
896struct Cx<'x, V, R> {
897    grid: Grid,
898    s: &'x mut PolyScratch<V>,
899    rings: &'x [R],
900}
901
902impl Sweep {
903    /// A sweep over `rows`, before its first row.
904    fn new(rows: RangeInclusive<i64>, cols: RangeInclusive<i32>) -> Self {
905        Self {
906            rows,
907            next_chunk: 0,
908            in_row: false,
909            ty: 0,
910            k: 0,
911            h: 0,
912            next: i64::MIN,
913            holes_in: 0,
914            pending: None,
915            ready: None,
916            tile_ready: None,
917            orient: None,
918            lh: 0,
919            cover: Some(0..0),
920            long_last: i64::MIN,
921            cols,
922        }
923    }
924
925    /// [`Self::step`] unclipped.
926    // Keeps this second copy of the sweep out of `PolygonSlices::next`, so the clipped one inlines as
927    // before (any extra code there costs the clipped sweep 2-5%).
928    #[inline(never)]
929    fn step_whole<V: PolyVertex, R: AsRef<[V]>>(&mut self, cx: &mut Cx<'_, V, R>) -> Result<Option<Event>, TileError> {
930        self.step::<true, V, R>(cx)
931    }
932
933    /// Advance the sweep to its next slice; `None` when the polygon is done. `WHOLE`
934    /// ([`ClipMode::Unclipped`]): give every tile the whole polygon, fill runs tile by tile.
935    fn step<const WHOLE: bool, V: PolyVertex, R: AsRef<[V]>>(
936        &mut self,
937        cx: &mut Cx<'_, V, R>,
938    ) -> Result<Option<Event>, TileError> {
939        loop {
940            if let Some(run) = self.ready.take() {
941                return Ok(Some(if WHOLE {
942                    self.whole_run_tile(cx.grid, run)
943                } else {
944                    Event::Run(run)
945                }));
946            }
947            if let Some(tx) = self.tile_ready.take() {
948                let tile = TileId::new(tx, self.ty);
949                if WHOLE {
950                    if let Some(event) = self.whole_tile(cx.grid, cx.s, tile) {
951                        return Ok(Some(event));
952                    }
953                } else if let Some(origin) = self.build_tile(cx, tile)? {
954                    return Ok(Some(Event::Built { tile, origin }));
955                }
956                continue;
957            }
958            if !self.in_row {
959                let Some(row) = self.rows.next() else {
960                    return Ok(None);
961                };
962                self.load_row(cx, row)?;
963                self.ty = i32::try_from(row).map_err(|_overflow| TileError::Overflow)?;
964                (self.in_row, self.k, self.h, self.lh, self.next) = (true, 0, 0, 0, i64::MIN);
965                (self.cover, self.long_last) = (Some(0..0), i64::MIN);
966                continue;
967            }
968            if self.next > i64::from(*self.cols.end()) {
969                // Past the window: nothing more in this row, whose parity starts the next one even.
970                self.ready = self.take_pending();
971                cx.s.inside.fill(false);
972                self.holes_in = 0;
973                self.in_row = false;
974                continue;
975            }
976            // Tiles `next..=bound` all see the same crossings on their winding rays.
977            let s = &*cx.s;
978            let bound = s
979                .by_x
980                .get(self.k)
981                .map_or(i64::MAX, |&i| s.crossings[i as usize].right_of);
982            // The next edge tile, and its spans. Rows without long edges (most) take the short path.
983            let tile = if s.long.is_empty() {
984                s.hits.get(self.h).map(|c| i64::from(c.tx))
985            } else {
986                // The sweep's next tile if a long edge still covers it, else where the next short or
987                // long span starts.
988                let next = self.next;
989                // (`long_last` is `i64::MIN` when no long edge covers the sweep, as at a row start.)
990                let covered = (self.long_last != i64::MIN && self.long_last >= next).then_some(next);
991                let short = s.hits.get(self.h).map(|c| i64::from(c.tx));
992                let long = s.long.get(self.lh).map(|c| i64::from(c.first).max(next));
993                [covered, short, long].into_iter().flatten().min()
994            };
995            if let Some(tx) = tile
996                && tx <= bound
997            {
998                let tx = i32::try_from(tx).map_err(|_overflow| TileError::Overflow)?;
999                let s = &mut *cx.s;
1000                // The tile's short-edge spans: one contiguous run.
1001                let start = self.h;
1002                self.h += s.hits[start..].partition_point(|c| c.tx == tx);
1003                self.cover = Some(start..self.h);
1004                if !s.long.is_empty() {
1005                    self.cover_long(s, tx, start);
1006                }
1007                self.fill(cx, self.next, i64::from(tx))?;
1008                // The edge tile ends any covered span before it.
1009                self.ready = self.take_pending();
1010                self.tile_ready = self.cols.contains(&tx).then_some(tx);
1011                self.next = i64::from(tx) + 1;
1012                continue;
1013            }
1014            if self.k == s.by_x.len() {
1015                // Past every crossing each ring's parity is even again: nothing covers.
1016                debug_assert!(cx.s.inside.iter().all(|&i| !i), "parity ends even");
1017                self.ready = self.take_pending();
1018                self.in_row = false;
1019                continue;
1020            }
1021            // `bound` is a crossing's `right_of` (|·| ≤ 2^32), so `+ 1` cannot overflow.
1022            self.fill(cx, self.next, bound + 1)?;
1023            self.next = bound + 1;
1024            // Tiles past `bound` have these crossings on their left.
1025            let s = &mut *cx.s;
1026            while let Some(&i) = s.by_x.get(self.k)
1027                && s.crossings[i as usize].right_of == bound
1028            {
1029                let crossing = s.crossings[i as usize];
1030                let r = crossing.ring as usize;
1031                s.inside[r] = !s.inside[r];
1032                if r != 0 {
1033                    if s.inside[r] {
1034                        self.holes_in += 1;
1035                    } else {
1036                        // Parity alternates from an empty row start, so a hole leaves only after
1037                        // entering.
1038                        self.holes_in = self.holes_in.saturating_sub(1);
1039                    }
1040                }
1041                fenwick_add(&mut s.fenwick, i as usize, -crossing.sign());
1042                self.k += 1;
1043            }
1044            // Coverage that ends here ends the covered span: it cannot grow past this crossing.
1045            if !(s.inside[0] && self.holes_in == 0) {
1046                self.ready = self.take_pending();
1047            }
1048        }
1049    }
1050
1051    /// Unclipped, each covered tile gets the whole polygon: the first tile of `run`, keeping the rest
1052    /// of it for the next steps.
1053    fn whole_run_tile(&mut self, grid: Grid, mut run: FillRun) -> Event {
1054        let tile = TileId::new(run.x.start, run.y);
1055        run.x.start += 1;
1056        if !run.x.is_empty() {
1057            self.ready = Some(run);
1058        }
1059        Event::Whole {
1060            tile,
1061            origin: grid.tile_origin(tile),
1062        }
1063    }
1064
1065    /// Add the long edges covering tile `tx` to its spans (the short ones are `s.hits[start..h]`):
1066    /// drop those ending before it, add those starting by it, and merge both in edge order.
1067    fn cover_long<V>(&mut self, s: &mut PolyScratch<V>, tx: i32, start: usize) {
1068        if self.long_last < i64::from(tx) {
1069            s.long_cover.clear();
1070        } else {
1071            s.long_cover.retain(|c| c.last >= tx);
1072        }
1073        let kept = s.long_cover.len();
1074        while let Some(&span) = s.long.get(self.lh)
1075            && span.first <= tx
1076        {
1077            s.long_cover.push(span);
1078            self.lh += 1;
1079        }
1080        if s.long_cover.is_empty() {
1081            self.long_last = i64::MIN;
1082            return;
1083        }
1084        merge_by_edge(&mut s.long_cover, kept, &mut s.spans_tmp, |c| c.edge);
1085        self.long_last = s.long_cover.iter().map(|c| i64::from(c.last)).max().unwrap_or(i64::MIN);
1086        s.covering.clear();
1087        s.covering.extend(s.long_cover.iter().map(|c| Hit {
1088            tx,
1089            edge: c.edge,
1090            ring: c.ring,
1091        }));
1092        let kept = s.covering.len();
1093        s.covering.extend_from_slice(&s.hits[start..self.h]);
1094        merge_by_edge(&mut s.covering, kept, &mut s.hits_tmp, |c| c.edge);
1095        self.cover = None;
1096    }
1097
1098    /// The covered span not yet yielded, as a run (ending it).
1099    fn take_pending(&mut self) -> Option<FillRun> {
1100        let (start, end) = self.pending.take()?;
1101        #[expect(
1102            clippy::cast_possible_truncation,
1103            reason = "both ends were checked to fit i32 when the span was recorded"
1104        )]
1105        Some(FillRun {
1106            y: self.ty,
1107            x: start as i32..end as i32,
1108            orient: self.orient.unwrap_or(Ordering::Equal),
1109        })
1110    }
1111
1112    /// Record tiles `start..end` of the current row as covered, if the polygon covers them,
1113    /// extending the span not yet yielded when they abut.
1114    fn fill<V: PolyVertex, R: AsRef<[V]>>(
1115        &mut self,
1116        cx: &mut Cx<'_, V, R>,
1117        start: i64,
1118        end: i64,
1119    ) -> Result<(), TileError> {
1120        let covered = cx.s.inside.first().copied().unwrap_or(false) && self.holes_in == 0;
1121        if start >= end || !covered {
1122            return Ok(());
1123        }
1124        i32::try_from(start).map_err(|_overflow| TileError::Overflow)?;
1125        i32::try_from(end).map_err(|_overflow| TileError::Overflow)?;
1126        let start = start.max(i64::from(*self.cols.start()));
1127        let end = end.min(i64::from(*self.cols.end()) + 1);
1128        if start >= end {
1129            return Ok(());
1130        }
1131        if self.orient.is_none() {
1132            let ext = cx.s.rings[0].pts(cx.rings, &cx.s.copies);
1133            self.orient = Some(ring_orientation(ext));
1134        }
1135        match &mut self.pending {
1136            Some((_, e)) if *e == start => *e = end,
1137            pending => {
1138                debug_assert!(pending.is_none(), "an edge tile or row end yields a span first");
1139                *pending = Some((start, end));
1140            }
1141        }
1142        Ok(())
1143    }
1144
1145    /// Gather row `ty`'s hits and crossings from the chunks reaching it.
1146    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1147    // (The `hotpath` wrapper hides the body from this lint.)
1148    #[cfg_attr(
1149        not(feature = "hotpath"),
1150        expect(clippy::many_single_char_names, reason = "edge endpoints and the scratch")
1151    )]
1152    fn load_row<V: PolyVertex, R: AsRef<[V]>>(&mut self, cx: &mut Cx<'_, V, R>, ty: i64) -> Result<(), TileError> {
1153        let (extent, buffer) = (i64::from(cx.grid.extent()), i64::from(cx.grid.buffer()));
1154        let s = &mut *cx.s;
1155        let rings = cx.rings;
1156        while let Some(&c) = s.order.get(self.next_chunk)
1157            && s.chunks[c as usize].rows.0 <= ty
1158        {
1159            let at = s.active.partition_point(|&a| a < c);
1160            s.active.insert(at, c);
1161            self.next_chunk += 1;
1162        }
1163        let chunks = &s.chunks;
1164        s.active.retain(|&c| chunks[c as usize].rows.1 >= ty);
1165
1166        s.hits.clear();
1167        s.long.clear();
1168        s.long_cover.clear();
1169        s.covering.clear();
1170        s.crossings.clear();
1171        let (slab_lo, slab_hi) = (ty * extent - buffer, ty * extent + extent - 1 + buffer);
1172        let cy = row_center(ty, extent);
1173        for &c in &s.active {
1174            let chunk = s.chunks[c as usize];
1175            let info = s.rings[chunk.ring as usize];
1176            let pts = info.pts(rings, &s.copies);
1177            let m = pts.len();
1178            for i in chunk.first as usize..(chunk.first + chunk.count) as usize {
1179                let (a, b) = (pts[i].position(), pts[(i + 1) % m].position());
1180                let (lo, hi) = if a.y <= b.y { (a, b) } else { (b, a) };
1181                if i64::from(hi.y) < slab_lo || i64::from(lo.y) > slab_hi {
1182                    continue;
1183                }
1184                #[expect(clippy::cast_possible_truncation, reason = "edge ids fit u32")]
1185                let edge = info.edge0 + i as u32;
1186                let wide = |p: Coord<i32>| Coord {
1187                    x: i64::from(p.x),
1188                    y: i64::from(p.y),
1189                };
1190                let (first, last) = Seg::new(wide(lo), wide(hi)).row_span(ty, extent, buffer);
1191                let fits = |v: i64| i32::try_from(v).map_err(|_overflow| TileError::Overflow);
1192                if last - first + 1 >= LONG_EDGE {
1193                    s.long.push(Span {
1194                        first: fits(first)?,
1195                        last: fits(last)?,
1196                        edge,
1197                        ring: chunk.ring,
1198                    });
1199                } else {
1200                    for tx in first..=last {
1201                        s.hits.push(Hit {
1202                            tx: fits(tx)?,
1203                            edge,
1204                            ring: chunk.ring,
1205                        });
1206                    }
1207                }
1208                // Crossings of the center line, half-open in `y`.
1209                if i64::from(lo.y) <= cy && cy < i64::from(hi.y) {
1210                    let x = crossing_x_ceil(a, b, i32::try_from(cy).map_err(|_overflow| TileError::Overflow)?);
1211                    s.crossings.push(Crossing {
1212                        edge,
1213                        ring: chunk.ring,
1214                        up: b.y > a.y,
1215                        // Right of tile `tx`'s box iff x > tx·extent + extent - 1 + buffer.
1216                        right_of: (x - extent - buffer).div_euclid(extent),
1217                    });
1218                }
1219            }
1220        }
1221        sort_hits(&mut s.hits, &mut s.hits_tmp, &mut s.counts);
1222        s.long.sort_unstable_by_key(|c| (c.first, c.edge));
1223        debug_assert!(s.crossings.is_sorted_by_key(|c| c.edge));
1224        s.by_x.clear();
1225        #[expect(clippy::cast_possible_truncation, reason = "one crossing per edge")]
1226        s.by_x.extend(0..s.crossings.len() as u32);
1227        let crossings = &s.crossings;
1228        s.by_x.sort_unstable_by_key(|&i| crossings[i as usize].right_of);
1229        fenwick_build(&mut s.fenwick, s.crossings.iter().map(|c| c.sign()));
1230        Ok(())
1231    }
1232
1233    /// The spans covering the current edge tile, if the polygon leaves anything there. Only the
1234    /// touching rings are visited: the untouched holes are settled at once by how many of them
1235    /// contain the tile. Takes the scratch's row fields, `hits`, `covering` and `inside`, rather than
1236    /// the scratch, so the caller can still write the piece buffer.
1237    #[expect(
1238        clippy::inline_always,
1239        reason = "run per edge tile; out of line it costs the polygon benchmarks 2%"
1240    )]
1241    #[inline(always)]
1242    fn tile_hits<'x>(&self, hits: &'x [Hit], covering: &'x [Hit], inside: &[bool]) -> Option<&'x [Hit]> {
1243        let hits = match &self.cover {
1244            Some(range) => &hits[range.clone()],
1245            None => covering,
1246        };
1247        // Hits come in edge order, so the exterior's (if any) come first, then each hole's.
1248        let exterior_touched = hits.first().is_some_and(|x| x.ring == 0);
1249        if !exterior_touched && !inside[0] {
1250            return None; // the exterior misses the tile
1251        }
1252        // `holes_in` counts every hole whose ray parity is odd, but a touched hole's parity says
1253        // nothing about the tile: what remains are untouched holes containing it.
1254        let holes_in = self.holes_in as usize;
1255        if holes_in > 0
1256            && holes_in
1257                > ring_groups(hits)
1258                    .filter(|g| g[0].ring != 0 && inside[g[0].ring as usize])
1259                    .count()
1260        {
1261            return None;
1262        }
1263        Some(hits)
1264    }
1265
1266    /// Unclipped, edge tile `tile` gets the whole polygon if it would get a piece.
1267    fn whole_tile<V>(&self, grid: Grid, s: &PolyScratch<V>, tile: TileId) -> Option<Event> {
1268        self.tile_hits(&s.hits, &s.covering, &s.inside)?;
1269        let origin = grid.tile_origin(tile);
1270        Some(Event::Whole { tile, origin })
1271    }
1272
1273    /// Build the polygon's piece in edge tile `tile` from [the spans covering it](Self::tile_hits)
1274    /// into the piece buffer, returning the tile origin; `None` if it leaves nothing there. Every
1275    /// vertex fits the tile's local frame: the polygon's bounds were checked when it was loaded.
1276    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1277    fn build_tile<V: PolyVertex, R: AsRef<[V]>>(
1278        &mut self,
1279        cx: &mut Cx<'_, V, R>,
1280        tile: TileId,
1281    ) -> Result<Option<Coord<i32>>, TileError> {
1282        let (min, max) = cx.grid.tile_buffered_bounds(tile)?;
1283        let origin = cx.grid.origin_of(min);
1284        let s = &mut *cx.s;
1285        let rings = cx.rings;
1286        let Some(hits) = self.tile_hits(&s.hits, &s.covering, &s.inside) else {
1287            return Ok(None);
1288        };
1289        let exterior_touched = hits.first().is_some_and(|x| x.ring == 0);
1290        // The plain clip: what [`Self::piece`] builds for [`Attempt::PLAIN`], without its bookkeeping.
1291        s.piece.clear();
1292        if !exterior_touched {
1293            // A tile the exterior covers gets a fill box, wound like the exterior.
1294            let orient = *self
1295                .orient
1296                .get_or_insert_with(|| ring_orientation(s.rings[0].pts(rings, &s.copies)));
1297            s.piece.push_fill_box(orient, min, max)?;
1298        }
1299        for ring_hits in ring_groups(hits) {
1300            let info = s.rings[ring_hits[0].ring as usize];
1301            s.arcs.clear();
1302            for x in ring_hits {
1303                keep_edge(&mut s.arcs, (x.edge - info.edge0) as usize);
1304            }
1305            let (cs, fenwick) = (&s.crossings, &s.fenwick);
1306            let winding = |first: usize, count: usize| excursion_winding(cs, fenwick, info, first, count);
1307            let pts = info.pts(rings, &s.copies);
1308            let (arcs, piece) = (&mut s.arcs, &mut s.piece);
1309            s.clip.close_ring(pts, arcs, (min, max), winding, piece)?;
1310        }
1311        if !self.make_valid(s, rings, (min, max), origin, exterior_touched)? {
1312            return Ok(None);
1313        }
1314        Ok(Some(origin))
1315    }
1316
1317    /// [`Self::build_tile`]'s plain clip, just built, made planar outside the box if it is not:
1318    /// `false` if the polygon then leaves nothing in the tile. Out of line, to keep the plain clip's
1319    /// small.
1320    #[inline(never)]
1321    fn make_valid<V: PolyVertex, R: AsRef<[V]>>(
1322        &self,
1323        s: &mut PolyScratch<V>,
1324        rings: &[R],
1325        (min, max): (Coord<i32>, Coord<i32>),
1326        origin: Coord<i32>,
1327        exterior_touched: bool,
1328    ) -> Result<bool, TileError> {
1329        let Some(budget) = needs_repair(s, (min, max)) else {
1330            return Ok(true);
1331        };
1332        // (The plain clip of a covered tile just found the exterior's winding.)
1333        let fill = (!exterior_touched).then(|| self.orient.unwrap_or(Ordering::Equal));
1334        let whole_fits = fits_whole(rings);
1335        repair(s, (min, max), origin, rings.len(), whole_fits, budget, |s, a, b| {
1336            self.piece(s, rings, (min, max), fill, a, b)
1337        })
1338    }
1339
1340    /// Build the piece of the edge tile with box `(min, max)`, which [`Self::tile_hits`] found gets one,
1341    /// by `attempt` into the piece buffer, from the spans covering it and the winding index, so a repair costs the piece, not
1342    /// the ring. `fill` is the exterior's winding if it covers the tile, which then gets a fill box.
1343    #[inline]
1344    fn piece<V: PolyVertex, R: AsRef<[V]>>(
1345        &self,
1346        s: &mut PolyScratch<V>,
1347        rings: &[R],
1348        (min, max): (Coord<i32>, Coord<i32>),
1349        fill: Option<Ordering>,
1350        attempt: Attempt,
1351        budget: &mut usize,
1352    ) -> Result<Built, TileError> {
1353        // (The caller checked the tile gets a piece: these are the spans covering it.)
1354        let hits = match &self.cover {
1355            Some(range) => &s.hits[range.clone()],
1356            None => &s.covering[..],
1357        };
1358        let covered = fill.is_some();
1359        // Growing the fill box does nothing unless the exterior covers the tile and there are holes.
1360        if attempt == Attempt::ENCLOSE && (!covered || rings.len() == 1) {
1361            return Ok(Built::Failed);
1362        }
1363        s.piece.clear();
1364        s.clip.start_attempt();
1365        if attempt.frame {
1366            let probed = adapt_frame(
1367                |depths, probe, bases| {
1368                    bases.clear();
1369                    bases.resize(rings.len(), 0);
1370                    for ring_hits in ring_groups(hits) {
1371                        let info = s.rings[ring_hits[0].ring as usize];
1372                        s.arcs.clear();
1373                        for x in ring_hits {
1374                            keep_edge(&mut s.arcs, (x.edge - info.edge0) as usize);
1375                        }
1376                        let plan = RingPlan {
1377                            depths: Some(depths),
1378                            bridge_base: probe.bridges,
1379                            ..RingPlan::PLAIN
1380                        };
1381                        bases[info.input as usize] = probe.bridges;
1382                        let pts = info.pts(rings, &s.copies);
1383                        arcs_points(pts, &mut s.arcs, plan, (min, max), probe);
1384                    }
1385                    Ok(())
1386                },
1387                &mut s.depths,
1388                &mut s.probe,
1389                &mut s.frame_hull,
1390                &mut s.ring_bases,
1391                (min, max),
1392                budget,
1393            )?;
1394            if !probed {
1395                return Ok(Built::Failed);
1396            }
1397        }
1398        if let Some(orient) = fill {
1399            s.piece.push_fill_box(orient, min, max)?;
1400        }
1401        for ring_hits in ring_groups(hits) {
1402            let info = s.rings[ring_hits[0].ring as usize];
1403            s.arcs.clear();
1404            for x in ring_hits {
1405                keep_edge(&mut s.arcs, (x.edge - info.edge0) as usize);
1406            }
1407            let (cs, fenwick) = (&s.crossings, &s.fenwick);
1408            let winding = |first: usize, count: usize| excursion_winding(cs, fenwick, info, first, count);
1409            let pts = info.pts(rings, &s.copies);
1410            let plan = if attempt == Attempt::PLAIN {
1411                RingPlan::PLAIN
1412            } else {
1413                let frame = attempt.frame.then(|| {
1414                    let ring = info.input as usize;
1415                    (s.frame_hull.as_slice(), s.depths.as_slice(), s.ring_bases[ring])
1416                });
1417                attempt.ring_plan(info.input as usize, rings.len(), frame)
1418            };
1419            let (arcs, piece) = (&mut s.arcs, &mut s.piece);
1420            let closed = s
1421                .clip
1422                .close_ring_planned(pts, arcs, (min, max), winding, &plan, piece)?;
1423            if closed == Closed::FrameMissed {
1424                return Ok(Built::Failed);
1425            }
1426        }
1427        if attempt.enclose && covered && s.piece.ring_ends().len() > 1 {
1428            s.piece.grow_fill_box(min, max)?;
1429        }
1430        Ok(Built::Piece)
1431    }
1432}
1433
1434/// A kept ring and its bounding box `(lo, hi)`.
1435type LoadedRing = (RingInfo, Coord<i32>, Coord<i32>);
1436
1437/// Load one ring of the polygon in `s` (its `index` among the input rings, its first edge `edge0`):
1438/// borrowed when it is distinct as given - no consecutive duplicates once its repeated closing
1439/// vertices are dropped - else its distinct vertices copied, with its bounding box. `None` for a
1440/// degenerate ring (fewer than 3 distinct vertices).
1441#[expect(
1442    clippy::inline_always,
1443    reason = "run per ring of every polygon; out of line it costs the small-polygon benchmarks 3-5%"
1444)]
1445#[inline(always)]
1446fn load_ring<V: Vertex>(
1447    s: &mut PolyScratch<V>,
1448    index: u32,
1449    ring: &[V],
1450    edge0: u32,
1451) -> Result<Option<LoadedRing>, TileError> {
1452    let Some(first) = ring.first().map(Vertex::position) else {
1453        return Ok(None);
1454    };
1455    let mut n = ring.len();
1456    while n >= 2 && ring[n - 1].position() == first {
1457        n -= 1;
1458    }
1459    // One pass: the bounding box, and whether the ring is distinct as given.
1460    let (mut lo, mut hi, mut prev, mut distinct) = (first, first, first, true);
1461    for v in &ring[1..n] {
1462        let p = v.position();
1463        (lo.x, lo.y, hi.x, hi.y) = (lo.x.min(p.x), lo.y.min(p.y), hi.x.max(p.x), hi.y.max(p.y));
1464        distinct &= p != prev;
1465        prev = p;
1466    }
1467    let (src, len) = if distinct {
1468        (Src::Input, n)
1469    } else {
1470        let start = s.copies.len();
1471        (Src::Copy(start), push_distinct(ring, &mut s.copies))
1472    };
1473    if len < 3 {
1474        if let Src::Copy(start) = src {
1475            s.copies.truncate(start);
1476        }
1477        return Ok(None);
1478    }
1479    let info = RingInfo {
1480        input: index,
1481        src,
1482        len: u32::try_from(len).map_err(|_too_large| TileError::GeometryTooLarge)?,
1483        edge0,
1484    };
1485    Ok(Some((info, lo, hi)))
1486}
1487
1488/// The row index of the polygon in `s.rings`: every run of [`CHUNK`] edges, with the rows its buffered
1489/// `y`-range reaches.
1490fn index_chunks<V: Vertex, R: AsRef<[V]>>(s: &mut PolyScratch<V>, rings: &[R], extent: i64, buffer: i64) {
1491    for (ring_id, info) in (0_u32..).zip(&s.rings) {
1492        let pts = info.pts(rings, &s.copies);
1493        for first in (0..pts.len()).step_by(CHUNK) {
1494            let count = CHUNK.min(pts.len() - first);
1495            let (mut y0, mut y1) = (i32::MAX, i32::MIN);
1496            for v in pts[first..first + count]
1497                .iter()
1498                .chain(iter::once(&pts[(first + count) % pts.len()]))
1499            {
1500                let y = v.position().y;
1501                (y0, y1) = (y0.min(y), y1.max(y));
1502            }
1503            #[expect(clippy::cast_possible_truncation, reason = "within the ring's u32 length")]
1504            s.chunks.push(Chunk {
1505                ring: ring_id,
1506                first: first as u32,
1507                count: count as u32,
1508                rows: (
1509                    (i64::from(y0) - buffer).div_euclid(extent),
1510                    (i64::from(y1) + buffer).div_euclid(extent),
1511                ),
1512            });
1513        }
1514    }
1515}
1516
1517/// How the rings of one repair attempt place their detours: all in the same lane, or each ring (and
1518/// each of its bridges) one lane further out - the exterior innermost, or outermost.
1519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1520enum Lanes {
1521    Shared,
1522    HolesOut,
1523    ExteriorOut,
1524}
1525
1526/// A frame's data for one ring: the hull to go around, how deep each bridge's tips go, and the ring's
1527/// first bridge.
1528type Frame<'a> = (&'a [Coord<i32>], &'a [(u32, u32)], usize);
1529
1530/// One attempt at building a piece: how deep each excursion keeps its original vertices, where the
1531/// detours run, and whether a covered tile's fill box grows to enclose the holes.
1532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1533struct Attempt {
1534    deepen: usize,
1535    lanes: Lanes,
1536    enclose: bool,
1537    /// Close excursions on a frame around the hull of everything kept, each tip keeping as many
1538    /// original vertices as it takes to be a vertex of that hull (see [`RingPlan::frame`]); `deepen`
1539    /// is not used.
1540    frame: bool,
1541}
1542
1543impl Attempt {
1544    /// The plain clip, whose pieces are what the slicer yields whenever they are planar.
1545    const PLAIN: Self = Self {
1546        deepen: 0,
1547        lanes: Lanes::Shared,
1548        enclose: false,
1549        frame: false,
1550    };
1551
1552    /// Only the fill box of a covered tile grows around the holes: the plain clip otherwise.
1553    const ENCLOSE: Self = Self {
1554        enclose: true,
1555        ..Self::PLAIN
1556    };
1557
1558    fn ring_plan(self, ring: usize, rings: usize, frame: Option<Frame<'_>>) -> RingPlan<'_> {
1559        let (lane_base, lane_step) = match self.lanes {
1560            Lanes::Shared => (0, 0),
1561            Lanes::HolesOut => (i32::try_from(ring).unwrap_or(i32::MAX), 1),
1562            Lanes::ExteriorOut => (i32::try_from(rings - 1 - ring).unwrap_or(i32::MAX), 1),
1563        };
1564        RingPlan {
1565            deepen: self.deepen,
1566            lane_base,
1567            lane_step,
1568            frame: frame.map(|f| f.0),
1569            depths: frame.map(|f| f.1),
1570            bridge_base: frame.map_or(0, |f| f.2),
1571        }
1572    }
1573}
1574
1575/// How many times a frame probe may deepen the tips that are not on the hull before giving up. A tip
1576/// goes one vertex deeper the first rounds, then more each round, so this reaches depths over 40.
1577const FRAME_ROUNDS: usize = 16;
1578
1579/// What a probe round costs, per point probed, in segment pairs of the tile's budget (the hull sorts).
1580const ROUND_COST: usize = 8;
1581
1582/// Find a frame for the piece: how many vertices each bridge's tips keep (into `depths`) so that every
1583/// tip is a vertex of the convex hull (into `hull`) of what the piece keeps outside the box, and the
1584/// corners of `B⁺`. `probe_all(depths, probe)` probes every ring of the piece at those depths, filling
1585/// `probe` and the first bridge of each input ring (`bases`). `false` if the tips do not get there.
1586fn adapt_frame(
1587    mut probe_all: impl FnMut(&[(u32, u32)], &mut Probe, &mut Vec<usize>) -> Result<(), TileError>,
1588    depths: &mut Vec<(u32, u32)>,
1589    probe: &mut Probe,
1590    hull: &mut Vec<Coord<i32>>,
1591    bases: &mut Vec<usize>,
1592    (min, max): (Coord<i32>, Coord<i32>),
1593    budget: &mut usize,
1594) -> Result<bool, TileError> {
1595    let (lo, hi) = lane_bounds(min, max, 1)?;
1596    depths.clear();
1597    for round in 0..FRAME_ROUNDS {
1598        probe.clear();
1599        probe_all(depths, probe, bases)?;
1600        let cost = probe.pts.len().saturating_mul(ROUND_COST);
1601        if cost > *budget {
1602            *budget = 0;
1603            return Ok(false);
1604        }
1605        *budget -= cost;
1606        depths.resize(probe.bridges, (0, 0));
1607        probe
1608            .pts
1609            .extend([lo, Coord { x: hi.x, y: lo.y }, hi, Coord { x: lo.x, y: hi.y }]);
1610        convex_hull(&mut probe.pts, hull);
1611        let mut deepened = false;
1612        for &(tip, bridge, side) in &probe.tips {
1613            if !hull.contains(&tip) {
1614                let d = &mut depths[bridge as usize];
1615                let step = 1 + u32::try_from(round / 4).unwrap_or(0);
1616                if side == 0 {
1617                    d.0 += step;
1618                } else {
1619                    d.1 += step;
1620                }
1621                deepened = true;
1622            }
1623        }
1624        if !deepened {
1625            return Ok(true);
1626        }
1627    }
1628    Ok(false)
1629}
1630
1631/// The most vertices a repair may fall back to keeping whole, as its last resort, counted over all
1632/// the polygon's rings (as given): a bigger polygon keeps the plain clip (invalid outside the box, but
1633/// bounded) rather than costing a tile its whole ring.
1634const WHOLE_LIMIT: usize = 2048;
1635
1636/// Whether the polygon `rings` is small enough for its excursions to be kept whole ([`WHOLE_LIMIT`]).
1637fn fits_whole<V, R: AsRef<[V]>>(rings: &[R]) -> bool {
1638    rings.iter().map(|r| r.as_ref().len()).sum::<usize>() <= WHOLE_LIMIT
1639}
1640
1641/// How deep the repairs without a frame keep each excursion's original vertices, shallowest first.
1642const DEPTHS: [usize; 5] = [1, 2, 4, 8, 16];
1643
1644/// The repairs tried after the plain clip, cheapest first: the fill box grown around the holes; the
1645/// frame (whose lanes nest the rings); the plain way with more vertices kept; and last every excursion
1646/// whole (`deepen == usize::MAX`), which is valid because the input is.
1647fn repair_attempts(rings: usize) -> impl Iterator<Item = Attempt> {
1648    let lanes = move |frame: bool, deepen: usize| {
1649        [Lanes::Shared, Lanes::HolesOut, Lanes::ExteriorOut]
1650            .into_iter()
1651            // One ring has no holes to put outside it, but its excursions still take lanes of their own.
1652            .filter(move |&l| rings > 1 || l != Lanes::ExteriorOut)
1653            .map(move |lanes| Attempt {
1654                deepen,
1655                lanes,
1656                enclose: true,
1657                frame,
1658            })
1659    };
1660    iter::once(Attempt::ENCLOSE)
1661        .chain(lanes(true, 0))
1662        .chain(DEPTHS.into_iter().flat_map(move |d| lanes(false, d)))
1663        .chain(iter::once(Attempt {
1664            deepen: usize::MAX,
1665            lanes: Lanes::Shared,
1666            enclose: true,
1667            frame: false,
1668        }))
1669}
1670
1671/// Build `rings`' piece in the box `[min, max]` for one `attempt` into the scratch's piece buffer,
1672/// in the input's frame: what [`Sweep::piece`] builds for the same attempt, from the rings.
1673fn build_piece<V: PolyVertex, R: AsRef<[V]>>(
1674    rings: &[R],
1675    min: Coord<i32>,
1676    max: Coord<i32>,
1677    attempt: Attempt,
1678    s: &mut PolyScratch<V>,
1679    budget: &mut usize,
1680) -> Result<Built, TileError> {
1681    s.piece.clear();
1682    s.clip.start_attempt();
1683    let Some((exterior, holes)) = rings.split_first() else {
1684        return Ok(Built::Empty);
1685    };
1686    // A frame goes around the hull of everything the piece keeps outside the box: find how deep each
1687    // tip must go to be on it.
1688    if attempt.frame {
1689        // Scan every ring once: the rounds of the probe only change how deep the tips go.
1690        s.probe_arcs.clear();
1691        s.probe_rings.clear();
1692        for ring in rings {
1693            s.probe_rings
1694                .push(scan_arcs(ring.as_ref(), min, max, &mut s.probe_arcs));
1695        }
1696        let probed = adapt_frame(
1697            |depths, probe, bases| {
1698                bases.clear();
1699                for (ring, scan) in rings.iter().zip(&s.probe_rings) {
1700                    bases.push(probe.bridges);
1701                    let plan = RingPlan {
1702                        depths: Some(depths),
1703                        bridge_base: probe.bridges,
1704                        ..RingPlan::PLAIN
1705                    };
1706                    match scan {
1707                        Some((m, arcs)) => {
1708                            if !arcs.is_empty() {
1709                                let ring = &ring.as_ref()[..*m];
1710                                arcs_points(ring, &mut s.probe_arcs[arcs.clone()], plan, (min, max), probe);
1711                            }
1712                        }
1713                        // A ring with repeated vertices is scanned from a copy, each round.
1714                        None => {
1715                            clip_ring_planned(
1716                                ring.as_ref(),
1717                                min,
1718                                max,
1719                                &mut s.clip,
1720                                &plan,
1721                                Some(&mut *probe),
1722                                &mut s.piece,
1723                            )?;
1724                        }
1725                    }
1726                }
1727                Ok(())
1728            },
1729            &mut s.depths,
1730            &mut s.probe,
1731            &mut s.frame_hull,
1732            &mut s.ring_bases,
1733            (min, max),
1734            budget,
1735        )?;
1736        if !probed {
1737            return Ok(Built::Failed);
1738        }
1739    }
1740    let frame = |ring: usize| {
1741        attempt
1742            .frame
1743            .then(|| (s.frame_hull.as_slice(), s.depths.as_slice(), s.ring_bases[ring]))
1744    };
1745    let plan = attempt.ring_plan(0, rings.len(), frame(0));
1746    // If the exterior misses the tile entirely, the whole polygon is absent here.
1747    let Some(exterior_clip) = clip_ring_planned(exterior.as_ref(), min, max, &mut s.clip, &plan, None, &mut s.piece)?
1748    else {
1749        return Ok(Built::Failed);
1750    };
1751    if exterior_clip == RingClip::Outside {
1752        return Ok(Built::Empty);
1753    }
1754    // Growing the fill box does nothing unless the exterior covers the tile and there are holes.
1755    if attempt == Attempt::ENCLOSE && (exterior_clip != RingClip::Covers || rings.len() == 1) {
1756        return Ok(Built::Failed);
1757    }
1758    for (i, hole) in (1..).zip(holes) {
1759        let plan = attempt.ring_plan(i, rings.len(), frame(i));
1760        match clip_ring_planned(hole.as_ref(), min, max, &mut s.clip, &plan, None, &mut s.piece)? {
1761            None => return Ok(Built::Failed),
1762            // A hole covering the whole tile leaves nothing to draw here.
1763            Some(RingClip::Covers) => return Ok(Built::Empty),
1764            Some(RingClip::Clipped | RingClip::Outside) => {}
1765        }
1766    }
1767    if attempt.enclose && exterior_clip == RingClip::Covers && s.piece.ring_ends().len() > 1 {
1768        s.piece.grow_fill_box(min, max)?;
1769    }
1770    Ok(Built::Piece)
1771}
1772
1773/// What building one attempt's piece came to.
1774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1775enum Built {
1776    /// The polygon leaves nothing in the tile.
1777    Empty,
1778    /// The attempt does not apply here, or can't be built: a fill box grown with no covered tile or
1779    /// no hole, a frame whose tips never reach its hull (within the budget) or can't close an
1780    /// excursion, or a lane past the `i32` limits.
1781    Failed,
1782    /// The piece is in the scratch's piece buffer.
1783    Piece,
1784}
1785
1786/// For the plain clip just built into `s` for the box `[min, max]`: `None` if it is planar outside
1787/// the box, or nothing says it is not (nothing synthetic can cross anything, and a check that runs
1788/// out of budget passes it); else the budget the check left for repairs.
1789#[inline]
1790fn needs_repair<V: PolyVertex>(s: &mut PolyScratch<V>, (min, max): (Coord<i32>, Coord<i32>)) -> Option<usize> {
1791    if s.piece.synthetic().is_empty() {
1792        return None;
1793    }
1794    let mut budget = PAIR_BUDGET;
1795    let verdict = is_planar(&s.piece, false, min, max, &mut s.segs, &mut budget);
1796    (verdict == Verdict::Crossing).then_some(budget)
1797}
1798
1799/// Rebuild the piece in `[min, max]`, whose plain clip is not planar outside the box, by the cheapest
1800/// repair that is (see [`repair_attempts`]), into the scratch's piece buffer; if none is found within
1801/// `budget`, or the last resort would keep more than [`WHOLE_LIMIT`] vertices (`!whole_fits`), the
1802/// plain clip again. `attempt_piece(s, attempt, budget)` builds one attempt's piece: [`Sweep::piece`] for the
1803/// all-tiles slicer, [`build_piece`] for one tile, which build the same pieces, so this one search
1804/// gives a tile the same piece either way. `false` if the polygon leaves nothing in the tile (as its
1805/// plain clip says).
1806#[cold]
1807#[inline(never)]
1808fn repair<V: PolyVertex>(
1809    s: &mut PolyScratch<V>,
1810    (min, max): (Coord<i32>, Coord<i32>),
1811    origin: Coord<i32>,
1812    rings: usize,
1813    whole_fits: bool,
1814    mut budget: usize,
1815    mut attempt_piece: impl FnMut(&mut PolyScratch<V>, Attempt, &mut usize) -> Result<Built, TileError>,
1816) -> Result<bool, TileError> {
1817    for attempt in repair_attempts(rings) {
1818        let whole = attempt.deepen == usize::MAX;
1819        if whole && !whole_fits {
1820            break;
1821        }
1822        let built = match attempt_piece(s, attempt, &mut budget) {
1823            // The plain clip fits `i32`: only a repair's growth past it can overflow.
1824            Err(TileError::Overflow) => Built::Failed,
1825            built => built?,
1826        };
1827        match built {
1828            Built::Empty => return Ok(false),
1829            Built::Failed => {}
1830            Built::Piece => {
1831                // Every excursion whole is the input's own rings: as valid as it is.
1832                let verdict = if whole {
1833                    Verdict::Planar
1834                } else {
1835                    is_planar(&s.piece, attempt.frame, min, max, &mut s.segs, &mut budget)
1836                };
1837                match verdict {
1838                    // (A piece grown past the tile's local frame is only a failed attempt.)
1839                    Verdict::Planar if check_local(s.piece.verts(), origin).is_ok() => {
1840                        return Ok(true);
1841                    }
1842                    Verdict::Planar | Verdict::Crossing => {}
1843                    Verdict::OverBudget => break,
1844                }
1845            }
1846        }
1847        if budget == 0 {
1848            break;
1849        }
1850    }
1851    // Nothing better within the budget: the plain clip, as it was.
1852    let built = attempt_piece(s, Attempt::PLAIN, &mut budget)?;
1853    debug_assert_ne!(built, Built::Failed, "the plain clip was built before");
1854    Ok(built == Built::Piece)
1855}
1856
1857/// Clip a polygon's `rings` to one `tile` into the scratch's piece buffer, and lend the piece; `None`
1858/// if the polygon leaves nothing in the tile. See [`Slicer::tile_polygon`](crate::Slicer::tile_polygon).
1859#[cfg_attr(feature = "hotpath", hotpath::measure)]
1860pub(crate) fn clip_polygon_to_tile<'s, V: PolyVertex, R: AsRef<[V]>>(
1861    grid: Grid,
1862    tile: TileId,
1863    rings: &'s [R],
1864    s: &'s mut PolyScratch<V>,
1865) -> Result<Option<PolygonPiece<'s, V, R>>, TileError> {
1866    let (min, max) = grid.tile_buffered_bounds(tile)?;
1867    // A lone small ring inside the tile's buffered box (a building, most often) is its piece there as
1868    // it is: lent, as `polygon` lends it, not clipped.
1869    if let [ring] = rings
1870        && let ring = ring.as_ref()
1871        && ring.len() <= LONE_RING
1872        && let Some(n) = ring_within(ring, min, max.x.wrapping_sub(min.x).cast_unsigned())
1873    {
1874        s.rings.clear();
1875        s.rings.push(RingInfo {
1876            input: 0,
1877            src: Src::Input,
1878            len: u32::try_from(n).unwrap_or(0),
1879            edge0: 0,
1880        });
1881        return Ok(Some(PolygonPiece {
1882            tile,
1883            rings: PieceRings::Whole {
1884                rings: &s.rings,
1885                input: rings,
1886                copies: &s.copies,
1887                origin: grid.origin_of(min),
1888            },
1889        }));
1890    }
1891    let Some(origin) = build_tile_piece(grid, min, max, rings, s)? else {
1892        return Ok(None);
1893    };
1894    Ok(Some(PolygonPiece {
1895        tile,
1896        rings: PieceRings::Built {
1897            verts: s.piece.verts(),
1898            ends: s.piece.ring_ends(),
1899            origin,
1900        },
1901    }))
1902}
1903
1904/// Clip a polygon's `rings` to the tile with buffered box `(min, max)` into the scratch's piece buffer
1905/// (tile-global frame), and return the tile's origin; `None` if the polygon leaves nothing in it.
1906/// A piece not planar outside the box is repaired.
1907#[inline(always)]
1908#[expect(
1909    clippy::inline_always,
1910    reason = "out of line, the one-tile call costs the polygon_one benchmark about 4%"
1911)]
1912fn build_tile_piece<V: PolyVertex, R: AsRef<[V]>>(
1913    grid: Grid,
1914    min: Coord<i32>,
1915    max: Coord<i32>,
1916    rings: &[R],
1917    s: &mut PolyScratch<V>,
1918) -> Result<Option<Coord<i32>>, TileError> {
1919    let origin = grid.origin_of(min);
1920    s.piece.clear();
1921    let Some((exterior, holes)) = rings.split_first() else {
1922        return Ok(None);
1923    };
1924    // If the exterior misses the tile entirely, the whole polygon is absent here.
1925    if clip_ring(exterior.as_ref(), min, max, &mut s.clip, &mut s.piece)? == RingClip::Outside {
1926        return Ok(None);
1927    }
1928    check_local(s.piece.verts(), origin)?;
1929    for hole in holes {
1930        let start = s.piece.len();
1931        match clip_ring(hole.as_ref(), min, max, &mut s.clip, &mut s.piece)? {
1932            // A hole covering the whole tile leaves nothing to draw here.
1933            RingClip::Covers => return Ok(None),
1934            RingClip::Clipped => check_local(&s.piece.verts()[start..], origin)?,
1935            RingClip::Outside => {}
1936        }
1937    }
1938    if !make_valid(rings, (min, max), origin, s)? {
1939        return Ok(None);
1940    }
1941    Ok(Some(origin))
1942}
1943
1944/// [`build_tile_piece`]'s plain clip, just built, made planar outside the box if it is not: `false`
1945/// if the polygon then leaves nothing in the tile. Out of line, to keep the plain clip's code small.
1946#[inline(never)]
1947fn make_valid<V: PolyVertex, R: AsRef<[V]>>(
1948    rings: &[R],
1949    (min, max): (Coord<i32>, Coord<i32>),
1950    origin: Coord<i32>,
1951    s: &mut PolyScratch<V>,
1952) -> Result<bool, TileError> {
1953    let Some(budget) = needs_repair(s, (min, max)) else {
1954        return Ok(true);
1955    };
1956    let whole_fits = fits_whole(rings);
1957    repair(s, (min, max), origin, rings.len(), whole_fits, budget, |s, a, b| {
1958        build_piece(rings, min, max, a, s, b)
1959    })
1960}
1961
1962/// A polygon's `rings` whole, lent in one `tile`'s local frame; `None` if the polygon leaves nothing
1963/// in the tile - the test [`clip_polygon_to_tile`] makes, without building the piece. See
1964/// [`Slicer::tile_polygon`](crate::Slicer::tile_polygon) in [`ClipMode::Unclipped`].
1965pub(crate) fn whole_polygon_in_tile<'s, V: PolyVertex, R: AsRef<[V]>>(
1966    grid: Grid,
1967    tile: TileId,
1968    rings: &'s [R],
1969    s: &'s mut PolyScratch<V>,
1970) -> Result<Option<PolygonPiece<'s, V, R>>, TileError> {
1971    let (min, max) = grid.tile_buffered_bounds(tile)?;
1972    let origin = grid.origin_of(min);
1973    s.rings.clear();
1974    s.copies.clear();
1975    for (index, ring) in (0_u32..).zip(rings) {
1976        // (Edge ids only index the sweep's rows.)
1977        let Some((info, lo, hi)) = load_ring(s, index, ring.as_ref(), 0)? else {
1978            if index == 0 {
1979                return Ok(None); // a degenerate exterior drops the polygon
1980            }
1981            continue;
1982        };
1983        match ring_meets_box(info.pts(rings, &s.copies), min, max) {
1984            // An exterior missing the tile, or a hole covering it, leaves nothing to draw here.
1985            RingClip::Outside if index == 0 => return Ok(None),
1986            RingClip::Covers if index > 0 => return Ok(None),
1987            RingClip::Outside | RingClip::Covers | RingClip::Clipped => {}
1988        }
1989        check_local(&[lo, hi], origin)?;
1990        s.rings.push(info);
1991    }
1992    if s.rings.is_empty() {
1993        return Ok(None); // no rings at all
1994    }
1995    Ok(Some(PolygonPiece {
1996        tile,
1997        rings: PieceRings::Whole {
1998            rings: &s.rings,
1999            input: rings,
2000            copies: &s.copies,
2001            origin,
2002        },
2003    }))
2004}