Skip to main content

map_tile_toolkit/
quantize.rs

1//! Rounding float polygons onto the integer grid without turning a valid polygon into an invalid one.
2
3use core::cmp::Ordering;
4use core::ops::{Add, AddAssign, Neg, Range, Sub, SubAssign};
5use std::collections::HashMap;
6use std::iter::once;
7
8use geo_types::Coord;
9
10use crate::TileError;
11use crate::geom::signed_area_2x;
12
13/// Fractional bits of the fixed-point coordinates a polygon is read into.
14const FRAC: u32 = 8;
15/// One grid unit in fixed point.
16const ONE: i64 = 1 << FRAC;
17/// Half a grid unit in fixed point.
18const HALF: i64 = ONE / 2;
19
20/// A coordinate in fixed point, [`ONE`] to a grid unit.
21type Fixed = Coord<i64>;
22/// A coordinate rounded to a grid point.
23type Pixel = Coord<i32>;
24
25/// Rounds float polygons onto the integer grid, keeping a valid polygon valid.
26///
27/// ```
28/// use geo_types::coord;
29/// use map_tile_toolkit::Quantizer;
30///
31/// let mut quantizer = Quantizer::new();
32/// let exterior = [coord! { x: 0.2, y: 0.1 }, coord! { x: 9.7, y: 0.4 }, coord! { x: 5.1, y: 8.6 }];
33/// let rounded = quantizer.polygon([exterior]).unwrap();
34/// let polygons: Vec<Vec<&[_]>> = rounded.polygons().map(Iterator::collect).collect();
35/// assert_eq!(polygons, [[&[coord! { x: 0, y: 0 }, coord! { x: 10, y: 0 }, coord! { x: 5, y: 9 }][..]]]);
36/// ```
37#[derive(Debug, Default, Clone)]
38pub struct Quantizer {
39    fixed: Vec<Fixed>,
40    fixed_ends: Vec<usize>,
41    fixed_polygon_ends: Vec<usize>,
42    rounded_at: Vec<Option<usize>>,
43    near_other_ring: Vec<bool>,
44    vertices: Vec<Pixel>,
45    ring_ends: Vec<usize>,
46    polygon_ends: Vec<usize>,
47    segs: Vec<Seg>,
48    lines: Vec<(Fixed, Fixed)>,
49    grid: Grid,
50    groups: PartGroups,
51    group: Option<Box<Self>>,
52}
53
54/// Reusable working memory that sorts a multipolygon's parts into groups that may round onto each other.
55#[derive(Debug, Default, Clone)]
56struct PartGroups {
57    boxes: Vec<(Pixel, Pixel)>,
58    starts: Vec<i32>,
59    ends: Vec<i32>,
60    roots: Vec<usize>,
61    order: Vec<usize>,
62    active: Vec<usize>,
63    grouped: Vec<(usize, usize)>,
64}
65
66impl PartGroups {
67    /// Groups the polygons whose rings end at `ring_ends` in `fixed` and that end at `polygon_ends`,
68    /// as `(first part, part)` pairs sorted by both: parts are grouped when the pixels their vertices
69    /// round into span touching boxes, directly or through other parts.
70    ///
71    /// Sweeps along the axis on which fewer pairs of boxes overlap, so a column of islands costs no more
72    /// than a row of them.
73    fn group(&mut self, fixed: &[Fixed], ring_ends: &[usize], polygon_ends: &[usize]) -> &[(usize, usize)] {
74        let Self {
75            boxes,
76            starts,
77            ends,
78            roots,
79            order,
80            active,
81            grouped,
82        } = self;
83        boxes.clear();
84        for rings in spans(polygon_ends) {
85            let vertices = span(ring_ends, rings.start).start..ring_ends[rings.end - 1];
86            let (min, max) = bounds(fixed[vertices].iter().copied()).expect("a part keeps its exterior");
87            boxes.push((pixel(min), pixel(max)));
88        }
89        let along_x = sweep_checks(boxes, |(lo, hi)| (lo.x, hi.x), starts, ends);
90        let along_y = sweep_checks(boxes, |(lo, hi)| (lo.y, hi.y), starts, ends);
91        if along_y < along_x {
92            for (lo, hi) in boxes.iter_mut() {
93                (*lo, *hi) = (Coord { x: lo.y, y: lo.x }, Coord { x: hi.y, y: hi.x });
94            }
95        }
96        roots.clear();
97        roots.extend(0..boxes.len());
98        order.clear();
99        order.extend(0..boxes.len());
100        order.sort_unstable_by_key(|&p| boxes[p].0.x);
101        active.clear();
102        for &p in &*order {
103            let (lo, hi) = boxes[p];
104            active.retain(|&q| boxes[q].1.x >= lo.x);
105            for &q in &*active {
106                if boxes[q].0.y <= hi.y && lo.y <= boxes[q].1.y {
107                    let (a, b) = (root(roots, p), root(roots, q));
108                    roots[a.max(b)] = a.min(b);
109                }
110            }
111            active.push(p);
112        }
113        grouped.clear();
114        for p in 0..boxes.len() {
115            let r = root(roots, p);
116            grouped.push((r, p));
117        }
118        grouped.sort_unstable();
119        grouped
120    }
121}
122
123/// How many pairs of `boxes` a sweep along the axis whose range `axis` gives would check: for each box,
124/// those starting no later that do not end before it starts.
125fn sweep_checks(
126    boxes: &[(Pixel, Pixel)],
127    axis: fn(&(Pixel, Pixel)) -> (i32, i32),
128    starts: &mut Vec<i32>,
129    ends: &mut Vec<i32>,
130) -> usize {
131    starts.clear();
132    ends.clear();
133    for b in boxes {
134        let (start, end) = axis(b);
135        starts.push(start);
136        ends.push(end);
137    }
138    starts.sort_unstable();
139    ends.sort_unstable();
140    starts
141        .iter()
142        .enumerate()
143        .map(|(i, &start)| i - ends.partition_point(|&end| end < start))
144        .sum()
145}
146
147/// The root of `p` in the forest `roots`, halving the path to it.
148fn root(roots: &mut [usize], mut p: usize) -> usize {
149    while roots[p] != p {
150        roots[p] = roots[roots[p]];
151        p = roots[p];
152    }
153    p
154}
155
156/// The polygons [`Quantizer::polygon`], [`Quantizer::multi_polygon`] or [`Quantizer::make_valid`] rounded into.
157#[derive(Debug, Clone, Copy)]
158pub struct Quantized<'a> {
159    quantizer: &'a Quantizer,
160}
161
162/// One edge of the rounded rings, with its ring, where that ring starts, and how many edges it has.
163#[derive(Debug, Clone, Copy)]
164struct Seg {
165    a: Pixel,
166    b: Pixel,
167    ring: usize,
168    ring_start: usize,
169    ring_len: usize,
170}
171
172impl Seg {
173    /// The edge with `i64` coordinates.
174    fn line(self) -> (Fixed, Fixed) {
175        (widen(self.a), widen(self.b))
176    }
177}
178
179/// An edge of the fixed-point rings with the winding its ring adds on its left.
180#[derive(Debug, Clone, Copy)]
181struct FixedEdge {
182    a: Fixed,
183    b: Fixed,
184    winding: Winding,
185}
186
187/// A rounded edge with how often the exterior and the holes run along it from `a` to `b`.
188#[derive(Debug, Clone, Copy)]
189struct NetEdge {
190    a: Pixel,
191    b: Pixel,
192    winding: Winding,
193}
194
195/// How many times the exterior and the holes wind around a point.
196#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
197struct Winding {
198    exterior: i32,
199    holes: i32,
200}
201
202impl Winding {
203    /// One turn of the exterior.
204    const EXTERIOR: Self = Self { exterior: 1, holes: 0 };
205    /// One turn of a hole.
206    const HOLE: Self = Self { exterior: 0, holes: 1 };
207
208    /// Whether the point is inside the exterior and outside every hole.
209    fn inside(self) -> bool {
210        self.exterior != 0 && self.holes == 0
211    }
212
213    /// Whether the point is inside more exteriors than holes: in some part of a valid multipolygon.
214    fn in_some_part(self) -> bool {
215        self.exterior + self.holes > 0
216    }
217}
218
219impl Add for Winding {
220    type Output = Self;
221
222    fn add(self, other: Self) -> Self {
223        Self {
224            exterior: self.exterior + other.exterior,
225            holes: self.holes + other.holes,
226        }
227    }
228}
229
230impl Sub for Winding {
231    type Output = Self;
232
233    fn sub(self, other: Self) -> Self {
234        self + -other
235    }
236}
237
238impl Neg for Winding {
239    type Output = Self;
240
241    fn neg(self) -> Self {
242        Self {
243            exterior: -self.exterior,
244            holes: -self.holes,
245        }
246    }
247}
248
249impl AddAssign for Winding {
250    fn add_assign(&mut self, other: Self) {
251        *self = *self + other;
252    }
253}
254
255impl SubAssign for Winding {
256    fn sub_assign(&mut self, other: Self) {
257        *self = *self - other;
258    }
259}
260
261impl Quantizer {
262    /// An empty quantizer.
263    #[must_use]
264    pub fn new() -> Self {
265        Self::default()
266    }
267
268    /// Rounds one valid polygon's `rings`, exterior first, in grid units, into valid polygons.
269    ///
270    /// # Errors
271    ///
272    /// [`TileError::Overflow`] if a coordinate is not finite or rounds outside the `i32` range.
273    pub fn polygon<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
274    where
275        R: IntoIterator,
276        R::Item: IntoIterator<Item = Coord<f64>>,
277    {
278        self.read(once(rings))?;
279        self.finish(Self::rounding_kept_valid, Winding::inside);
280        debug_assert!(
281            self.output_is_valid(),
282            "Quantizer::polygon was given an invalid polygon"
283        );
284        Ok(Quantized { quantizer: self })
285    }
286
287    /// Rounds a multipolygon's `polygons`, each its rings, exterior first, in grid units, into valid
288    /// polygons.
289    ///
290    /// Each polygon must be valid on its own, as for [`Self::polygon`], but they may touch or overlap:
291    /// parts whose rounded rings meet or overlap merge into one polygon.
292    ///
293    /// # Errors
294    ///
295    /// [`TileError::Overflow`] if a coordinate is not finite or rounds outside the `i32` range.
296    pub fn multi_polygon<P>(&mut self, polygons: P) -> Result<Quantized<'_>, TileError>
297    where
298        P: IntoIterator,
299        P::Item: IntoIterator,
300        <P::Item as IntoIterator>::Item: IntoIterator<Item = Coord<f64>>,
301    {
302        self.read(polygons)?;
303        let parts = self.fixed_polygon_ends.len();
304        let mut groups = std::mem::take(&mut self.groups);
305        let grouped: &[(usize, usize)] = if parts <= 1 {
306            &[]
307        } else {
308            groups.group(&self.fixed, &self.fixed_ends, &self.fixed_polygon_ends)
309        };
310        if grouped
311            .first()
312            .is_none_or(|&(first, _)| grouped.iter().all(|g| g.0 == first))
313        {
314            self.finish_group(parts);
315        } else {
316            let mut group = self.group.take().unwrap_or_default();
317            self.vertices.clear();
318            self.ring_ends.clear();
319            self.polygon_ends.clear();
320            for members in grouped.chunk_by(|a, b| a.0 == b.0) {
321                group.fixed.clear();
322                group.fixed_ends.clear();
323                group.fixed_polygon_ends.clear();
324                for &(_, p) in members {
325                    for r in span(&self.fixed_polygon_ends, p) {
326                        group.fixed.extend_from_slice(&self.fixed[span(&self.fixed_ends, r)]);
327                        group.fixed_ends.push(group.fixed.len());
328                    }
329                    group.fixed_polygon_ends.push(group.fixed_ends.len());
330                }
331                group.finish_group(members.len());
332                let (vertex_offset, ring_offset) = (self.vertices.len(), self.ring_ends.len());
333                self.vertices.extend_from_slice(&group.vertices);
334                self.ring_ends.extend(group.ring_ends.iter().map(|e| e + vertex_offset));
335                self.polygon_ends
336                    .extend(group.polygon_ends.iter().map(|e| e + ring_offset));
337            }
338            self.group = Some(group);
339        }
340        self.groups = groups;
341        debug_assert!(
342            self.output_is_valid(),
343            "Quantizer::multi_polygon was given a polygon that is not valid on its own"
344        );
345        Ok(Quantized { quantizer: self })
346    }
347
348    /// Rounds any polygon's `rings`, exterior first, in grid units, into valid polygons.
349    ///
350    /// The area kept is what the exterior covers, minus what any hole covers.
351    ///
352    /// # Errors
353    ///
354    /// [`TileError::Overflow`] if a coordinate is not finite or rounds outside the `i32` range.
355    pub fn make_valid<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
356    where
357        R: IntoIterator,
358        R::Item: IntoIterator<Item = Coord<f64>>,
359    {
360        self.read(once(rings))?;
361        self.finish(Self::rounded_is_valid, Winding::inside);
362        debug_assert!(self.output_is_valid(), "Quantizer::make_valid gave an invalid polygon");
363        Ok(Quantized { quantizer: self })
364    }
365
366    /// Rounds the polygons read, keeping the rounded rings if `still_valid` holds and repairing them
367    /// into the area where `inside` holds if not.
368    fn finish(&mut self, still_valid: fn(&mut Self) -> bool, inside: fn(Winding) -> bool) {
369        self.round();
370        if !self.ring_ends.is_empty() {
371            if still_valid(self) {
372                self.keep();
373            } else {
374                self.repair(inside);
375            }
376        }
377    }
378
379    /// Rounds a group of `parts` polygons read: one as [`Self::polygon`] does, more keeping the rounded
380    /// rings only if none of them meet, and their union if any do.
381    fn finish_group(&mut self, parts: usize) {
382        if parts == 1 {
383            self.finish(Self::rounding_kept_valid, Winding::inside);
384        } else {
385            self.finish(
386                |q| q.rounded_rings_apart() && q.output_is_valid(),
387                Winding::in_some_part,
388            );
389        }
390    }
391
392    /// Reads each of `polygons` with [`Self::read_polygon`].
393    fn read<P>(&mut self, polygons: P) -> Result<(), TileError>
394    where
395        P: IntoIterator,
396        P::Item: IntoIterator,
397        <P::Item as IntoIterator>::Item: IntoIterator<Item = Coord<f64>>,
398    {
399        self.fixed.clear();
400        self.fixed_ends.clear();
401        self.fixed_polygon_ends.clear();
402        for rings in polygons {
403            self.read_polygon(rings)?;
404        }
405        Ok(())
406    }
407
408    /// Reads `rings` into fixed point without repeated vertices, dropping rings with fewer than three,
409    /// and all of them when that is the exterior or there is none, and turning the exterior positive and
410    /// the holes negative.
411    fn read_polygon<R>(&mut self, rings: R) -> Result<(), TileError>
412    where
413        R: IntoIterator,
414        R::Item: IntoIterator<Item = Coord<f64>>,
415    {
416        let first_ring = self.fixed_ends.len();
417        for (i, ring) in rings.into_iter().enumerate() {
418            let start = self.fixed.len();
419            for c in ring {
420                let c = Coord {
421                    x: to_fixed(c.x)?,
422                    y: to_fixed(c.y)?,
423                };
424                push_new(&mut self.fixed, start, c);
425            }
426            drop_closing(&mut self.fixed, start);
427            if self.fixed.len() - start < 3 {
428                self.fixed.truncate(start);
429                if i == 0 {
430                    return Ok(());
431                }
432                continue;
433            }
434            let area = fixed_area_2x(&self.fixed[start..]);
435            if (i == 0 && area < 0) || (i > 0 && area > 0) {
436                self.fixed[start..].reverse();
437            }
438            self.fixed_ends.push(self.fixed.len());
439        }
440        if self.fixed_ends.len() > first_ring {
441            self.fixed_polygon_ends.push(self.fixed_ends.len());
442        }
443        Ok(())
444    }
445
446    /// Whether the rounded polygons are valid.
447    fn output_is_valid(&self) -> bool {
448        let vertices: Vec<Fixed> = self.vertices.iter().map(|&p| widen(p)).collect();
449        is_valid(&vertices, &self.ring_ends, &self.polygon_ends)
450    }
451
452    /// Rounds every vertex on its own, dropping the rings left with fewer than three, and a polygon's
453    /// rings when that is its exterior.
454    fn round(&mut self) {
455        self.vertices.clear();
456        self.ring_ends.clear();
457        self.polygon_ends.clear();
458        self.rounded_at.clear();
459        for rings in spans(&self.fixed_polygon_ends) {
460            let first_ring = self.ring_ends.len();
461            for r in rings.clone() {
462                let start = self.vertices.len();
463                let from = self.rounded_at.len();
464                for &c in &self.fixed[span(&self.fixed_ends, r)] {
465                    push_new(&mut self.vertices, start, pixel(c));
466                    self.rounded_at.push(Some(self.vertices.len() - 1));
467                }
468                if drop_closing(&mut self.vertices, start) {
469                    let last = Some(self.vertices.len());
470                    for at in &mut self.rounded_at[from..] {
471                        if *at == last {
472                            *at = Some(start);
473                        }
474                    }
475                }
476                if self.vertices.len() - start < 3 {
477                    self.vertices.truncate(start);
478                    if r == rings.start {
479                        self.rounded_at.truncate(from);
480                        self.rounded_at.resize(self.fixed_ends[rings.end - 1], None);
481                        break;
482                    }
483                    self.rounded_at[from..].fill(None);
484                    continue;
485                }
486                self.ring_ends.push(self.vertices.len());
487            }
488            if self.ring_ends.len() > first_ring {
489                self.polygon_ends.push(self.ring_ends.len());
490            }
491        }
492    }
493
494    /// Keeps the rounded rings as they are, each exterior turning positive and each hole negative.
495    fn keep(&mut self) {
496        for rings in spans(&self.polygon_ends) {
497            for r in rings.clone() {
498                let ring = &mut self.vertices[span(&self.ring_ends, r)];
499                if (signed_area_2x(ring) > 0) != (r == rings.start) {
500                    ring.reverse();
501                }
502            }
503        }
504    }
505
506    /// Lists the rounded edges, and tells whether no ring folds back onto itself at a vertex.
507    fn rounded_edges(&mut self) -> bool {
508        self.segs.clear();
509        for (ring, span) in spans(&self.ring_ends).enumerate() {
510            let ring_start = span.start;
511            let verts = &self.vertices[span];
512            let ring_len = verts.len();
513            for (k, &at) in verts.iter().enumerate() {
514                let (prev, next) = (verts[(k + ring_len - 1) % ring_len], verts[(k + 1) % ring_len]);
515                if folds(widen(prev), widen(at), widen(next)) {
516                    return false;
517                }
518                self.segs.push(Seg {
519                    a: at,
520                    b: next,
521                    ring,
522                    ring_start,
523                    ring_len,
524                });
525            }
526        }
527        true
528    }
529
530    /// Whether the polygon is valid in fixed point and stayed valid when rounded, checking only the
531    /// vertices within a unit of another edge.
532    fn rounding_kept_valid(&mut self) -> bool {
533        if !self.rounded_edges() {
534            return false;
535        }
536        self.near_other_ring.clear();
537        self.near_other_ring.resize(self.fixed.len(), false);
538        let Self {
539            fixed,
540            fixed_ends,
541            rounded_at,
542            near_other_ring,
543            segs,
544            grid,
545            ..
546        } = self;
547        let segs = &*segs;
548        let incident = |r: usize| {
549            let s = segs[r];
550            [
551                if r == s.ring_start {
552                    s.ring_start + s.ring_len - 1
553                } else {
554                    r - 1
555                },
556                r,
557            ]
558        };
559        let apart = |x: usize, y: usize| {
560            x == y || adjacent(segs, x, y) || contact(segs[x].line(), segs[y].line()) == Contact::Apart
561        };
562        let planar = near_vertices(fixed, fixed_ends, grid, |v, a, b| {
563            let (Some(rv), Some(ra)) = (rounded_at[v], rounded_at[a]) else {
564                return true;
565            };
566            if !edges_at_clear_of(fixed, fixed_ends, v, a, b) {
567                return false;
568            }
569            if segs[rv].ring != segs[ra].ring {
570                near_other_ring[v] = true;
571            }
572            let image = if rounded_at[b] == Some(ra) {
573                incident(ra)
574            } else {
575                [ra, ra]
576            };
577            incident(rv).iter().all(|&x| image.iter().all(|&y| apart(x, y)))
578        });
579        planar
580            && rings_of(rounded_at, fixed_ends)
581                .zip(rings_of(near_other_ring, fixed_ends))
582                .all(|(r, near)| r[0].is_none() || near.contains(&false))
583    }
584
585    /// Whether the rounded rings meet only where consecutive edges share a vertex, listing their edges
586    /// in `lines`.
587    fn rounded_rings_apart(&mut self) -> bool {
588        if !self.rounded_edges() {
589            return false;
590        }
591        let segs = &self.segs;
592        self.lines.clear();
593        self.lines.extend(segs.iter().map(|s| s.line()));
594        let lines = &self.lines;
595        near_pairs(lines, &mut self.grid, |i, j| {
596            adjacent(segs, i, j) || contact(lines[i], lines[j]) == Contact::Apart
597        })
598    }
599
600    /// Whether the rounded rings meet only where consecutive edges share a vertex, with every hole
601    /// inside the exterior and outside the other holes.
602    fn rounded_is_valid(&mut self) -> bool {
603        if !self.rounded_rings_apart() {
604            return false;
605        }
606        let (segs, lines) = (&self.segs, &self.lines);
607        if self.ring_ends.len() == 1 {
608            return true;
609        }
610        let edges: Vec<(Fixed, Fixed)> = lines.iter().map(|&(a, b)| left_first(a, b)).collect();
611        let hole_starts = &self.ring_ends[..self.ring_ends.len() - 1];
612        let queries: Vec<Fixed> = hole_starts.iter().map(|&s| widen(self.vertices[s]) * 2).collect();
613        let mut hits = Vec::new();
614        rays_up(&edges, &queries, |q, e| {
615            if segs[e].ring != q + 1 {
616                hits.push((q, segs[e].ring));
617            }
618        });
619        let around = odd_runs(hits);
620        around.len() == queries.len()
621            && around
622                .iter()
623                .enumerate()
624                .all(|(q, &(hole, ring))| hole == q && ring == 0)
625    }
626
627    /// Snap-rounds the polygons and rebuilds the area where `inside` holds as valid polygons.
628    fn repair(&mut self, inside: fn(Winding) -> bool) {
629        self.vertices.clear();
630        self.ring_ends.clear();
631        self.polygon_ends.clear();
632        let mut edges = Vec::new();
633        for rings in spans(&self.fixed_polygon_ends) {
634            for r in rings.clone() {
635                let ring = &self.fixed[span(&self.fixed_ends, r)];
636                let winding = if r == rings.start {
637                    Winding::EXTERIOR
638                } else {
639                    Winding::HOLE
640                };
641                for (k, &a) in ring.iter().enumerate() {
642                    let b = ring[(k + 1) % ring.len()];
643                    edges.push(FixedEdge { a, b, winding });
644                }
645            }
646        }
647        let hot = hot_pixels(&edges);
648        let net = net_edges(&edges, &hot);
649        let rings = trace(boundary(&net, inside));
650        self.assemble(rings);
651    }
652
653    /// Groups traced rings into polygons: each hole goes to the smallest exterior around it.
654    fn assemble(&mut self, rings: Vec<Vec<Pixel>>) {
655        let (shells, holes): (Vec<_>, Vec<_>) = rings.into_iter().partition(|r| signed_area_2x(r) > 0);
656        let mut owner = vec![Some(0); holes.len()];
657        if shells.len() > 1 && !holes.is_empty() {
658            let mut edges = Vec::new();
659            let mut ring_of = Vec::new();
660            for (s, shell) in shells.iter().enumerate() {
661                for (k, &a) in shell.iter().enumerate() {
662                    edges.push(left_first(widen(a), widen(shell[(k + 1) % shell.len()])));
663                    ring_of.push(s);
664                }
665            }
666            let queries: Vec<Fixed> = holes.iter().map(|h| widen(h[0]) + widen(h[1])).collect();
667            let mut hits = Vec::new();
668            rays_up(&edges, &queries, |q, e| hits.push((q, ring_of[e])));
669            let areas: Vec<i128> = shells.iter().map(|s| signed_area_2x(s)).collect();
670            owner.fill(None);
671            for (hole, shell) in odd_runs(hits) {
672                if owner[hole].is_none_or(|o| areas[shell] < areas[o]) {
673                    owner[hole] = Some(shell);
674                }
675            }
676        }
677        for (s, shell) in shells.iter().enumerate() {
678            self.vertices.extend_from_slice(shell);
679            self.ring_ends.push(self.vertices.len());
680            for (hole, _) in holes.iter().zip(&owner).filter(|&(_, &o)| o == Some(s)) {
681                self.vertices.extend_from_slice(hole);
682                self.ring_ends.push(self.vertices.len());
683            }
684            self.polygon_ends.push(self.ring_ends.len());
685        }
686    }
687}
688
689/// Appends `v` to the ring starting at `start` unless it repeats the ring's last vertex.
690fn push_new<T: PartialEq>(verts: &mut Vec<T>, start: usize, v: T) {
691    if verts.len() == start || verts.last() != Some(&v) {
692        verts.push(v);
693    }
694}
695
696/// Drops the last vertex of the ring starting at `start` if it repeats the first, telling whether it did.
697fn drop_closing<T: PartialEq>(verts: &mut Vec<T>, start: usize) -> bool {
698    let closes = verts.len() > start + 1 && verts.last() == verts.get(start);
699    if closes {
700        verts.pop();
701    }
702    closes
703}
704
705/// Whether both edges at vertex `v` meet the edge from vertex `a` to vertex `b` only as a valid
706/// polygon's edges can.
707fn edges_at_clear_of(verts: &[Fixed], ends: &[usize], v: usize, a: usize, b: usize) -> bool {
708    let ring = span(ends, ends.partition_point(|&e| e <= v));
709    let prev = if v == ring.start { ring.end - 1 } else { v - 1 };
710    let next = if v + 1 == ring.end { ring.start } else { v + 1 };
711    let same_ring = ring.contains(&a);
712    [(prev, v), (v, next)]
713        .into_iter()
714        .all(|(x, y)| match contact((verts[x], verts[y]), (verts[a], verts[b])) {
715            Contact::Apart => true,
716            Contact::Point => !same_ring || x == b || y == a,
717            Contact::Cross | Contact::Overlap => false,
718        })
719}
720
721/// Whether two rounded edges follow each other around a ring.
722fn adjacent(segs: &[Seg], i: usize, j: usize) -> bool {
723    segs[i].ring == segs[j].ring && (i.abs_diff(j) == 1 || i.abs_diff(j) == segs[i].ring_len - 1)
724}
725
726impl<'a> Quantized<'a> {
727    /// Each polygon's rings, exterior first, open: exteriors have a positive [`signed_area_2x`], holes a
728    /// negative one.
729    ///
730    /// [`signed_area_2x`]: crate::signed_area_2x
731    pub fn polygons(self) -> impl Iterator<Item = impl Iterator<Item = &'a [Pixel]> + 'a> + 'a {
732        let q = self.quantizer;
733        spans(&q.polygon_ends).map(move |rings| rings.map(move |r| &q.vertices[span(&q.ring_ends, r)]))
734    }
735}
736
737/// The index range of the `i`th ring or polygon of those ending at `ends`.
738fn span(ends: &[usize], i: usize) -> Range<usize> {
739    let start = if i == 0 { 0 } else { ends[i - 1] };
740    start..ends[i]
741}
742
743/// The index range of each ring or polygon of those ending at `ends`.
744fn spans(ends: &[usize]) -> impl Iterator<Item = Range<usize>> + '_ {
745    (0..ends.len()).map(|i| span(ends, i))
746}
747
748/// The rings of `verts` that end at `ends`.
749fn rings_of<'a, T>(verts: &'a [T], ends: &'a [usize]) -> impl Iterator<Item = &'a [T]> {
750    spans(ends).map(|span| &verts[span])
751}
752
753/// `v` in fixed point, if its pixel fits `i32`, never on a half `v` is not on.
754#[expect(clippy::cast_possible_truncation, reason = "range-checked before the cast")]
755#[expect(clippy::cast_precision_loss, reason = "ONE and HALF are small powers of two")]
756fn to_fixed(v: f64) -> Result<i64, TileError> {
757    /// Adding and taking away `1.5 · 2^52` rounds anything below `2^51` to a whole number, ties to even.
758    const ROUND: f64 = 6_755_399_441_055_744.0;
759    let scaled = v * ONE as f64;
760    let mut f = (scaled + ROUND) - ROUND;
761    #[expect(
762        clippy::float_cmp,
763        reason = "exact on purpose: only a rounded `f` may move off a half"
764    )]
765    let rounded_onto_a_half = f != scaled && f.rem_euclid(ONE as f64) == HALF as f64;
766    if rounded_onto_a_half {
767        f += (scaled - f).signum();
768    }
769    let lo = f64::from(i32::MIN) * ONE as f64 - HALF as f64;
770    let hi = (f64::from(i32::MAX) + 1.0) * ONE as f64 - HALF as f64;
771    if f >= lo && f < hi {
772        Ok(f as i64)
773    } else {
774        Err(TileError::Overflow)
775    }
776}
777
778/// The pixel holding a fixed-point coordinate: the nearest grid point, halves to the even one as `PostGIS`
779/// rounds. Along each axis, pixel `c` holds `[c - ½, c + ½]` when `c` is even and `(c - ½, c + ½)` when odd.
780#[expect(clippy::cast_possible_truncation, reason = "to_fixed keeps every pixel in i32")]
781fn pixel(c: Fixed) -> Pixel {
782    // A tie rounds down from an even unit and up from an odd one; branch-free, as a `match` mispredicts.
783    let unit = |v: i64| ((v + HALF - 1 + ((v >> FRAC) & 1)) >> FRAC) as i32;
784    Coord {
785        x: unit(c.x),
786        y: unit(c.y),
787    }
788}
789
790/// `numerator / denominator` (`denominator > 0`) rounded to the nearest integer, halves to the even one.
791fn round_ratio(numerator: i128, denominator: i128) -> i128 {
792    let quotient = numerator.div_euclid(denominator);
793    let remainder = numerator.rem_euclid(denominator);
794    match (2 * remainder).cmp(&denominator) {
795        Ordering::Less => quotient,
796        Ordering::Greater => quotient + 1,
797        Ordering::Equal => quotient + quotient.rem_euclid(2),
798    }
799}
800
801/// `p` with `i64` coordinates.
802fn widen(p: Pixel) -> Coord<i64> {
803    Coord {
804        x: i64::from(p.x),
805        y: i64::from(p.y),
806    }
807}
808
809/// The lowest and highest corners of the box around `points`.
810fn bounds(mut points: impl Iterator<Item = Fixed>) -> Option<(Fixed, Fixed)> {
811    let first = points.next()?;
812    Some(points.fold((first, first), |(min, max), c| {
813        (
814            Coord {
815                x: min.x.min(c.x),
816                y: min.y.min(c.y),
817            },
818            Coord {
819                x: max.x.max(c.x),
820                y: max.y.max(c.y),
821            },
822        )
823    }))
824}
825
826/// Reusable working memory of [`near_pairs`].
827#[derive(Debug, Default, Clone)]
828struct Grid {
829    cells: Vec<(u64, usize)>,
830    lengths: Vec<i64>,
831    columns: Vec<usize>,
832    points: Vec<(usize, usize)>,
833}
834
835/// Whether `test(i, j)` holds for every two of `lines` that pass through a common cell of a grid sized
836/// to their typical length, stopping at the first that fails.
837fn near_pairs(lines: &[(Coord<i64>, Coord<i64>)], grid: &mut Grid, mut test: impl FnMut(usize, usize) -> bool) -> bool {
838    let Grid { cells, lengths, .. } = grid;
839    cells.clear();
840    lengths.clear();
841    let Some((min, max)) = bounds(lines.iter().flat_map(|&(a, b)| [a, b])) else {
842        return true;
843    };
844    lengths.extend(lines.iter().map(|&(a, b)| (b.x - a.x).abs().max((b.y - a.y).abs())));
845    let size = cell_size(lengths, min, max, 1);
846    let cell = |v: i64, o: i64| u64::try_from((v - o) / size).unwrap_or(0);
847    let rows = cell(max.y, min.y) + 1;
848    for (i, &(a, b)) in lines.iter().enumerate() {
849        let (a, b) = if a.x <= b.x { (a, b) } else { (b, a) };
850        let (lo, hi) = (a.y.min(b.y), a.y.max(b.y));
851        let (c0, c1) = (cell(a.x, min.x), cell(b.x, min.x));
852        if c0 == c1 {
853            for cy in cell(lo, min.y)..=cell(hi, min.y) {
854                cells.push((c0 * rows + cy, i));
855            }
856            continue;
857        }
858        #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
859        let at = |x: i64| a.y as f64 + (b.y - a.y) as f64 * ((x - a.x) as f64 / (b.x - a.x) as f64);
860        let mut x0 = a.x;
861        for cx in c0..=c1 {
862            let x1 = (min.x + i64::try_from(cx + 1).unwrap_or(i64::MAX).saturating_mul(size)).min(b.x);
863            let (left, right) = (at(x0), at(x1));
864            #[expect(clippy::cast_possible_truncation, reason = "clamped to the segment's own span")]
865            let (y0, y1) = (
866                (left.min(right).floor() as i64 - 1).max(lo),
867                (left.max(right).ceil() as i64 + 1).min(hi),
868            );
869            for cy in cell(y0, min.y)..=cell(y1, min.y) {
870                cells.push((cx * rows + cy, i));
871            }
872            x0 = x1;
873        }
874    }
875    cells.sort_unstable_by_key(|c| c.0);
876    for group in cells.chunk_by(|p, q| p.0 == q.0) {
877        for (k, p) in group.iter().enumerate() {
878            for q in &group[k + 1..] {
879                if !test(p.1, q.1) {
880                    return false;
881                }
882            }
883        }
884    }
885    true
886}
887
888/// The cell size of a grid over the box from `min` to `max`: the median of `lengths`, but at least
889/// `floor` and big enough to hold the box in twice as many cells per axis as there are lengths.
890fn cell_size(lengths: &mut [i64], min: Fixed, max: Fixed, floor: i64) -> i64 {
891    let mid = lengths.len() / 2;
892    let median = *lengths.select_nth_unstable(mid).1;
893    let n = i64::try_from(lengths.len()).unwrap_or(i64::MAX);
894    median
895        .max((max.x - min.x).max(max.y - min.y) / n.saturating_mul(2))
896        .max(floor)
897}
898
899/// Up to this many vertices, [`near_vertices`] checks every vertex against every edge.
900/// Building the grid costs more than it saves for values below it.
901const GRID_MIN_VERTICES: usize = 32;
902
903/// Whether `test(v, a, b)` holds for every vertex `v` within a unit of an edge from vertex `a` to vertex
904/// `b` of the rings ending at `ends`, stopping at the first that fails.
905fn near_vertices(
906    verts: &[Fixed],
907    ends: &[usize],
908    grid: &mut Grid,
909    mut test: impl FnMut(usize, usize, usize) -> bool,
910) -> bool {
911    let Grid {
912        lengths,
913        columns,
914        points,
915        ..
916    } = grid;
917    let edges = || {
918        spans(ends)
919            .flat_map(|Range { start, end }| (start..end).map(move |k| (k, if k + 1 == end { start } else { k + 1 })))
920    };
921    if verts.len() <= GRID_MIN_VERTICES {
922        return edges().all(|(a, b)| {
923            let (p, q) = (verts[a], verts[b]);
924            verts
925                .iter()
926                .enumerate()
927                .all(|(v, &c)| v == a || v == b || !passes_near(p, q, c) || test(v, a, b))
928        });
929    }
930    lengths.clear();
931    columns.clear();
932    points.clear();
933    let Some((min, max)) = bounds(verts.iter().copied()) else {
934        return true;
935    };
936    lengths.extend(edges().map(|(a, b)| {
937        let d = verts[b] - verts[a];
938        d.x.abs().max(d.y.abs())
939    }));
940    let shift = cell_size(lengths, min, max, ONE)
941        .unsigned_abs()
942        .next_power_of_two()
943        .trailing_zeros()
944        + 1;
945    let cell = |v: i64, o: i64| usize::try_from((v - o) >> shift).unwrap_or(0);
946    let (cols, rows) = (cell(max.x, min.x) + 1, cell(max.y, min.y) + 1);
947    let (column, row) = (
948        |x: i64| cell(x, min.x).min(cols - 1),
949        |y: i64| cell(y, min.y).min(rows - 1),
950    );
951    columns.resize(cols + 1, 0);
952    for c in verts {
953        columns[column(c.x) + 1] += 1;
954    }
955    for k in 1..=cols {
956        columns[k] += columns[k - 1];
957    }
958    points.resize(verts.len(), (0, 0));
959    for (i, c) in verts.iter().enumerate() {
960        let next = &mut columns[column(c.x)];
961        points[*next] = (row(c.y), i);
962        *next += 1;
963    }
964    columns.pop();
965    columns.insert(0, 0);
966    for k in 0..cols {
967        points[columns[k]..columns[k + 1]].sort_unstable_by_key(|p| p.0);
968    }
969    for (a, b) in edges() {
970        let (p, q) = (verts[a], verts[b]);
971        let (l, r) = if p.x <= q.x { (p, q) } else { (q, p) };
972        let (lo, hi) = (l.y.min(r.y), l.y.max(r.y));
973        #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
974        let at = |x: i64| l.y as f64 + (r.y - l.y) as f64 * ((x - l.x) as f64 / (r.x - l.x) as f64);
975        let (c0, c1) = (column(l.x - ONE), column(r.x + ONE));
976        for cx in c0..=c1 {
977            #[expect(clippy::cast_possible_truncation, reason = "clamped to the edge's own span")]
978            let (y0, y1) = if c1 - c0 <= 2 {
979                (lo, hi)
980            } else {
981                let x0 = min.x + (i64::try_from(cx).unwrap_or(i64::MAX) << shift);
982                let (xa, xb) = ((x0 - ONE).clamp(l.x, r.x), (x0 + (1 << shift) + ONE).clamp(l.x, r.x));
983                let (ya, yb) = (at(xa), at(xb));
984                ((ya.min(yb) as i64 - 2).max(lo), (ya.max(yb) as i64 + 2).min(hi))
985            };
986            let (r0, r1) = (row(y0 - ONE), row(y1 + ONE));
987            let col = &points[columns[cx]..columns[cx + 1]];
988            for &(y, v) in &col[col.partition_point(|p| p.0 < r0)..] {
989                if y > r1 {
990                    break;
991                }
992                if v != a && v != b && passes_near(p, q, verts[v]) && !test(v, a, b) {
993                    return false;
994                }
995            }
996        }
997    }
998    true
999}
1000
1001/// Whether the edge `a`-`b` passes within a unit of `v` along both axes.
1002fn passes_near(a: Fixed, b: Fixed, v: Fixed) -> bool {
1003    if a.x.min(b.x) > v.x + ONE || a.x.max(b.x) < v.x - ONE || a.y.min(b.y) > v.y + ONE || a.y.max(b.y) < v.y - ONE {
1004        return false;
1005    }
1006    let d = b - a;
1007    cross(d, v - a).abs() <= i128::from(ONE) * i128::from(d.x.abs() + d.y.abs())
1008}
1009
1010/// How two edges meet.
1011#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1012enum Contact {
1013    /// Not at all.
1014    Apart,
1015    /// At one point only, an end of one of them.
1016    Point,
1017    /// Crossing inside both.
1018    Cross,
1019    /// Along a stretch.
1020    Overlap,
1021}
1022
1023/// How the edges `p1`-`p2` and `q1`-`q2` meet.
1024fn contact((p1, p2): (Fixed, Fixed), (q1, q2): (Fixed, Fixed)) -> Contact {
1025    let boxed = |c: Fixed, a: Fixed, b: Fixed| {
1026        c.x >= a.x.min(b.x) && c.x <= a.x.max(b.x) && c.y >= a.y.min(b.y) && c.y <= a.y.max(b.y)
1027    };
1028    let side = |a: Fixed, b: Fixed, c: Fixed| cross(b - a, c - a).signum();
1029    let (s1, s2) = (side(p1, p2, q1), side(p1, p2, q2));
1030    let (s3, s4) = (side(q1, q2, p1), side(q1, q2, p2));
1031    if s1 * s2 < 0 && s3 * s4 < 0 {
1032        return Contact::Cross;
1033    }
1034    if s1 == 0 && s2 == 0 {
1035        let key = |c: Fixed| if p1.x == p2.x { c.y } else { c.x };
1036        let lo = key(p1).min(key(p2)).max(key(q1).min(key(q2)));
1037        let hi = key(p1).max(key(p2)).min(key(q1).max(key(q2)));
1038        return match lo.cmp(&hi) {
1039            Ordering::Less => Contact::Overlap,
1040            Ordering::Equal => Contact::Point,
1041            Ordering::Greater => Contact::Apart,
1042        };
1043    }
1044    let touches = (s1 == 0 && boxed(q1, p1, p2))
1045        || (s2 == 0 && boxed(q2, p1, p2))
1046        || (s3 == 0 && boxed(p1, q1, q2))
1047        || (s4 == 0 && boxed(p2, q1, q2));
1048    if touches { Contact::Point } else { Contact::Apart }
1049}
1050
1051/// Whether the polygons' rings are simple, cross no other ring, and nest as exteriors and holes:
1052/// what an OGC-valid multipolygon needs, short of a connected interior.
1053fn is_valid(verts: &[Fixed], ring_ends: &[usize], polygon_ends: &[usize]) -> bool {
1054    let mut lines = Vec::new();
1055    let mut ring_of = Vec::new();
1056    for (r, ring) in rings_of(verts, ring_ends).enumerate() {
1057        let n = ring.len();
1058        if n < 3 {
1059            return false;
1060        }
1061        for k in 0..n {
1062            let (prev, at, next) = (ring[(k + n - 1) % n], ring[k], ring[(k + 1) % n]);
1063            if folds(prev, at, next) {
1064                return false;
1065            }
1066            lines.push((at, next));
1067            ring_of.push(r);
1068        }
1069    }
1070    let ring_len = |r: usize| span(ring_ends, r).len();
1071    let simple = near_pairs(&lines, &mut Grid::default(), |i, j| match contact(lines[i], lines[j]) {
1072        Contact::Apart => true,
1073        Contact::Point => ring_of[i] != ring_of[j] || i.abs_diff(j) == 1 || i.abs_diff(j) == ring_len(ring_of[i]) - 1,
1074        Contact::Cross | Contact::Overlap => false,
1075    });
1076    if !simple {
1077        return false;
1078    }
1079    let mut polygon_of = Vec::new();
1080    let mut shell_of = Vec::new();
1081    for (p, rings) in spans(polygon_ends).enumerate() {
1082        polygon_of.extend(core::iter::repeat_n(p, rings.len()));
1083        shell_of.extend(core::iter::repeat_n(rings.start, rings.len()));
1084    }
1085    let edges: Vec<(Fixed, Fixed)> = lines.iter().map(|&(a, b)| left_first(a, b)).collect();
1086    let queries: Vec<Fixed> = rings_of(verts, ring_ends).map(|r| r[0] + r[1]).collect();
1087    let mut hits = Vec::new();
1088    rays_up(&edges, &queries, |q, e| {
1089        if ring_of[e] != q {
1090            hits.push((q, ring_of[e]));
1091        }
1092    });
1093    let around = odd_runs(hits);
1094    let mut held = vec![false; queries.len()];
1095    for group in around.chunk_by(|a, b| a.0 == b.0 && polygon_of[a.1] == polygon_of[b.1]) {
1096        let (q, r) = group[0];
1097        if polygon_of[r] != polygon_of[q] {
1098            if group.len() != 2 || shell_of[r] != r {
1099                return false;
1100            }
1101        } else if shell_of[q] == q || group != [(q, shell_of[q])] {
1102            return false;
1103        } else {
1104            held[q] = true;
1105        }
1106    }
1107    (0..queries.len()).all(|q| shell_of[q] == q || held[q])
1108}
1109
1110/// Whether a ring turns straight back at `at`, coming from `prev` and going on to `next`.
1111fn folds(prev: Fixed, at: Fixed, next: Fixed) -> bool {
1112    let (back, ahead) = (prev - at, next - at);
1113    cross(back, ahead) == 0 && dot(back, ahead) > 0
1114}
1115
1116/// The edge from `a` to `b` with its lower `(x, y)` end first.
1117fn left_first(a: Fixed, b: Fixed) -> (Fixed, Fixed) {
1118    if (a.x, a.y) <= (b.x, b.y) { (a, b) } else { (b, a) }
1119}
1120
1121/// The cross product of `a` and `b`.
1122fn cross(a: Fixed, b: Fixed) -> i128 {
1123    i128::from(a.x) * i128::from(b.y) - i128::from(a.y) * i128::from(b.x)
1124}
1125
1126/// The dot product of `a` and `b`.
1127fn dot(a: Fixed, b: Fixed) -> i128 {
1128    i128::from(a.x) * i128::from(b.x) + i128::from(a.y) * i128::from(b.y)
1129}
1130
1131/// Twice the signed area of a fixed-point ring.
1132fn fixed_area_2x(ring: &[Fixed]) -> i128 {
1133    let o = ring[0];
1134    ring.windows(2).map(|w| cross(w[0] - o, w[1] - o)).sum()
1135}
1136
1137/// Every pixel holding a vertex or a point where two edges cross, sorted.
1138fn hot_pixels(edges: &[FixedEdge]) -> Vec<Pixel> {
1139    let mut hot: Vec<Pixel> = edges.iter().map(|e| pixel(e.a)).collect();
1140    let lines: Vec<(Fixed, Fixed)> = edges.iter().map(|e| (e.a, e.b)).collect();
1141    near_pairs(&lines, &mut Grid::default(), |i, j| {
1142        if contact(lines[i], lines[j]) == Contact::Cross {
1143            let ((p1, p2), (q1, q2)) = (lines[i], lines[j]);
1144            hot.push(crossing(p1, p2 - p1, q1, q2 - q1));
1145        }
1146        true
1147    });
1148    hot.sort_unstable_by_key(|p| (p.x, p.y));
1149    hot.dedup();
1150    hot
1151}
1152
1153/// The pixel of the point where `p + t·d` crosses `q + s·e`, for two edges known to cross.
1154#[expect(
1155    clippy::cast_possible_truncation,
1156    reason = "the crossing lies on both edges, so in i32"
1157)]
1158fn crossing(p: Fixed, d: Fixed, q: Fixed, e: Fixed) -> Pixel {
1159    let (mut num, mut den) = (cross(q - p, e), cross(d, e));
1160    if den < 0 {
1161        (num, den) = (-num, -den);
1162    }
1163    let at = |p: i64, d: i64| {
1164        let numerator = i128::from(p) * den + num * i128::from(d);
1165        let denominator = den * i128::from(ONE);
1166        round_ratio(numerator, denominator) as i32
1167    };
1168    Coord {
1169        x: at(p.x, d.x),
1170        y: at(p.y, d.y),
1171    }
1172}
1173
1174/// A bound on the parameter `t = n / d` (`d > 0`) of a point along an edge.
1175#[derive(Clone, Copy)]
1176struct Bound {
1177    n: i128,
1178    d: i128,
1179    open: bool,
1180}
1181
1182impl Bound {
1183    /// Orders two bounds by their parameter.
1184    fn cmp(self, other: Self) -> Ordering {
1185        (self.n * other.d).cmp(&(other.n * self.d))
1186    }
1187}
1188
1189/// Whether the edge `p`-`q` passes through pixel `h`.
1190fn passes(p: Fixed, q: Fixed, h: Pixel) -> bool {
1191    let mut lo = Bound {
1192        n: 0,
1193        d: 1,
1194        open: false,
1195    };
1196    let mut hi = Bound {
1197        n: 1,
1198        d: 1,
1199        open: false,
1200    };
1201    for (p0, d, c) in [(p.x, q.x - p.x, h.x), (p.y, q.y - p.y, h.y)] {
1202        let (min, max) = (i64::from(c) * ONE - HALF, i64::from(c) * ONE + HALF);
1203        // Halves round to the even pixel, so an odd one leaves out both ends of its span.
1204        let open = c % 2 != 0;
1205        let inside = if open {
1206            min < p0 && p0 < max
1207        } else {
1208            min <= p0 && p0 <= max
1209        };
1210        let (from, to) = match d.cmp(&0) {
1211            Ordering::Equal if inside => continue,
1212            Ordering::Equal => return false,
1213
1214            Ordering::Greater => (
1215                Bound {
1216                    n: (min - p0).into(),
1217                    d: d.into(),
1218                    open,
1219                },
1220                Bound {
1221                    n: (max - p0).into(),
1222                    d: d.into(),
1223                    open,
1224                },
1225            ),
1226            Ordering::Less => (
1227                Bound {
1228                    n: (p0 - max).into(),
1229                    d: (-d).into(),
1230                    open,
1231                },
1232                Bound {
1233                    n: (p0 - min).into(),
1234                    d: (-d).into(),
1235                    open,
1236                },
1237            ),
1238        };
1239        match from.cmp(lo) {
1240            Ordering::Greater => lo = from,
1241            Ordering::Equal => lo.open |= from.open,
1242            Ordering::Less => {}
1243        }
1244        match to.cmp(hi) {
1245            Ordering::Less => hi = to,
1246            Ordering::Equal => hi.open |= to.open,
1247            Ordering::Greater => {}
1248        }
1249    }
1250    match lo.cmp(hi) {
1251        Ordering::Less => true,
1252        Ordering::Equal => !lo.open && !hi.open,
1253        Ordering::Greater => false,
1254    }
1255}
1256
1257/// Each edge snapped through the hot pixels it passes, summed per rounded edge, keeping those that
1258/// some ring still runs along.
1259fn net_edges(edges: &[FixedEdge], hot: &[Pixel]) -> Vec<NetEdge> {
1260    let mut frags = Vec::new();
1261    let mut path: Vec<(i128, Pixel)> = Vec::new();
1262    for &FixedEdge { a: p, b: q, winding } in edges {
1263        let (pp, pq) = (pixel(p), pixel(q));
1264        if pp == pq {
1265            continue;
1266        }
1267        let (lo, hi) = (
1268            pixel(Coord {
1269                x: p.x.min(q.x),
1270                y: p.y.min(q.y),
1271            }),
1272            pixel(Coord {
1273                x: p.x.max(q.x),
1274                y: p.y.max(q.y),
1275            }),
1276        );
1277        let from = hot.partition_point(|h| h.x < lo.x);
1278        let to = hot.partition_point(|h| h.x <= hi.x);
1279        path.clear();
1280        path.push((i128::MIN, pp));
1281        for &h in &hot[from..to] {
1282            if (lo.y..=hi.y).contains(&h.y) && h != pp && h != pq && passes(p, q, h) {
1283                path.push((dot(widen(h) * ONE - p, q - p), h));
1284            }
1285        }
1286        path.sort_unstable_by_key(|s| s.0);
1287        path.push((i128::MAX, pq));
1288        for w in path.windows(2) {
1289            let (a, b) = (w[0].1, w[1].1);
1290            frags.push(if (a.x, a.y) < (b.x, b.y) {
1291                NetEdge { a, b, winding }
1292            } else {
1293                NetEdge {
1294                    a: b,
1295                    b: a,
1296                    winding: -winding,
1297                }
1298            });
1299        }
1300    }
1301    frags.sort_unstable_by_key(|f| (f.a.x, f.a.y, f.b.x, f.b.y));
1302    let mut net: Vec<NetEdge> = Vec::new();
1303    for f in frags {
1304        match net.last_mut() {
1305            Some(n) if n.a == f.a && n.b == f.b => n.winding += f.winding,
1306            _ => net.push(f),
1307        }
1308    }
1309    net.retain(|n| n.winding != Winding::default());
1310    net
1311}
1312
1313/// Calls `hit(query, edge)` for each edge, given left end first, that the upward ray from just right of
1314/// each query point, in doubled coordinates, crosses.
1315fn rays_up(edges: &[(Fixed, Fixed)], queries: &[Fixed], mut hit: impl FnMut(usize, usize)) {
1316    let x2 = |v: i64| 2 * v;
1317    let mut order: Vec<usize> = (0..edges.len()).filter(|&e| edges[e].0.x != edges[e].1.x).collect();
1318    order.sort_unstable_by_key(|&e| edges[e].0.x);
1319    let mut by_x: Vec<usize> = (0..queries.len()).collect();
1320    by_x.sort_unstable_by_key(|&q| queries[q].x);
1321    let mut active: Vec<usize> = Vec::new();
1322    let mut next = 0;
1323    for q in by_x {
1324        let m = queries[q];
1325        while next < order.len() && x2(edges[order[next]].0.x) <= m.x {
1326            active.push(order[next]);
1327            next += 1;
1328        }
1329        active.retain(|&e| x2(edges[e].1.x) > m.x);
1330        for &e in &active {
1331            let (l, r) = (edges[e].0 * 2, edges[e].1 * 2);
1332            if cross(r - l, m - l) < 0 {
1333                hit(q, e);
1334            }
1335        }
1336    }
1337}
1338
1339/// The `(query, ring)` pairs that occur an odd number of times: the rings around each query point.
1340fn odd_runs(mut hits: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
1341    hits.sort_unstable();
1342    let mut odd: Vec<(usize, usize)> = Vec::new();
1343    for h in hits {
1344        if odd.last() == Some(&h) {
1345            odd.pop();
1346        } else {
1347            odd.push(h);
1348        }
1349    }
1350    odd
1351}
1352
1353/// The edges between the area where `inside` holds and the rest, each directed with the area on its left.
1354fn boundary(net: &[NetEdge], inside: fn(Winding) -> bool) -> Vec<(Pixel, Pixel)> {
1355    let lines: Vec<(Fixed, Fixed)> = net.iter().map(|n| (widen(n.a), widen(n.b))).collect();
1356    let queries: Vec<Fixed> = lines.iter().map(|&(a, b)| a + b).collect();
1357    let mut above = vec![Winding::default(); net.len()];
1358    rays_up(&lines, &queries, |q, e| {
1359        if q != e {
1360            above[q] -= net[e].winding;
1361        }
1362    });
1363    let mut edges = Vec::new();
1364    for (n, w) in net.iter().zip(above) {
1365        let (left, right) = if n.a.x == n.b.x {
1366            (w + n.winding, w)
1367        } else {
1368            (w, w - n.winding)
1369        };
1370        match (inside(left), inside(right)) {
1371            (true, false) => edges.push((n.a, n.b)),
1372            (false, true) => edges.push((n.b, n.a)),
1373            _ => {}
1374        }
1375    }
1376    edges
1377}
1378
1379/// Which half of the plane a direction points into, counter-clockwise from `+x`.
1380fn half_plane(d: Coord<i64>) -> u8 {
1381    u8::from(!(d.y > 0 || (d.y == 0 && d.x > 0)))
1382}
1383
1384/// Orders directions counter-clockwise from `+x`.
1385fn by_angle(a: Coord<i64>, b: Coord<i64>) -> Ordering {
1386    half_plane(a).cmp(&half_plane(b)).then_with(|| 0.cmp(&cross(a, b)))
1387}
1388
1389/// Walks the boundary `edges` into simple rings: at each vertex it turns as far left as it can, and a
1390/// walk that comes back to a vertex splits there.
1391fn trace(mut edges: Vec<(Pixel, Pixel)>) -> Vec<Vec<Pixel>> {
1392    edges.sort_unstable_by(|p, q| {
1393        (p.0.x, p.0.y)
1394            .cmp(&(q.0.x, q.0.y))
1395            .then_with(|| by_angle(widen(p.1) - widen(p.0), widen(q.1) - widen(q.0)))
1396    });
1397    let mut used = vec![false; edges.len()];
1398    let mut rings = Vec::new();
1399    let mut walk = Vec::new();
1400    for start in 0..edges.len() {
1401        if used[start] {
1402            continue;
1403        }
1404        walk.clear();
1405        let mut h = start;
1406        let closed = loop {
1407            used[h] = true;
1408            let (a, v) = edges[h];
1409            walk.push(a);
1410            let from = edges.partition_point(|e| (e.0.x, e.0.y) < (v.x, v.y));
1411            let to = edges.partition_point(|e| (e.0.x, e.0.y) <= (v.x, v.y));
1412            if from == to {
1413                break false;
1414            }
1415            let back = widen(a) - widen(v);
1416            let past =
1417                from + edges[from..to].partition_point(|e| by_angle(widen(e.1) - widen(v), back) == Ordering::Less);
1418            h = if past == from { to - 1 } else { past - 1 };
1419            if h == start {
1420                break true;
1421            }
1422            if used[h] {
1423                break false;
1424            }
1425        };
1426        if closed {
1427            split(&walk, &mut rings);
1428        }
1429    }
1430    rings
1431}
1432
1433/// Splits a closed walk into simple rings wherever it comes back to a vertex.
1434fn split(walk: &[Pixel], rings: &mut Vec<Vec<Pixel>>) {
1435    let mut stack: Vec<Pixel> = Vec::new();
1436    let mut at: HashMap<(i32, i32), usize> = HashMap::new();
1437    for &v in walk {
1438        if let Some(&i) = at.get(&(v.x, v.y)) {
1439            let ring: Vec<Pixel> = stack.drain(i..).collect();
1440            for c in &ring[1..] {
1441                at.remove(&(c.x, c.y));
1442            }
1443            stack.push(v);
1444            if ring.len() >= 3 {
1445                rings.push(ring);
1446            }
1447        } else {
1448            at.insert((v.x, v.y), stack.len());
1449            stack.push(v);
1450        }
1451    }
1452    if stack.len() >= 3 {
1453        rings.push(stack);
1454    }
1455}