1use core::cmp::Ordering;
4use std::collections::HashMap;
5
6use geo_types::Coord;
7
8use crate::TileError;
9use crate::geom::{orient, signed_area_2x};
10use crate::planar::{Meet, meet};
11
12const FRAC: u32 = 8;
14const ONE: i64 = 1 << FRAC;
16const HALF: i64 = ONE / 2;
18
19type Fixed = Coord<i64>;
21type Pixel = Coord<i32>;
23
24#[derive(Debug, Default, Clone)]
37pub struct Quantizer {
38 fixed: Vec<Fixed>,
39 fixed_ends: Vec<usize>,
40 rounded_at: Vec<usize>,
41 near: Vec<bool>,
42 vertices: Vec<Pixel>,
43 ring_ends: Vec<usize>,
44 polygon_ends: Vec<usize>,
45 segs: Vec<Seg>,
46 lines: Vec<(Fixed, Fixed)>,
47 grid: Grid,
48}
49
50#[derive(Debug, Clone, Copy)]
52pub struct Quantized<'a> {
53 q: &'a Quantizer,
54}
55
56#[derive(Debug, Clone, Copy)]
58struct Seg {
59 a: Pixel,
60 b: Pixel,
61 ring: usize,
62 first: usize,
63 edges: usize,
64}
65
66#[derive(Debug, Clone, Copy)]
68struct Net {
69 a: Pixel,
70 b: Pixel,
71 exterior: i32,
72 holes: i32,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77enum Ring {
78 Exterior,
79 Hole,
80}
81
82#[derive(Debug, Clone, Copy, Default)]
84struct Winding {
85 exterior: i32,
86 holes: i32,
87}
88
89impl Winding {
90 fn inside(self) -> bool {
92 self.exterior != 0 && self.holes == 0
93 }
94}
95
96impl Quantizer {
97 #[must_use]
99 pub fn new() -> Self {
100 Self::default()
101 }
102
103 pub fn polygon<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
109 where
110 R: IntoIterator,
111 R::Item: IntoIterator<Item = Coord<f64>>,
112 {
113 self.read(rings)?;
114 self.round();
115 if !self.ring_ends.is_empty() {
116 if self.rounding_kept_valid() {
117 self.keep();
118 } else {
119 self.repair();
120 }
121 }
122 debug_assert!(
123 self.output_is_valid(),
124 "Quantizer::polygon was given an invalid polygon"
125 );
126 Ok(Quantized { q: self })
127 }
128
129 pub fn make_valid<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
137 where
138 R: IntoIterator,
139 R::Item: IntoIterator<Item = Coord<f64>>,
140 {
141 self.read(rings)?;
142 self.round();
143 if !self.ring_ends.is_empty() {
144 if self.rounded_is_valid() {
145 self.keep();
146 } else {
147 self.repair();
148 }
149 }
150 debug_assert!(self.output_is_valid(), "Quantizer::make_valid gave an invalid polygon");
151 Ok(Quantized { q: self })
152 }
153
154 fn read<R>(&mut self, rings: R) -> Result<(), TileError>
157 where
158 R: IntoIterator,
159 R::Item: IntoIterator<Item = Coord<f64>>,
160 {
161 self.fixed.clear();
162 self.fixed_ends.clear();
163 for (i, ring) in rings.into_iter().enumerate() {
164 let start = self.fixed.len();
165 for c in ring {
166 let c = Coord {
167 x: to_fixed(c.x)?,
168 y: to_fixed(c.y)?,
169 };
170 if self.fixed.len() == start || self.fixed.last() != Some(&c) {
171 self.fixed.push(c);
172 }
173 }
174 if self.fixed.len() > start + 1 && self.fixed.last() == self.fixed.get(start) {
175 self.fixed.pop();
176 }
177 if self.fixed.len() - start < 3 {
178 self.fixed.truncate(start);
179 if i == 0 {
180 return Ok(());
181 }
182 continue;
183 }
184 let area = fixed_area_2x(&self.fixed[start..]);
185 if (i == 0 && area < 0) || (i > 0 && area > 0) {
186 self.fixed[start..].reverse();
187 }
188 self.fixed_ends.push(self.fixed.len());
189 }
190 Ok(())
191 }
192
193 fn output_is_valid(&self) -> bool {
195 let vertices: Vec<Fixed> = self.vertices.iter().map(|&p| widen(p)).collect();
196 is_valid(&vertices, &self.ring_ends, &self.polygon_ends)
197 }
198
199 fn round(&mut self) {
202 self.vertices.clear();
203 self.ring_ends.clear();
204 self.polygon_ends.clear();
205 self.rounded_at.clear();
206 for (i, ring) in rings_of(&self.fixed, &self.fixed_ends).enumerate() {
207 let start = self.vertices.len();
208 let from = self.rounded_at.len();
209 for &c in ring {
210 let p = pixel(c);
211 if self.vertices.len() == start || self.vertices.last() != Some(&p) {
212 self.vertices.push(p);
213 }
214 self.rounded_at.push(self.vertices.len() - 1);
215 }
216 if self.vertices.len() > start + 1 && self.vertices.last() == self.vertices.get(start) {
217 self.vertices.pop();
218 let last = self.vertices.len();
219 for r in &mut self.rounded_at[from..] {
220 if *r == last {
221 *r = start;
222 }
223 }
224 }
225 if self.vertices.len() - start < 3 {
226 self.vertices.truncate(start);
227 if i == 0 {
228 return;
229 }
230 self.rounded_at[from..].fill(usize::MAX);
231 continue;
232 }
233 self.ring_ends.push(self.vertices.len());
234 }
235 }
236
237 fn keep(&mut self) {
239 let mut start = 0;
240 for (i, &end) in self.ring_ends.iter().enumerate() {
241 let ring = &mut self.vertices[start..end];
242 if (signed_area_2x(ring) > 0) != (i == 0) {
243 ring.reverse();
244 }
245 start = end;
246 }
247 self.polygon_ends.push(self.ring_ends.len());
248 }
249
250 fn rounded_edges(&mut self) -> bool {
252 self.segs.clear();
253 let mut first = 0;
254 for (ring, &end) in self.ring_ends.iter().enumerate() {
255 let verts = &self.vertices[first..end];
256 let edges = verts.len();
257 for (k, &at) in verts.iter().enumerate() {
258 let (prev, next) = (verts[(k + edges - 1) % edges], verts[(k + 1) % edges]);
259 let (back, ahead) = (widen(prev) - widen(at), widen(next) - widen(at));
260 if orient(prev, at, next) == Ordering::Equal && back.x * ahead.x + back.y * ahead.y > 0 {
261 return false;
262 }
263 self.segs.push(Seg {
264 a: at,
265 b: next,
266 ring,
267 first,
268 edges,
269 });
270 }
271 first = end;
272 }
273 true
274 }
275
276 fn rounding_kept_valid(&mut self) -> bool {
279 if !self.rounded_edges() {
280 return false;
281 }
282 self.near.clear();
283 self.near.resize(self.fixed.len(), false);
284 let Self {
285 fixed,
286 fixed_ends,
287 rounded_at,
288 near,
289 segs,
290 grid,
291 ..
292 } = self;
293 let segs = &*segs;
294 let incident = |r: usize| {
295 let s = segs[r];
296 [if r == s.first { s.first + s.edges - 1 } else { r - 1 }, r]
297 };
298 let apart = |x: usize, y: usize| {
299 let (p, q) = (segs[x], segs[y]);
300 x == y || adjacent(segs, x, y) || matches!(meet(p.a, p.b, q.a, q.b), Meet::Apart)
301 };
302 let planar = near_vertices(fixed, fixed_ends, grid, |v, a, b| {
303 let (rv, ra, rb) = (rounded_at[v], rounded_at[a], rounded_at[b]);
304 if rv == usize::MAX || ra == usize::MAX {
305 return true;
306 }
307 if !edges_at_clear_of(fixed, fixed_ends, v, a, b) {
308 return false;
309 }
310 if segs[rv].ring != segs[ra].ring {
311 near[v] = true;
312 }
313 let image = if ra == rb { incident(ra) } else { [ra, ra] };
314 incident(rv).iter().all(|&x| image.iter().all(|&y| apart(x, y)))
315 });
316 planar
317 && rings_of(rounded_at, fixed_ends)
318 .zip(rings_of(near, fixed_ends))
319 .all(|(r, near)| r[0] == usize::MAX || near.contains(&false))
320 }
321
322 fn rounded_is_valid(&mut self) -> bool {
325 if !self.rounded_edges() {
326 return false;
327 }
328 let segs = &self.segs;
329 self.lines.clear();
330 self.lines.extend(segs.iter().map(|s| (widen(s.a), widen(s.b))));
331 let planar = near_pairs(&self.lines, &mut self.grid, |i, j| {
332 let (p, q) = (segs[i], segs[j]);
333 adjacent(segs, i, j) || matches!(meet(p.a, p.b, q.a, q.b), Meet::Apart)
334 });
335 if !planar {
336 return false;
337 }
338 if self.ring_ends.len() == 1 {
339 return true;
340 }
341 let edges: Vec<(Fixed, Fixed)> = self.lines.iter().map(|&(a, b)| left_first(a, b)).collect();
342 let hole_starts = &self.ring_ends[..self.ring_ends.len() - 1];
343 let queries: Vec<Fixed> = hole_starts.iter().map(|&s| doubled(self.vertices[s])).collect();
344 let mut hits = Vec::new();
345 rays_up(&edges, &queries, |q, e| {
346 if segs[e].ring != q + 1 {
347 hits.push((q, segs[e].ring));
348 }
349 });
350 let around = odd_runs(hits);
351 around.len() == queries.len()
352 && around
353 .iter()
354 .enumerate()
355 .all(|(q, &(hole, ring))| hole == q && ring == 0)
356 }
357
358 fn repair(&mut self) {
360 self.vertices.clear();
361 self.ring_ends.clear();
362 self.polygon_ends.clear();
363 let mut segs: Vec<(Fixed, Fixed, Ring)> = Vec::new();
364 for (i, ring) in rings_of(&self.fixed, &self.fixed_ends).enumerate() {
365 let kind = if i == 0 { Ring::Exterior } else { Ring::Hole };
366 for (k, &a) in ring.iter().enumerate() {
367 segs.push((a, ring[(k + 1) % ring.len()], kind));
368 }
369 }
370 let hot = hot_pixels(&segs);
371 let net = net_edges(&segs, &hot);
372 let rings = trace(boundary(&net));
373 self.assemble(rings);
374 }
375
376 fn assemble(&mut self, rings: Vec<Vec<Pixel>>) {
378 let (shells, holes): (Vec<_>, Vec<_>) = rings.into_iter().partition(|r| signed_area_2x(r) > 0);
379 let mut owner = vec![0; holes.len()];
380 if shells.len() > 1 && !holes.is_empty() {
381 let mut edges = Vec::new();
382 let mut ring_of = Vec::new();
383 for (s, shell) in shells.iter().enumerate() {
384 for (k, &a) in shell.iter().enumerate() {
385 edges.push(left_first(widen(a), widen(shell[(k + 1) % shell.len()])));
386 ring_of.push(s);
387 }
388 }
389 let queries: Vec<Fixed> = holes.iter().map(|h| widen(h[0]) + widen(h[1])).collect();
390 let mut hits = Vec::new();
391 rays_up(&edges, &queries, |q, e| hits.push((q, ring_of[e])));
392 let areas: Vec<i128> = shells.iter().map(|s| signed_area_2x(s)).collect();
393 owner.fill(usize::MAX);
394 for (hole, shell) in odd_runs(hits) {
395 if owner[hole] == usize::MAX || areas[shell] < areas[owner[hole]] {
396 owner[hole] = shell;
397 }
398 }
399 }
400 for (s, shell) in shells.iter().enumerate() {
401 self.vertices.extend_from_slice(shell);
402 self.ring_ends.push(self.vertices.len());
403 for (hole, _) in holes.iter().zip(&owner).filter(|&(_, &o)| o == s) {
404 self.vertices.extend_from_slice(hole);
405 self.ring_ends.push(self.vertices.len());
406 }
407 self.polygon_ends.push(self.ring_ends.len());
408 }
409 }
410}
411
412fn edges_at_clear_of(verts: &[Fixed], ends: &[usize], v: usize, a: usize, b: usize) -> bool {
415 let ring = ends.partition_point(|&e| e <= v);
416 let (start, end) = (if ring == 0 { 0 } else { ends[ring - 1] }, ends[ring]);
417 let prev = if v == start { end - 1 } else { v - 1 };
418 let next = if v + 1 == end { start } else { v + 1 };
419 let same_ring = (start..end).contains(&a);
420 [(prev, v), (v, next)]
421 .into_iter()
422 .all(|(x, y)| match contact((verts[x], verts[y]), (verts[a], verts[b])) {
423 Contact::Apart => true,
424 Contact::Point => !same_ring || x == b || y == a,
425 Contact::Bad => false,
426 })
427}
428
429fn adjacent(segs: &[Seg], i: usize, j: usize) -> bool {
431 segs[i].ring == segs[j].ring && (i.abs_diff(j) == 1 || i.abs_diff(j) == segs[i].edges - 1)
432}
433
434impl<'a> Quantized<'a> {
435 #[must_use]
437 pub fn is_empty(self) -> bool {
438 self.q.polygon_ends.is_empty()
439 }
440
441 pub fn polygons(self) -> impl Iterator<Item = impl Iterator<Item = &'a [Pixel]> + 'a> + 'a {
446 let q = self.q;
447 let ring_starts = core::iter::once(0).chain(q.polygon_ends.iter().copied());
448 ring_starts.zip(&q.polygon_ends).map(move |(first, &last)| {
449 (first..last).map(move |r| {
450 let start = if r == 0 { 0 } else { q.ring_ends[r - 1] };
451 &q.vertices[start..q.ring_ends[r]]
452 })
453 })
454 }
455}
456
457fn rings_of<'a, T>(verts: &'a [T], ends: &'a [usize]) -> impl Iterator<Item = &'a [T]> {
459 let starts = core::iter::once(0).chain(ends.iter().copied());
460 starts.zip(ends).map(|(s, &e)| &verts[s..e])
461}
462
463#[expect(clippy::cast_possible_truncation, reason = "range-checked before the cast")]
465#[expect(clippy::cast_precision_loss, reason = "ONE and HALF are small powers of two")]
466fn to_fixed(v: f64) -> Result<i64, TileError> {
467 const ROUND: f64 = 6_755_399_441_055_744.0;
469 let f = (v * ONE as f64 + ROUND) - ROUND;
470 let lo = f64::from(i32::MIN) * ONE as f64 - HALF as f64;
471 let hi = (f64::from(i32::MAX) + 1.0) * ONE as f64 - HALF as f64;
472 if f >= lo && f < hi {
473 Ok(f as i64)
474 } else {
475 Err(TileError::Overflow)
476 }
477}
478
479#[expect(clippy::cast_possible_truncation, reason = "to_fixed keeps every pixel in i32")]
481fn pixel(c: Fixed) -> Pixel {
482 Coord {
483 x: ((c.x + HALF) >> FRAC) as i32,
484 y: ((c.y + HALF) >> FRAC) as i32,
485 }
486}
487
488fn widen(p: Pixel) -> Coord<i64> {
490 Coord {
491 x: i64::from(p.x),
492 y: i64::from(p.y),
493 }
494}
495
496#[derive(Debug, Default, Clone)]
498struct Grid {
499 cells: Vec<(u64, usize)>,
500 lengths: Vec<i64>,
501 columns: Vec<usize>,
502 points: Vec<(usize, usize)>,
503}
504
505fn near_pairs(lines: &[(Coord<i64>, Coord<i64>)], grid: &mut Grid, mut test: impl FnMut(usize, usize) -> bool) -> bool {
508 let Grid { cells, lengths, .. } = grid;
509 cells.clear();
510 lengths.clear();
511 let Some(&(first, _)) = lines.first() else {
512 return true;
513 };
514 let (mut min, mut max) = (first, first);
515 for &(a, b) in lines {
516 for c in [a, b] {
517 (min.x, min.y, max.x, max.y) = (min.x.min(c.x), min.y.min(c.y), max.x.max(c.x), max.y.max(c.y));
518 }
519 lengths.push((b.x - a.x).abs().max((b.y - a.y).abs()));
520 }
521 let size = cell_size(lengths, min, max, 1);
522 let cell = |v: i64, o: i64| u64::try_from((v - o) / size).unwrap_or(0);
523 let rows = cell(max.y, min.y) + 1;
524 for (i, &(a, b)) in lines.iter().enumerate() {
525 let (a, b) = if a.x <= b.x { (a, b) } else { (b, a) };
526 let (lo, hi) = (a.y.min(b.y), a.y.max(b.y));
527 let (c0, c1) = (cell(a.x, min.x), cell(b.x, min.x));
528 if c0 == c1 {
529 for cy in cell(lo, min.y)..=cell(hi, min.y) {
530 cells.push((c0 * rows + cy, i));
531 }
532 continue;
533 }
534 #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
535 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);
536 let mut x0 = a.x;
537 for cx in c0..=c1 {
538 let x1 = (min.x + i64::try_from(cx + 1).unwrap_or(i64::MAX).saturating_mul(size)).min(b.x);
539 let (left, right) = (at(x0), at(x1));
540 #[expect(clippy::cast_possible_truncation, reason = "clamped to the segment's own span")]
541 let (y0, y1) = (
542 (left.min(right).floor() as i64 - 1).max(lo),
543 (left.max(right).ceil() as i64 + 1).min(hi),
544 );
545 for cy in cell(y0, min.y)..=cell(y1, min.y) {
546 cells.push((cx * rows + cy, i));
547 }
548 x0 = x1;
549 }
550 }
551 cells.sort_unstable_by_key(|c| c.0);
552 for group in cells.chunk_by(|p, q| p.0 == q.0) {
553 for (k, p) in group.iter().enumerate() {
554 for q in &group[k + 1..] {
555 if !test(p.1, q.1) {
556 return false;
557 }
558 }
559 }
560 }
561 true
562}
563
564fn cell_size(lengths: &mut [i64], min: Fixed, max: Fixed, floor: i64) -> i64 {
567 let mid = lengths.len() / 2;
568 let median = *lengths.select_nth_unstable(mid).1;
569 let n = i64::try_from(lengths.len()).unwrap_or(i64::MAX);
570 median
571 .max((max.x - min.x).max(max.y - min.y) / n.saturating_mul(2))
572 .max(floor)
573}
574
575fn near_vertices(
578 verts: &[Fixed],
579 ends: &[usize],
580 grid: &mut Grid,
581 mut test: impl FnMut(usize, usize, usize) -> bool,
582) -> bool {
583 let Grid {
584 lengths,
585 columns,
586 points,
587 ..
588 } = grid;
589 lengths.clear();
590 columns.clear();
591 points.clear();
592 let Some(&first) = verts.first() else {
593 return true;
594 };
595 let (mut min, mut max) = (first, first);
596 for &c in verts {
597 (min.x, min.y, max.x, max.y) = (min.x.min(c.x), min.y.min(c.y), max.x.max(c.x), max.y.max(c.y));
598 }
599 let starts = core::iter::once(0).chain(ends.iter().copied());
600 let edges = || {
601 starts
602 .clone()
603 .zip(ends)
604 .flat_map(|(s, &e)| (s..e).map(move |k| (k, if k + 1 == e { s } else { k + 1 })))
605 };
606 lengths.extend(edges().map(|(a, b)| {
607 let d = verts[b] - verts[a];
608 d.x.abs().max(d.y.abs())
609 }));
610 let shift = cell_size(lengths, min, max, ONE)
611 .unsigned_abs()
612 .next_power_of_two()
613 .trailing_zeros()
614 + 1;
615 let cell = |v: i64, o: i64| usize::try_from((v - o) >> shift).unwrap_or(0);
616 let (cols, rows) = (cell(max.x, min.x) + 1, cell(max.y, min.y) + 1);
617 let (column, row) = (
618 |x: i64| cell(x, min.x).min(cols - 1),
619 |y: i64| cell(y, min.y).min(rows - 1),
620 );
621 columns.resize(cols + 1, 0);
622 for c in verts {
623 columns[column(c.x) + 1] += 1;
624 }
625 for k in 1..=cols {
626 columns[k] += columns[k - 1];
627 }
628 points.resize(verts.len(), (0, 0));
629 for (i, c) in verts.iter().enumerate() {
630 let next = &mut columns[column(c.x)];
631 points[*next] = (row(c.y), i);
632 *next += 1;
633 }
634 columns.pop();
635 columns.insert(0, 0);
636 for k in 0..cols {
637 points[columns[k]..columns[k + 1]].sort_unstable_by_key(|p| p.0);
638 }
639 for (a, b) in edges() {
640 let (p, q) = (verts[a], verts[b]);
641 let (l, r) = if p.x <= q.x { (p, q) } else { (q, p) };
642 let (lo, hi) = (l.y.min(r.y), l.y.max(r.y));
643 #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
644 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);
645 let (c0, c1) = (column(l.x - ONE), column(r.x + ONE));
646 for cx in c0..=c1 {
647 #[expect(clippy::cast_possible_truncation, reason = "clamped to the edge's own span")]
648 let (y0, y1) = if c1 - c0 <= 2 {
649 (lo, hi)
650 } else {
651 let x0 = min.x + (i64::try_from(cx).unwrap_or(i64::MAX) << shift);
652 let (xa, xb) = ((x0 - ONE).clamp(l.x, r.x), (x0 + (1 << shift) + ONE).clamp(l.x, r.x));
653 let (ya, yb) = (at(xa), at(xb));
654 ((ya.min(yb) as i64 - 2).max(lo), (ya.max(yb) as i64 + 2).min(hi))
655 };
656 let (r0, r1) = (row(y0 - ONE), row(y1 + ONE));
657 let col = &points[columns[cx]..columns[cx + 1]];
658 for &(y, v) in &col[col.partition_point(|p| p.0 < r0)..] {
659 if y > r1 {
660 break;
661 }
662 if v != a && v != b && within(p, q, verts[v]) && !test(v, a, b) {
663 return false;
664 }
665 }
666 }
667 }
668 true
669}
670
671fn within(a: Fixed, b: Fixed, v: Fixed) -> bool {
673 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 {
674 return false;
675 }
676 let d = b - a;
677 cross(d, v - a).abs() <= i128::from(ONE) * i128::from(d.x.abs() + d.y.abs())
678}
679
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
682enum Contact {
683 Apart,
684 Point,
686 Bad,
688}
689
690fn contact((p1, p2): (Fixed, Fixed), (q1, q2): (Fixed, Fixed)) -> Contact {
692 let boxed = |c: Fixed, a: Fixed, b: Fixed| {
693 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)
694 };
695 let side = |a: Fixed, b: Fixed, c: Fixed| cross(b - a, c - a).signum();
696 let (s1, s2) = (side(p1, p2, q1), side(p1, p2, q2));
697 let (s3, s4) = (side(q1, q2, p1), side(q1, q2, p2));
698 if s1 * s2 < 0 && s3 * s4 < 0 {
699 return Contact::Bad;
700 }
701 if s1 == 0 && s2 == 0 {
702 let key = |c: Fixed| if p1.x == p2.x { c.y } else { c.x };
703 let lo = key(p1).min(key(p2)).max(key(q1).min(key(q2)));
704 let hi = key(p1).max(key(p2)).min(key(q1).max(key(q2)));
705 return match lo.cmp(&hi) {
706 Ordering::Less => Contact::Bad,
707 Ordering::Equal => Contact::Point,
708 Ordering::Greater => Contact::Apart,
709 };
710 }
711 let touches = (s1 == 0 && boxed(q1, p1, p2))
712 || (s2 == 0 && boxed(q2, p1, p2))
713 || (s3 == 0 && boxed(p1, q1, q2))
714 || (s4 == 0 && boxed(p2, q1, q2));
715 if touches { Contact::Point } else { Contact::Apart }
716}
717
718fn is_valid(verts: &[Fixed], ring_ends: &[usize], polygon_ends: &[usize]) -> bool {
721 let mut lines = Vec::new();
722 let mut ring_of = Vec::new();
723 for (r, ring) in rings_of(verts, ring_ends).enumerate() {
724 let n = ring.len();
725 if n < 3 {
726 return false;
727 }
728 for k in 0..n {
729 let (prev, at, next) = (ring[(k + n - 1) % n], ring[k], ring[(k + 1) % n]);
730 let (back, ahead) = (prev - at, next - at);
731 if cross(back, ahead) == 0
732 && i128::from(back.x) * i128::from(ahead.x) + i128::from(back.y) * i128::from(ahead.y) > 0
733 {
734 return false;
735 }
736 lines.push((at, next));
737 ring_of.push(r);
738 }
739 }
740 let ring_len = |r: usize| ring_ends[r] - if r == 0 { 0 } else { ring_ends[r - 1] };
741 let simple = near_pairs(&lines, &mut Grid::default(), |i, j| match contact(lines[i], lines[j]) {
742 Contact::Apart => true,
743 Contact::Point => ring_of[i] != ring_of[j] || i.abs_diff(j) == 1 || i.abs_diff(j) == ring_len(ring_of[i]) - 1,
744 Contact::Bad => false,
745 });
746 if !simple {
747 return false;
748 }
749 let mut polygon_of = Vec::new();
750 let mut shell_of = Vec::new();
751 let starts = core::iter::once(0).chain(polygon_ends.iter().copied());
752 for (p, (first, &last)) in starts.zip(polygon_ends).enumerate() {
753 polygon_of.extend(core::iter::repeat_n(p, last - first));
754 shell_of.extend(core::iter::repeat_n(first, last - first));
755 }
756 let edges: Vec<(Fixed, Fixed)> = lines.iter().map(|&(a, b)| left_first(a, b)).collect();
757 let queries: Vec<Fixed> = rings_of(verts, ring_ends).map(|r| r[0] + r[1]).collect();
758 let mut hits = Vec::new();
759 rays_up(&edges, &queries, |q, e| {
760 if ring_of[e] != q {
761 hits.push((q, ring_of[e]));
762 }
763 });
764 let around = odd_runs(hits);
765 let mut held = vec![false; queries.len()];
766 for group in around.chunk_by(|a, b| a.0 == b.0 && polygon_of[a.1] == polygon_of[b.1]) {
767 let (q, r) = group[0];
768 if polygon_of[r] != polygon_of[q] {
769 if group.len() != 2 || shell_of[r] != r {
770 return false;
771 }
772 } else if shell_of[q] == q || group != [(q, shell_of[q])] {
773 return false;
774 } else {
775 held[q] = true;
776 }
777 }
778 (0..queries.len()).all(|q| shell_of[q] == q || held[q])
779}
780
781fn doubled(p: Pixel) -> Fixed {
783 Coord {
784 x: 2 * i64::from(p.x),
785 y: 2 * i64::from(p.y),
786 }
787}
788
789fn left_first(a: Fixed, b: Fixed) -> (Fixed, Fixed) {
791 if (a.x, a.y) <= (b.x, b.y) { (a, b) } else { (b, a) }
792}
793
794fn cross(a: Fixed, b: Fixed) -> i128 {
796 i128::from(a.x) * i128::from(b.y) - i128::from(a.y) * i128::from(b.x)
797}
798
799fn fixed_area_2x(ring: &[Fixed]) -> i128 {
801 let o = ring[0];
802 ring.windows(2).map(|w| cross(w[0] - o, w[1] - o)).sum()
803}
804
805fn hot_pixels(segs: &[(Fixed, Fixed, Ring)]) -> Vec<Pixel> {
807 let mut hot: Vec<Pixel> = segs.iter().map(|s| pixel(s.0)).collect();
808 let lines: Vec<(Fixed, Fixed)> = segs.iter().map(|s| (s.0, s.1)).collect();
809 near_pairs(&lines, &mut Grid::default(), |i, j| {
810 let ((p1, p2), (q1, q2)) = (lines[i], lines[j]);
811 if p1 != q1 && p1 != q2 && p2 != q1 && p2 != q2 {
812 let (d, e) = (p2 - p1, q2 - q1);
813 let (s1, s2) = (cross(d, q1 - p1).signum(), cross(d, q2 - p1).signum());
814 let (s3, s4) = (cross(e, p1 - q1).signum(), cross(e, p2 - q1).signum());
815 if s1 * s2 < 0 && s3 * s4 < 0 {
816 hot.push(crossing(p1, d, q1, e));
817 }
818 }
819 true
820 });
821 hot.sort_unstable_by_key(|p| (p.x, p.y));
822 hot.dedup();
823 hot
824}
825
826#[expect(
828 clippy::cast_possible_truncation,
829 reason = "the crossing lies on both edges, so in i32"
830)]
831fn crossing(p: Fixed, d: Fixed, q: Fixed, e: Fixed) -> Pixel {
832 let (mut num, mut den) = (cross(q - p, e), cross(d, e));
833 if den < 0 {
834 (num, den) = (-num, -den);
835 }
836 let at =
837 |p: i64, d: i64| ((i128::from(p + HALF) * den + num * i128::from(d)).div_euclid(den * i128::from(ONE))) as i32;
838 Coord {
839 x: at(p.x, d.x),
840 y: at(p.y, d.y),
841 }
842}
843
844#[derive(Clone, Copy)]
846struct Bound {
847 n: i128,
848 d: i128,
849 open: bool,
850}
851
852impl Bound {
853 fn cmp(self, other: Self) -> Ordering {
855 (self.n * other.d).cmp(&(other.n * self.d))
856 }
857}
858
859fn passes(p: Fixed, q: Fixed, h: Pixel) -> bool {
861 let mut lo = Bound {
862 n: 0,
863 d: 1,
864 open: false,
865 };
866 let mut hi = Bound {
867 n: 1,
868 d: 1,
869 open: false,
870 };
871 for (p0, d, c) in [(p.x, q.x - p.x, h.x), (p.y, q.y - p.y, h.y)] {
872 let (min, max) = (i64::from(c) * ONE - HALF, i64::from(c) * ONE + HALF);
873 let (from, to) = match d.cmp(&0) {
874 Ordering::Equal if (min..max).contains(&p0) => continue,
875 Ordering::Equal => return false,
876 Ordering::Greater => (
877 Bound {
878 n: (min - p0).into(),
879 d: d.into(),
880 open: false,
881 },
882 Bound {
883 n: (max - p0).into(),
884 d: d.into(),
885 open: true,
886 },
887 ),
888 Ordering::Less => (
889 Bound {
890 n: (p0 - max).into(),
891 d: (-d).into(),
892 open: true,
893 },
894 Bound {
895 n: (p0 - min).into(),
896 d: (-d).into(),
897 open: false,
898 },
899 ),
900 };
901 match from.cmp(lo) {
902 Ordering::Greater => lo = from,
903 Ordering::Equal => lo.open |= from.open,
904 Ordering::Less => {}
905 }
906 match to.cmp(hi) {
907 Ordering::Less => hi = to,
908 Ordering::Equal => hi.open |= to.open,
909 Ordering::Greater => {}
910 }
911 }
912 match lo.cmp(hi) {
913 Ordering::Less => true,
914 Ordering::Equal => !lo.open && !hi.open,
915 Ordering::Greater => false,
916 }
917}
918
919fn net_edges(segs: &[(Fixed, Fixed, Ring)], hot: &[Pixel]) -> Vec<Net> {
922 let mut frags = Vec::new();
923 let mut path: Vec<(i128, Pixel)> = Vec::new();
924 for &(p, q, kind) in segs {
925 let (pp, pq) = (pixel(p), pixel(q));
926 if pp == pq {
927 continue;
928 }
929 let (lo, hi) = (
930 pixel(Coord {
931 x: p.x.min(q.x),
932 y: p.y.min(q.y),
933 }),
934 pixel(Coord {
935 x: p.x.max(q.x),
936 y: p.y.max(q.y),
937 }),
938 );
939 let from = hot.partition_point(|h| h.x < lo.x);
940 let to = hot.partition_point(|h| h.x <= hi.x);
941 path.clear();
942 path.push((i128::MIN, pp));
943 for &h in &hot[from..to] {
944 if (lo.y..=hi.y).contains(&h.y) && h != pp && h != pq && passes(p, q, h) {
945 let c = Coord {
946 x: i64::from(h.x) * ONE,
947 y: i64::from(h.y) * ONE,
948 };
949 let along =
950 i128::from(c.x - p.x) * i128::from(q.x - p.x) + i128::from(c.y - p.y) * i128::from(q.y - p.y);
951 path.push((along, h));
952 }
953 }
954 path.sort_unstable_by_key(|s| s.0);
955 path.push((i128::MAX, pq));
956 for w in path.windows(2) {
957 let (a, b) = (w[0].1, w[1].1);
958 let (exterior, holes) = match kind {
959 Ring::Exterior => (1, 0),
960 Ring::Hole => (0, 1),
961 };
962 let (a, b, sign) = if (a.x, a.y) < (b.x, b.y) { (a, b, 1) } else { (b, a, -1) };
963 frags.push(Net {
964 a,
965 b,
966 exterior: sign * exterior,
967 holes: sign * holes,
968 });
969 }
970 }
971 frags.sort_unstable_by_key(|f| (f.a.x, f.a.y, f.b.x, f.b.y));
972 let mut net: Vec<Net> = Vec::new();
973 for f in frags {
974 match net.last_mut() {
975 Some(n) if n.a == f.a && n.b == f.b => {
976 n.exterior += f.exterior;
977 n.holes += f.holes;
978 }
979 _ => net.push(f),
980 }
981 }
982 net.retain(|n| n.exterior != 0 || n.holes != 0);
983 net
984}
985
986fn rays_up(edges: &[(Fixed, Fixed)], queries: &[Fixed], mut hit: impl FnMut(usize, usize)) {
989 let x2 = |v: i64| 2 * v;
990 let mut order: Vec<usize> = (0..edges.len()).filter(|&e| edges[e].0.x != edges[e].1.x).collect();
991 order.sort_unstable_by_key(|&e| edges[e].0.x);
992 let mut by_x: Vec<usize> = (0..queries.len()).collect();
993 by_x.sort_unstable_by_key(|&q| queries[q].x);
994 let mut active: Vec<usize> = Vec::new();
995 let mut next = 0;
996 for q in by_x {
997 let m = queries[q];
998 while next < order.len() && x2(edges[order[next]].0.x) <= m.x {
999 active.push(order[next]);
1000 next += 1;
1001 }
1002 active.retain(|&e| x2(edges[e].1.x) > m.x);
1003 for &e in &active {
1004 let (l, r) = (edges[e].0 * 2, edges[e].1 * 2);
1005 if cross(r - l, m - l) < 0 {
1006 hit(q, e);
1007 }
1008 }
1009 }
1010}
1011
1012fn odd_runs(mut hits: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
1014 hits.sort_unstable();
1015 let mut odd: Vec<(usize, usize)> = Vec::new();
1016 for h in hits {
1017 if odd.last() == Some(&h) {
1018 odd.pop();
1019 } else {
1020 odd.push(h);
1021 }
1022 }
1023 odd
1024}
1025
1026fn boundary(net: &[Net]) -> Vec<(Pixel, Pixel)> {
1028 let edges: Vec<(Fixed, Fixed)> = net.iter().map(|n| (widen(n.a), widen(n.b))).collect();
1029 let queries: Vec<Fixed> = edges.iter().map(|&(a, b)| a + b).collect();
1030 let mut above = vec![Winding::default(); net.len()];
1031 rays_up(&edges, &queries, |q, e| {
1032 if q != e {
1033 above[q].exterior -= net[e].exterior;
1034 above[q].holes -= net[e].holes;
1035 }
1036 });
1037 let mut half = Vec::new();
1038 for (n, w) in net.iter().zip(above) {
1039 let (left, right) = if n.a.x == n.b.x {
1040 (
1041 Winding {
1042 exterior: w.exterior + n.exterior,
1043 holes: w.holes + n.holes,
1044 },
1045 w,
1046 )
1047 } else {
1048 (
1049 w,
1050 Winding {
1051 exterior: w.exterior - n.exterior,
1052 holes: w.holes - n.holes,
1053 },
1054 )
1055 };
1056 match (left.inside(), right.inside()) {
1057 (true, false) => half.push((n.a, n.b)),
1058 (false, true) => half.push((n.b, n.a)),
1059 _ => {}
1060 }
1061 }
1062 half
1063}
1064
1065fn half_plane(d: Coord<i64>) -> u8 {
1067 u8::from(!(d.y > 0 || (d.y == 0 && d.x > 0)))
1068}
1069
1070fn by_angle(a: Coord<i64>, b: Coord<i64>) -> Ordering {
1072 half_plane(a).cmp(&half_plane(b)).then_with(|| 0.cmp(&cross(a, b)))
1073}
1074
1075fn direction(from: Pixel, to: Pixel) -> Coord<i64> {
1077 Coord {
1078 x: i64::from(to.x) - i64::from(from.x),
1079 y: i64::from(to.y) - i64::from(from.y),
1080 }
1081}
1082
1083fn trace(mut half: Vec<(Pixel, Pixel)>) -> Vec<Vec<Pixel>> {
1086 half.sort_unstable_by(|p, q| {
1087 (p.0.x, p.0.y)
1088 .cmp(&(q.0.x, q.0.y))
1089 .then_with(|| by_angle(direction(p.0, p.1), direction(q.0, q.1)))
1090 });
1091 let mut used = vec![false; half.len()];
1092 let mut rings = Vec::new();
1093 let mut walk = Vec::new();
1094 for start in 0..half.len() {
1095 if used[start] {
1096 continue;
1097 }
1098 walk.clear();
1099 let mut h = start;
1100 let closed = loop {
1101 used[h] = true;
1102 let (a, v) = half[h];
1103 walk.push(a);
1104 let from = half.partition_point(|e| (e.0.x, e.0.y) < (v.x, v.y));
1105 let to = half.partition_point(|e| (e.0.x, e.0.y) <= (v.x, v.y));
1106 if from == to {
1107 break false;
1108 }
1109 let back = direction(v, a);
1110 let past = from + half[from..to].partition_point(|e| by_angle(direction(v, e.1), back) == Ordering::Less);
1111 h = if past == from { to - 1 } else { past - 1 };
1112 if h == start {
1113 break true;
1114 }
1115 if used[h] {
1116 break false;
1117 }
1118 };
1119 if closed {
1120 split(&walk, &mut rings);
1121 }
1122 }
1123 rings
1124}
1125
1126fn split(walk: &[Pixel], rings: &mut Vec<Vec<Pixel>>) {
1128 let mut stack: Vec<Pixel> = Vec::new();
1129 let mut at: HashMap<(i32, i32), usize> = HashMap::new();
1130 for &v in walk {
1131 if let Some(&i) = at.get(&(v.x, v.y)) {
1132 let ring: Vec<Pixel> = stack.drain(i..).collect();
1133 for c in &ring[1..] {
1134 at.remove(&(c.x, c.y));
1135 }
1136 stack.push(v);
1137 if ring.len() >= 3 {
1138 rings.push(ring);
1139 }
1140 } else {
1141 at.insert((v.x, v.y), stack.len());
1142 stack.push(v);
1143 }
1144 }
1145 if stack.len() >= 3 {
1146 rings.push(stack);
1147 }
1148}