use std::collections::{BTreeSet, HashMap, HashSet};
use geo::{LineString, Polygon};
use geolith::geometry::mercator::{MAX_LAT, MIN_LAT, wgs84_to_world};
use geolith::tile::feature::TILE_EXTENT;
use rstar::primitives::GeomWithData;
use rstar::{AABB, RTree};
pub type Pt = (i64, i64);
pub const FINE_BITS: u32 = 30;
pub const NODE_TOLERANCE: i64 = 8;
pub const SIMPLIFY_UNITS: f64 = 4.0;
pub const MIN_SIMPLIFY_UNITS: f64 = 1.0;
pub const MAX_ZOOM: u8 = (FINE_BITS - 12) as u8;
const REPAIR_ROUNDS: usize = 8;
const SEARCH_CELL: i64 = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ArcUse {
arc: usize,
reversed: bool,
}
struct SourceRing {
feature: u32,
points: Vec<Pt>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct BorderStats {
pub shared_before: f64,
pub shared_after: f64,
pub total_before: f64,
pub total_after: f64,
pub merged: usize,
pub inserted: usize,
pub arcs: usize,
pub nodes: usize,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ZoomStats {
pub vertices: usize,
pub repaired: usize,
pub crossing: usize,
pub dropped_rings: usize,
}
pub type FeatureRings = Vec<Vec<Vec<Pt>>>;
pub struct Coverage {
arcs: Vec<Vec<Pt>>,
features: Vec<Vec<Vec<Vec<ArcUse>>>>,
pub stats: BorderStats,
}
fn to_fine(lon: f64, lat: f64) -> Pt {
let (x, y) = wgs84_to_world(lon, lat.clamp(MIN_LAT, MAX_LAT));
let scale = f64::from(1_u32 << FINE_BITS);
((x * scale).round() as i64, (y * scale).round() as i64)
}
fn fine_ring(ring: &LineString<f64>) -> Vec<Pt> {
let mut points: Vec<Pt> = ring.0.iter().map(|c| to_fine(c.x, c.y)).collect();
points.dedup();
while points.len() > 1 && points.first() == points.last() {
points.pop();
}
points
}
fn dedup_ring(points: &mut Vec<Pt>) {
points.dedup();
while points.len() > 1 && points.first() == points.last() {
points.pop();
}
}
fn edge_key(a: Pt, b: Pt) -> (Pt, Pt) {
if a <= b { (a, b) } else { (b, a) }
}
fn length(a: Pt, b: Pt) -> f64 {
((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64)
}
fn edge_features(rings: &[SourceRing]) -> HashMap<(Pt, Pt), Vec<u32>> {
let mut edges: HashMap<(Pt, Pt), Vec<u32>> = HashMap::new();
for ring in rings {
let n = ring.points.len();
for i in 0..n {
let key = edge_key(ring.points[i], ring.points[(i + 1) % n]);
edges.entry(key).or_default().push(ring.feature);
}
}
for features in edges.values_mut() {
features.sort_unstable();
}
edges
}
fn share(edges: &HashMap<(Pt, Pt), Vec<u32>>) -> (f64, f64) {
let (mut shared, mut total) = (0.0, 0.0);
for (&(a, b), features) in edges {
let len = length(a, b);
total += len;
if features.len() >= 2 {
shared += len;
}
}
(shared, total)
}
fn loose_vertices(rings: &[SourceRing], edges: &HashMap<(Pt, Pt), Vec<u32>>) -> Vec<(Pt, u32)> {
let mut loose: Vec<(Pt, u32)> = Vec::new();
for ring in rings {
let n = ring.points.len();
for i in 0..n {
let (a, b) = (ring.points[i], ring.points[(i + 1) % n]);
if edges.get(&edge_key(a, b)).is_some_and(|f| f.len() == 1) {
loose.push((a, ring.feature));
loose.push((b, ring.feature));
}
}
}
loose.sort_unstable();
loose.dedup();
loose
}
type Indexed = GeomWithData<[i64; 2], usize>;
fn index(loose: &[(Pt, u32)]) -> RTree<Indexed> {
RTree::bulk_load(
loose
.iter()
.enumerate()
.map(|(i, &((x, y), _))| GeomWithData::new([x, y], i))
.collect(),
)
}
const fn find(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
i = parent[i];
}
i
}
fn merge_vertices(rings: &mut [SourceRing]) -> usize {
let edges = edge_features(rings);
let loose = loose_vertices(rings, &edges);
let tree = index(&loose);
let mut parent: Vec<usize> = (0..loose.len()).collect();
let t = NODE_TOLERANCE;
for (i, &((x, y), feature)) in loose.iter().enumerate() {
let envelope = AABB::from_corners([x - t, y - t], [x + t, y + t]);
for near in tree.locate_in_envelope(envelope) {
let j = near.data;
let ((nx, ny), other) = loose[j];
if other == feature || (nx - x).pow(2) + (ny - y).pow(2) > t * t {
continue;
}
let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
if ri != rj {
parent[ri.max(rj)] = ri.min(rj);
}
}
}
let mut remap: HashMap<Pt, Pt> = HashMap::new();
for i in 0..loose.len() {
let root = find(&mut parent, i);
if loose[root].0 != loose[i].0 {
remap.insert(loose[i].0, loose[root].0);
}
}
let mut moved = 0;
for ring in rings.iter_mut() {
for p in &mut ring.points {
if let Some(&to) = remap.get(p) {
*p = to;
moved += 1;
}
}
dedup_ring(&mut ring.points);
}
moved
}
fn insert_vertices(rings: &mut [SourceRing]) -> usize {
let edges = edge_features(rings);
let loose = loose_vertices(rings, &edges);
let tree = index(&loose);
let t = NODE_TOLERANCE as f64;
let mut added = 0;
for ring in rings.iter_mut() {
let n = ring.points.len();
let mut out: Vec<Pt> = Vec::with_capacity(n);
for i in 0..n {
let (a, b) = (ring.points[i], ring.points[(i + 1) % n]);
out.push(a);
if !edges.get(&edge_key(a, b)).is_some_and(|f| f.len() == 1) {
continue;
}
let tl = NODE_TOLERANCE;
let envelope = AABB::from_corners(
[a.0.min(b.0) - tl, a.1.min(b.1) - tl],
[a.0.max(b.0) + tl, a.1.max(b.1) + tl],
);
let (dx, dy) = ((b.0 - a.0) as f64, (b.1 - a.1) as f64);
let len2 = dx * dx + dy * dy;
if len2 == 0.0 {
continue;
}
let mut on: Vec<(f64, Pt)> = tree
.locate_in_envelope(envelope)
.filter_map(|near| {
let (p, feature) = loose[near.data];
if feature == ring.feature || p == a || p == b {
return None;
}
let (px, py) = ((p.0 - a.0) as f64, (p.1 - a.1) as f64);
let s = (px * dx + py * dy) / len2;
if s <= 0.0 || s >= 1.0 {
return None;
}
let d = (px * dy - py * dx).abs() / len2.sqrt();
(d <= t).then_some((s, p))
})
.collect();
on.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)));
on.dedup_by(|x, y| x.1 == y.1);
added += on.len();
out.extend(on.into_iter().map(|(_, p)| p));
}
dedup_ring(&mut out);
ring.points = out;
}
added
}
impl Coverage {
#[must_use]
pub fn build(features: &[Vec<&Polygon<f64>>]) -> Self {
let mut slots: Vec<(usize, usize, usize)> = Vec::new();
let mut rings: Vec<SourceRing> = Vec::new();
for (f, polygons) in features.iter().enumerate() {
for (p, polygon) in polygons.iter().enumerate() {
let all = std::iter::once(polygon.exterior()).chain(polygon.interiors());
for (r, ring) in all.enumerate() {
slots.push((f, p, r));
rings.push(SourceRing {
feature: f as u32,
points: fine_ring(ring),
});
}
}
}
let (shared_before, total_before) = share(&edge_features(&rings));
let merged = merge_vertices(&mut rings);
let inserted = insert_vertices(&mut rings);
let edges = edge_features(&rings);
let (shared_after, total_after) = share(&edges);
let mut neighbours: HashMap<Pt, Vec<Pt>> = HashMap::new();
for &(a, b) in edges.keys() {
neighbours.entry(a).or_default().push(b);
neighbours.entry(b).or_default().push(a);
}
let is_node = |p: Pt| match neighbours.get(&p).map(Vec::as_slice) {
Some(&[n0, n1]) => edges.get(&edge_key(p, n0)) != edges.get(&edge_key(p, n1)),
_ => true,
};
let mut arcs: Vec<Vec<Pt>> = Vec::new();
let mut lookup: HashMap<(Pt, Pt), ArcUse> = HashMap::new();
let mut nodes: BTreeSet<Pt> = BTreeSet::new();
let mut uses_of: Vec<Vec<ArcUse>> = Vec::with_capacity(rings.len());
for ring in &rings {
let points = &ring.points;
let n = points.len();
if n < 3 {
uses_of.push(Vec::new());
continue;
}
let starts: Vec<usize> = (0..n).filter(|&i| is_node(points[i])).collect();
let mut pieces: Vec<(Vec<Pt>, bool)> = Vec::new();
if let Some(&first) = starts.first() {
nodes.extend(starts.iter().map(|&i| points[i]));
let mut piece = vec![points[first]];
for k in 1..=n {
let p = points[(first + k) % n];
piece.push(p);
if is_node(p) {
pieces.push((std::mem::replace(&mut piece, vec![p]), false));
}
}
} else {
let start = (0..n).min_by_key(|&i| points[i]).unwrap_or(0);
let mut piece: Vec<Pt> = (0..=n).map(|k| points[(start + k) % n]).collect();
let flipped = piece[n - 1] < piece[1];
if flipped {
piece.reverse();
}
pieces.push((piece, flipped));
}
let mut uses = Vec::with_capacity(pieces.len());
for (piece, flipped) in pieces {
let m = piece.len();
let key = (piece[0], piece[1]);
let found = lookup.get(&key).copied().filter(|u| {
let arc = &arcs[u.arc];
arc.len() == m
&& if u.reversed {
arc.iter().rev().eq(piece.iter())
} else {
*arc == piece
}
});
let used = if let Some(u) = found {
u
} else {
let arc = arcs.len();
lookup.entry(key).or_insert(ArcUse {
arc,
reversed: false,
});
lookup
.entry((piece[m - 1], piece[m - 2]))
.or_insert(ArcUse {
arc,
reversed: true,
});
arcs.push(piece);
ArcUse {
arc,
reversed: false,
}
};
uses.push(ArcUse {
arc: used.arc,
reversed: used.reversed != flipped,
});
}
uses_of.push(uses);
}
let mut out: Vec<Vec<Vec<Vec<ArcUse>>>> = features
.iter()
.map(|polygons| {
polygons
.iter()
.map(|p| vec![Vec::new(); 1 + p.interiors().len()])
.collect()
})
.collect();
for ((&(f, p, r), mut uses), ring) in slots.iter().zip(uses_of).zip(&rings) {
if (area2(&ring.points) > 0) != (r == 0) {
uses.reverse();
for u in &mut uses {
u.reversed = !u.reversed;
}
}
out[f][p][r] = uses;
}
let stats = BorderStats {
shared_before,
shared_after,
total_before,
total_after,
merged,
inserted,
arcs: arcs.len(),
nodes: nodes.len(),
};
Self {
arcs,
features: out,
stats,
}
}
fn simplified_arcs(&self, z: u8) -> (Vec<Vec<Pt>>, usize, usize) {
let shift = FINE_BITS - 12 - u32::from(z.min(MAX_ZOOM));
let unsnapped: Vec<Vec<Fp>> = self.arcs.iter().map(|a| zoom_arc(a, shift)).collect();
let mut tolerance = vec![SIMPLIFY_UNITS; unsnapped.len()];
let mut simplified: Vec<Vec<Fp>> = unsnapped
.iter()
.map(|a| simplify_arc(a, SIMPLIFY_UNITS))
.collect();
let mut repaired: BTreeSet<usize> = BTreeSet::new();
for _ in 0..REPAIR_ROUNDS {
let crossing = crossing_arcs(&simplified);
let mut changed = false;
for &arc in &crossing {
if tolerance[arc] > 0.0 {
tolerance[arc] = if tolerance[arc] <= MIN_SIMPLIFY_UNITS {
0.0
} else {
tolerance[arc] / 2.0
};
simplified[arc] = simplify_arc(&unsnapped[arc], tolerance[arc]);
repaired.insert(arc);
changed = true;
}
}
if !changed {
break;
}
}
let snapped = snap_round(&simplified);
let crossing = proper_crossings(&snapped);
(snapped, repaired.len(), crossing)
}
#[must_use]
pub fn rings_at_zoom(&self, z: u8) -> (Vec<FeatureRings>, ZoomStats) {
let (simplified, repaired, crossing) = self.simplified_arcs(z);
let mut stats = ZoomStats {
vertices: simplified.iter().map(Vec::len).sum(),
repaired,
crossing,
dropped_rings: 0,
};
let features = self
.features
.iter()
.map(|polygons| {
let mut out: FeatureRings = Vec::new();
for rings in polygons {
let built: Vec<Vec<Pt>> = rings
.iter()
.map(|uses| assemble(&simplified, uses))
.collect();
let has_area = |ring: &Vec<Pt>| ring.len() >= 3 && area2(ring) != 0;
if !built.first().is_some_and(has_area) {
stats.dropped_rings += built.len();
continue;
}
let kept: Vec<Vec<Pt>> = built.into_iter().filter(has_area).collect();
stats.dropped_rings += rings.len() - kept.len();
out.push(kept);
}
out
})
.collect();
(features, stats)
}
}
type Fp = [f64; 2];
fn zoom_arc(arc: &[Pt], shift: u32) -> Vec<Fp> {
let unit = f64::from(1_u32 << shift);
let mut out: Vec<Fp> = arc
.iter()
.map(|&(x, y)| [x as f64 / unit, y as f64 / unit])
.collect();
out.dedup();
out
}
fn segment_distance(p: Fp, a: Fp, b: Fp) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let (px, py) = (p[0] - a[0], p[1] - a[1]);
let len2 = dx * dx + dy * dy;
if len2 == 0.0 {
return px.hypot(py);
}
let s = ((px * dx + py * dy) / len2).clamp(0.0, 1.0);
(px - s * dx).hypot(py - s * dy)
}
fn douglas_peucker(points: &[Fp], from: usize, to: usize, tolerance: f64, keep: &mut [bool]) {
let mut stack = vec![(from, to)];
while let Some((i, j)) = stack.pop() {
if j <= i + 1 {
continue;
}
let (mut far, mut far_d) = (i, -1.0);
for k in i + 1..j {
let d = segment_distance(points[k], points[i], points[j]);
if d > far_d {
(far, far_d) = (k, d);
}
}
if far_d > tolerance {
keep[far] = true;
stack.push((i, far));
stack.push((far, j));
}
}
}
fn despike(points: Vec<Pt>) -> Vec<Pt> {
let mut out: Vec<Pt> = Vec::with_capacity(points.len());
for p in points {
if out.last() == Some(&p) {
continue;
}
out.push(p);
while out.len() >= 3 {
let n = out.len();
let (a, b, c) = (out[n - 3], out[n - 2], out[n - 1]);
let back = (i128::from(b.0 - a.0) * i128::from(c.1 - a.1)
== i128::from(b.1 - a.1) * i128::from(c.0 - a.0))
&& (b.0 - a.0) * (c.0 - b.0) + (b.1 - a.1) * (c.1 - b.1) <= 0;
if !back {
break;
}
out.remove(n - 2);
if out[n - 3] == out[n - 2] {
out.pop();
}
}
}
out
}
fn simplify_arc(arc: &[Fp], tolerance: f64) -> Vec<Fp> {
let n = arc.len();
if n <= 2 {
return arc.to_vec();
}
let mut keep = vec![false; n];
keep[0] = true;
keep[n - 1] = true;
if arc[0] == arc[n - 1] {
let dist = |k: usize| (arc[k][0] - arc[0][0]).hypot(arc[k][1] - arc[0][1]);
let far = (1..n - 1)
.max_by(|&a, &b| dist(a).total_cmp(&dist(b)).then(b.cmp(&a)))
.unwrap_or(1);
keep[far] = true;
douglas_peucker(arc, 0, far, tolerance, &mut keep);
douglas_peucker(arc, far, n - 1, tolerance, &mut keep);
if keep.iter().filter(|&&k| k).count() < 4 && n >= 4 {
let side = |k: usize| segment_distance(arc[k], arc[0], arc[far]);
let third = (1..n - 1)
.filter(|&k| k != far)
.max_by(|&a, &b| side(a).total_cmp(&side(b)).then(b.cmp(&a)))
.unwrap_or(far);
keep[third] = true;
}
} else {
douglas_peucker(arc, 0, n - 1, tolerance, &mut keep);
}
arc.iter()
.zip(keep)
.filter_map(|(&p, k)| k.then_some(p))
.collect()
}
const fn round(p: Fp) -> Pt {
(p[0].round() as i64, p[1].round() as i64)
}
fn snap_round(arcs: &[Vec<Fp>]) -> Vec<Vec<Pt>> {
let mut hot: HashSet<Pt> = arcs.iter().flatten().map(|&p| round(p)).collect();
for_each_close_pair(arcs, |a, i, b, j| {
let (p, q) = (arcs[a][i], arcs[a][i + 1]);
let (r, s) = (arcs[b][j], arcs[b][j + 1]);
if let Some(x) = crossing_point(p, q, r, s) {
hot.insert(round(x));
}
});
arcs.iter()
.map(|arc| {
let mut out: Vec<Pt> = Vec::with_capacity(arc.len());
if let Some(&first) = arc.first() {
out.push(round(first));
}
for w in arc.windows(2) {
let (a, b) = (w[0], w[1]);
let mut on: Vec<(f64, Pt)> = Vec::new();
let mut seen: HashSet<Pt> = HashSet::new();
let mut consider = |c: Pt| {
for dx in -1..=1 {
for dy in -1..=1 {
let h = (c.0 + dx, c.1 + dy);
if !seen.insert(h) || !hot.contains(&h) || !touches_cell(a, b, h) {
continue;
}
on.push((projection(a, b, h), h));
}
}
};
consider(round(a));
cells_along(a, b, &mut consider);
on.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.cmp(&y.1)));
out.extend(on.into_iter().map(|(_, h)| h));
out.push(round(b));
}
despike(out)
})
.collect()
}
fn touches_cell(a: Fp, b: Fp, c: Pt) -> bool {
let (x0, x1) = (c.0 as f64 - 0.5, c.0 as f64 + 0.5);
let (y0, y1) = (c.1 as f64 - 0.5, c.1 as f64 + 0.5);
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
for (p, q) in [
(-dx, a[0] - x0),
(dx, x1 - a[0]),
(-dy, a[1] - y0),
(dy, y1 - a[1]),
] {
if p == 0.0 {
if q < 0.0 {
return false;
}
} else {
let r = q / p;
if p < 0.0 {
t0 = t0.max(r);
} else {
t1 = t1.min(r);
}
}
}
t0 <= t1
}
fn projection(a: Fp, b: Fp, c: Pt) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let len2 = dx * dx + dy * dy;
if len2 == 0.0 {
return 0.0;
}
(((c.0 as f64 - a[0]) * dx + (c.1 as f64 - a[1]) * dy) / len2).clamp(0.0, 1.0)
}
fn crossing_point(p: Fp, q: Fp, r: Fp, s: Fp) -> Option<Fp> {
let (d1, d2) = ([q[0] - p[0], q[1] - p[1]], [s[0] - r[0], s[1] - r[1]]);
let den = d1[0] * d2[1] - d1[1] * d2[0];
if den == 0.0 {
return None;
}
let (ex, ey) = (r[0] - p[0], r[1] - p[1]);
let t = (ex * d2[1] - ey * d2[0]) / den;
let u = (ex * d1[1] - ey * d1[0]) / den;
((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u))
.then(|| [p[0] + t * d1[0], p[1] + t * d1[1]])
}
fn cells_along(a: Fp, b: Fp, mut visit: impl FnMut(Pt)) {
let cell = |v: f64| (v + 0.5).floor() as i64;
let (mut x, mut y) = (cell(a[0]), cell(a[1]));
let (end_x, end_y) = (cell(b[0]), cell(b[1]));
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let (step_x, step_y) = (dx.signum() as i64, dy.signum() as i64);
let next = |v: i64, step: i64| v as f64 + 0.5 * step as f64;
let mut t_x = if dx == 0.0 {
f64::INFINITY
} else {
(next(x, step_x) - a[0]) / dx
};
let mut t_y = if dy == 0.0 {
f64::INFINITY
} else {
(next(y, step_y) - a[1]) / dy
};
let (dt_x, dt_y) = (1.0 / dx.abs(), 1.0 / dy.abs());
let mut left = (end_x - x).abs() + (end_y - y).abs();
while (x, y) != (end_x, end_y) && left > 0 {
if t_x < t_y {
x += step_x;
t_x += dt_x;
} else {
y += step_y;
t_y += dt_y;
}
left -= 1;
visit((x, y));
}
}
fn orient(a: Fp, b: Fp, c: Fp) -> f64 {
((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])).signum_or_zero()
}
trait SignumOrZero {
fn signum_or_zero(self) -> f64;
}
impl SignumOrZero for f64 {
fn signum_or_zero(self) -> f64 {
if self == 0.0 { 0.0 } else { self.signum() }
}
}
fn within(p: Fp, a: Fp, b: Fp) -> bool {
p[0] >= a[0].min(b[0])
&& p[0] <= a[0].max(b[0])
&& p[1] >= a[1].min(b[1])
&& p[1] <= a[1].max(b[1])
}
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Contact {
None,
SharedEnd,
Bad,
}
#[must_use]
pub fn contact(a: Pt, b: Pt, c: Pt, d: Pt) -> Contact {
let f = |p: Pt| [p.0 as f64, p.1 as f64];
contact_f(f(a), f(b), f(c), f(d))
}
fn contact_f(a: Fp, b: Fp, c: Fp, d: Fp) -> Contact {
if a[0].max(b[0]) < c[0].min(d[0])
|| c[0].max(d[0]) < a[0].min(b[0])
|| a[1].max(b[1]) < c[1].min(d[1])
|| c[1].max(d[1]) < a[1].min(b[1])
{
return Contact::None;
}
let (o1, o2) = (orient(a, b, c), orient(a, b, d));
let (o3, o4) = (orient(c, d, a), orient(c, d, b));
if o1 * o2 > 0.0 || o3 * o4 > 0.0 {
return Contact::None;
}
if o1 == 0.0 && o2 == 0.0 {
let mut touching: Vec<Fp> = [
(c, within(c, a, b)),
(d, within(d, a, b)),
(a, within(a, c, d)),
(b, within(b, c, d)),
]
.into_iter()
.filter_map(|(p, w)| w.then_some(p))
.collect();
touching.sort_by(|p, q| p[0].total_cmp(&q[0]).then(p[1].total_cmp(&q[1])));
touching.dedup();
return match touching.as_slice() {
[] => Contact::None,
[p] if (*p == a || *p == b) && (*p == c || *p == d) => Contact::SharedEnd,
_ => Contact::Bad,
};
}
if [a, b].iter().any(|p| *p == c || *p == d) {
Contact::SharedEnd
} else {
Contact::Bad
}
}
fn for_each_close_pair(arcs: &[Vec<Fp>], mut f: impl FnMut(usize, usize, usize, usize)) {
let cell = SEARCH_CELL as f64;
let mut cells: HashMap<(i64, i64), Vec<(usize, usize)>> = HashMap::new();
for (a, arc) in arcs.iter().enumerate() {
for i in 0..arc.len().saturating_sub(1) {
let (p, q) = (arc[i], arc[i + 1]);
let (x0, x1) = (
(p[0].min(q[0]) / cell).floor() as i64,
(p[0].max(q[0]) / cell).floor() as i64,
);
let (y0, y1) = (
(p[1].min(q[1]) / cell).floor() as i64,
(p[1].max(q[1]) / cell).floor() as i64,
);
for x in x0..=x1 {
for y in y0..=y1 {
cells.entry((x, y)).or_default().push((a, i));
}
}
}
}
let mut keys: Vec<&(i64, i64)> = cells.keys().collect();
keys.sort_unstable();
for key in keys {
let segments = &cells[key];
for (k, &(a, i)) in segments.iter().enumerate() {
for &(b, j) in &segments[k + 1..] {
f(a, i, b, j);
}
}
}
}
fn crossing_arcs(arcs: &[Vec<Fp>]) -> BTreeSet<usize> {
let is_end = |arc: &[Fp], p: Fp| arc.first() == Some(&p) || arc.last() == Some(&p);
let mut bad: BTreeSet<usize> = BTreeSet::new();
for_each_close_pair(arcs, |a, i, b, j| {
let (arc_a, arc_b) = (&arcs[a], &arcs[b]);
let (p, q) = (arc_a[i], arc_a[i + 1]);
let (r, s) = (arc_b[j], arc_b[j + 1]);
if a != b && ((p, q) == (r, s) || (p, q) == (s, r)) {
return;
}
let ok = match contact_f(p, q, r, s) {
Contact::None => true,
Contact::Bad => false,
Contact::SharedEnd => {
let shared = if p == r || p == s { p } else { q };
if a == b {
let last = arc_a.len() - 2;
i.abs_diff(j) == 1
|| (arc_a.first() == arc_a.last()
&& is_end(arc_a, shared)
&& i.min(j) == 0
&& i.max(j) == last)
} else {
is_end(arc_a, shared) && is_end(arc_b, shared)
}
}
};
if !ok {
bad.insert(a);
bad.insert(b);
}
});
bad
}
fn proper_crossings(arcs: &[Vec<Pt>]) -> usize {
let f: Vec<Vec<Fp>> = arcs
.iter()
.map(|a| a.iter().map(|p| [p.0 as f64, p.1 as f64]).collect())
.collect();
let mut pairs: BTreeSet<(usize, usize, usize, usize)> = BTreeSet::new();
for_each_close_pair(&f, |a, i, b, j| {
let (p, q, r, s) = (f[a][i], f[a][i + 1], f[b][j], f[b][j + 1]);
let (o1, o2) = (orient(p, q, r), orient(p, q, s));
let (o3, o4) = (orient(r, s, p), orient(r, s, q));
if o1 * o2 < 0.0 && o3 * o4 < 0.0 {
pairs.insert((a, i, b, j));
}
});
pairs.len()
}
fn assemble(arcs: &[Vec<Pt>], uses: &[ArcUse]) -> Vec<Pt> {
let mut ring: Vec<Pt> = Vec::new();
for u in uses {
let arc = &arcs[u.arc];
let Some((_, rest)) = arc.split_last() else {
continue;
};
if u.reversed {
let reversed: Vec<Pt> = arc.iter().rev().copied().collect();
ring.extend_from_slice(&reversed[..reversed.len() - 1]);
} else {
ring.extend_from_slice(rest);
}
}
dedup_ring(&mut ring);
ring
}
#[must_use]
pub fn area2(ring: &[Pt]) -> i128 {
let n = ring.len();
(0..n)
.map(|i| {
let (a, b) = (ring[i], ring[(i + 1) % n]);
i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1)
})
.sum()
}
pub const EXTENT: i64 = TILE_EXTENT as i64;
#[cfg(test)]
mod tests {
use super::*;
use geo::{LineString, Polygon};
fn square(x: f64, y: f64, s: f64) -> LineString<f64> {
LineString::from(vec![(x, y), (x + s, y), (x + s, y + s), (x, y + s), (x, y)])
}
#[test]
#[ignore = "needs a real areas dir"]
fn real_india_crossings() {
let Some(dir) = crate::settings::current().run.areas_dir.clone() else {
return;
};
let dir = dir.as_path();
let file = crate::areas::read_areas_geojson(&dir.join("areas.geojson")).expect("areas");
let bytes = std::fs::read(dir.join("gaps.geojson")).expect("gaps");
let gaps: geojson::FeatureCollection = serde_json::from_slice(&bytes).expect("gaps json");
let mut features: Vec<Vec<Polygon<f64>>> =
file.areas.iter().map(|a| a.shape.0.clone()).collect();
for g in gaps.features {
let geometry = g.geometry.expect("geometry");
match geo::Geometry::<f64>::try_from(geometry).expect("geo") {
geo::Geometry::Polygon(p) => features.push(vec![p]),
geo::Geometry::MultiPolygon(m) => features.push(m.0),
_ => {}
}
}
let coverage = build(&features);
eprintln!("{:?}", coverage.stats);
for z in 0..=8 {
let (_, stats) = coverage.rings_at_zoom(z);
eprintln!("z{z}: {stats:?}");
}
}
#[test]
fn contact_kinds() {
assert_eq!(contact((0, 0), (4, 4), (0, 4), (4, 0)), Contact::Bad);
assert_eq!(contact((0, 0), (4, 0), (4, 0), (4, 4)), Contact::SharedEnd);
assert_eq!(contact((0, 0), (4, 0), (2, 0), (2, 4)), Contact::Bad);
assert_eq!(contact((0, 0), (4, 0), (2, 0), (6, 0)), Contact::Bad);
assert_eq!(contact((0, 0), (4, 0), (4, 0), (6, 0)), Contact::SharedEnd);
assert_eq!(contact((0, 0), (4, 0), (0, 1), (4, 1)), Contact::None);
assert_eq!(contact((0, 0), (4, 0), (4, 0), (2, 0)), Contact::Bad);
}
fn hole(x: f64, y: f64, s: f64) -> LineString<f64> {
let mut ring = square(x, y, s);
ring.0.reverse();
ring
}
fn synthetic() -> Vec<Vec<Polygon<f64>>> {
vec![
vec![Polygon::new(
square(0.0, 0.0, 1.0),
vec![hole(0.25, 0.25, 0.5)],
)],
vec![Polygon::new(square(1.0, 0.0, 1.0), vec![])],
vec![Polygon::new(square(0.0, 1.0, 1.0), vec![])],
vec![Polygon::new(square(1.0, 1.0, 1.0), vec![])],
vec![Polygon::new(square(0.25, 0.25, 0.5), vec![])],
vec![
Polygon::new(square(3.0, 3.0, 0.5), vec![]),
Polygon::new(square(5.0, 0.0, 1.0), vec![square(5.25, 0.25, 0.5)]),
],
]
}
fn build(features: &[Vec<Polygon<f64>>]) -> Coverage {
let refs: Vec<Vec<&Polygon<f64>>> = features.iter().map(|f| f.iter().collect()).collect();
Coverage::build(&refs)
}
#[test]
fn arcs_split_at_junctions() {
let coverage = build(&synthetic());
assert_eq!(coverage.stats.nodes, 5, "{:?}", coverage.stats);
assert_eq!(coverage.stats.arcs, 12, "{:?}", coverage.stats);
assert!((coverage.stats.shared_after - coverage.stats.shared_before).abs() < 1e-9);
}
#[test]
fn a_shared_arc_is_stored_once_and_used_both_ways() {
let coverage = build(&synthetic());
let mut count: HashMap<usize, Vec<bool>> = HashMap::new();
for feature in &coverage.features {
for polygon in feature {
for ring in polygon {
for u in ring {
count.entry(u.arc).or_default().push(u.reversed);
}
}
}
}
let mut shared: Vec<(&usize, &Vec<bool>)> =
count.iter().filter(|v| v.1.len() == 2).collect();
shared.sort();
assert_eq!(shared.len(), 5);
for (arc, uses) in shared {
assert_ne!(uses[0], uses[1], "arc {arc}: neighbours walk it both ways");
}
}
#[test]
fn rings_rebuild_with_holes_and_islands() {
let coverage = build(&synthetic());
for z in [0, 4, 8] {
let (features, stats) = coverage.rings_at_zoom(z);
assert_eq!(stats.crossing, 0, "z{z}");
assert_eq!(features[0][0].len(), 2, "z{z}: exterior and hole");
assert_eq!(features[5].len(), 2, "z{z}: island and holed square");
assert_eq!(features[5][1].len(), 2, "z{z}");
let mut hole = features[0][0][1].clone();
let mut enclave = features[4][0][0].clone();
hole.sort_unstable();
enclave.sort_unstable();
assert_eq!(hole, enclave, "z{z}");
for f in &features {
for polygon in f {
for ring in polygon {
assert!(area2(ring) != 0, "z{z}: ring with no area");
}
}
}
}
}
#[test]
fn near_coincident_borders_share_vertices() {
let left = Polygon::new(square(0.0, 0.0, 1.0), vec![]);
let e = 1e-6;
let right = Polygon::new(
LineString::from(vec![
(1.0 + e, 0.0),
(2.0, 0.0),
(2.0, 1.0),
(1.0 - e, 1.0),
(1.0, 0.5),
(1.0 + e, 0.0),
]),
vec![],
);
let coverage = build(&[vec![left], vec![right]]);
let s = coverage.stats;
assert!(s.shared_before < 1.0, "{s:?}");
assert!(s.merged >= 2 && s.inserted >= 1, "{s:?}");
let full = f64::from(1_u32 << FINE_BITS);
let side = full / 360.0;
assert!((s.shared_after - side).abs() < side * 1e-3, "{s:?}");
}
#[test]
fn a_wiggly_shared_border_simplifies_once() {
let wiggle: Vec<(f64, f64)> = (0..=200)
.map(|i| {
let y = f64::from(i) * 0.01;
(1.0 + 0.003 * (f64::from(i) * 0.7).sin(), y)
})
.collect();
let mut left: Vec<(f64, f64)> = vec![(0.0, 0.0)];
left.extend(wiggle.iter().copied());
left.extend([(0.0, 2.0), (0.0, 0.0)]);
let mut right: Vec<(f64, f64)> = vec![(2.0, 0.0), (2.0, 2.0)];
right.extend(wiggle.iter().rev().copied());
right.push((2.0, 0.0));
let features = vec![
vec![Polygon::new(LineString::from(left), vec![])],
vec![Polygon::new(LineString::from(right), vec![])],
];
let coverage = build(&features);
for z in 0..=8 {
let (rings, stats) = coverage.rings_at_zoom(z);
assert_eq!(stats.crossing, 0, "z{z}");
let edges = |ring: &[Pt]| -> BTreeSet<(Pt, Pt)> {
(0..ring.len())
.map(|i| edge_key(ring[i], ring[(i + 1) % ring.len()]))
.collect()
};
let (a, b) = (edges(&rings[0][0][0]), edges(&rings[1][0][0]));
let common = a.intersection(&b).count();
assert_eq!(common, a.len() - 3, "z{z}");
}
}
}