use geo::{Coord, Geometry, LineString, MultiLineString, MultiPolygon, Polygon};
pub const RADIUS: f64 = 6_378_137.0;
const EPS: f64 = 1e-7;
const STEP: f64 = 1.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ortho {
lon0: f64,
sin0: f64,
cos0: f64,
}
type V3 = (f64, f64, f64);
impl Ortho {
pub fn new(lon0: f64, lat0: f64) -> Ortho {
let (sin0, cos0) = lat0.to_radians().sin_cos();
Ortho { lon0, sin0, cos0 }
}
pub fn parse(definition: &str) -> Option<Ortho> {
let words: Vec<&str> = definition.split_whitespace().collect();
if !words.contains(&"+proj=ortho") {
return None;
}
let value = |key: &str| words.iter().find_map(|w| w.strip_prefix(key)).and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
Some(Ortho::new(value("+lon_0="), value("+lat_0=")))
}
fn turn(&self, lon: f64, lat: f64) -> V3 {
let (sp, cp) = lat.to_radians().sin_cos();
let (sl, cl) = (lon - self.lon0).to_radians().sin_cos();
(cp * sl, self.cos0 * sp - self.sin0 * cp * cl, self.sin0 * sp + self.cos0 * cp * cl)
}
fn back(&self, (x, y, z): V3) -> (f64, f64) {
let lat = (y * self.cos0 + z * self.sin0).clamp(-1.0, 1.0).asin();
let lon = x.atan2(z * self.cos0 - y * self.sin0);
(wrap(self.lon0 + lon.to_degrees()), lat.to_degrees())
}
pub fn forward(&self, lon: f64, lat: f64) -> (f64, f64) {
let (x, y, z) = self.turn(lon, lat);
if z < -EPS {
return (f64::NAN, f64::NAN);
}
(RADIUS * x, RADIUS * y)
}
pub fn inverse(&self, x: f64, y: f64) -> Option<(f64, f64)> {
let (x, y) = (x / RADIUS, y / RADIUS);
let r2 = x * x + y * y;
if r2 > 1.0 + 1e-12 {
return None;
}
Some(self.back((x, y, (1.0 - r2).max(0.0).sqrt())))
}
pub fn ground(&self, radius: f64) -> geo::Polygon<f64> {
let r = radius.clamp(0.0, 90.0);
let lat0 = self.sin0.atan2(self.cos0).to_degrees();
let (mut south, mut north) = (lat0 - r, lat0 + r);
let (mut west, mut east) = (-180.0, 180.0);
if north >= 90.0 {
north = 90.0;
} else if south <= -90.0 {
south = -90.0;
} else {
let s = r.to_radians().sin() / lat0.to_radians().cos();
if s < 1.0 {
let d = s.asin().to_degrees();
if self.lon0 - d >= -180.0 && self.lon0 + d <= 180.0 {
(west, east) = (self.lon0 - d, self.lon0 + d);
}
}
}
geo::Polygon::new(LineString::from(vec![(west, south), (east, south), (east, north), (west, north), (west, south)]), vec![])
}
pub fn distance(&self, lon: f64, lat: f64) -> f64 {
self.turn(lon, lat).2.clamp(-1.0, 1.0).acos().to_degrees()
}
pub fn visible(&self, g: &Geometry<f64>) -> Geometry<f64> {
match g {
Geometry::Point(p) => {
Geometry::Point(*p)
}
Geometry::MultiPoint(m) => Geometry::MultiPoint(m.iter().filter(|p| self.turn(p.x(), p.y()).2 >= -EPS).copied().collect()),
Geometry::Line(l) => self.visible(&Geometry::LineString(LineString::new(vec![l.start, l.end]))),
Geometry::LineString(l) => Geometry::MultiLineString(MultiLineString::new(self.lines(l))),
Geometry::MultiLineString(m) => Geometry::MultiLineString(MultiLineString::new(m.iter().flat_map(|l| self.lines(l)).collect())),
Geometry::Polygon(p) => Geometry::MultiPolygon(MultiPolygon::new(self.polygons(p))),
Geometry::MultiPolygon(m) => Geometry::MultiPolygon(MultiPolygon::new(m.iter().flat_map(|p| self.polygons(p)).collect())),
Geometry::Rect(r) => self.visible(&Geometry::Polygon(r.to_polygon())),
Geometry::Triangle(t) => self.visible(&Geometry::Polygon(t.to_polygon())),
Geometry::GeometryCollection(c) => Geometry::GeometryCollection(c.iter().map(|g| self.visible(g)).collect()),
}
}
fn dense(&self, l: &LineString<f64>) -> Vec<V3> {
self.dense_lonlat(l).into_iter().map(|(p, _)| p).collect()
}
fn dense_lonlat(&self, l: &LineString<f64>) -> Vec<(V3, (f64, f64))> {
let turn = |x: f64, y: f64| self.turn(if x >= 180.0 { x - 360.0 } else { x }, y);
let snap = |c: Coord<f64>| {
if (c.x.abs() - 180.0).abs() < SEAM {
Coord { x: 180.0f64.copysign(c.x), y: c.y }
} else {
c
}
};
let mut seam: Vec<f64> = l.0.iter().map(|&c| snap(c)).filter(|c| c.x.abs() == 180.0).map(|c| c.y).collect();
seam.sort_by(f64::total_cmp);
seam.dedup();
let mut out = Vec::with_capacity(l.0.len());
for (i, &c) in l.0.iter().enumerate() {
let c = snap(c);
if i > 0 {
let a = snap(l.0[i - 1]);
let (pa, pc) = (turn(a.x, a.y), turn(c.x, c.y));
let same = (pa.0 - pc.0).abs() + (pa.1 - pc.1).abs() + (pa.2 - pc.2).abs() < 1e-12;
if same {
} else if a.x == c.x || a.y == c.y {
let (from, to) = if a.x == c.x { (a.y, c.y) } else { (a.x, c.x) };
let (lo, hi) = (from.min(to), from.max(to));
let mut cuts: Vec<f64> = ((lo / STEP).floor() as i64 + 1..=(hi / STEP).ceil() as i64 - 1).map(|k| k as f64 * STEP).filter(|v| *v > lo && *v < hi).collect();
if a.x == c.x && a.x.abs() == 180.0 {
cuts.extend(seam.iter().copied().filter(|v| *v > lo && *v < hi));
cuts.sort_by(f64::total_cmp);
cuts.dedup();
}
if to < from {
cuts.reverse();
}
for v in cuts {
let (x, y) = if a.x == c.x { (a.x, v) } else { (v, a.y) };
out.push((turn(x, y), (x, y)));
}
} else {
let n = ((c.x - a.x).abs().max((c.y - a.y).abs()) / STEP).ceil() as usize;
for k in 1..n {
let t = k as f64 / n as f64;
let (x, y) = (a.x + (c.x - a.x) * t, a.y + (c.y - a.y) * t);
out.push((turn(x, y), (x, y)));
}
}
}
out.push((turn(c.x, c.y), (c.x, c.y)));
}
out
}
fn lines(&self, l: &LineString<f64>) -> Vec<LineString<f64>> {
let pts = self.dense(l);
let mut runs = Vec::new();
let mut run: Vec<Coord<f64>> = Vec::new();
for (i, &p) in pts.iter().enumerate() {
let seen = p.2 >= EPS;
if i > 0 {
let q = pts[i - 1];
if (q.2 >= EPS) != seen {
run.push(self.coord(cross(q, p)));
if !seen {
runs.push(LineString::new(std::mem::take(&mut run)));
}
}
}
if seen {
run.push(self.coord(p));
}
}
if run.len() >= 2 {
runs.push(LineString::new(run));
}
runs.retain(|r| r.0.len() >= 2);
runs
}
fn coord(&self, p: V3) -> Coord<f64> {
let (x, y) = self.back(p);
Coord { x, y }
}
fn rings(&self, l: &LineString<f64>, ccw: bool) -> Vec<Vec<V3>> {
let (mut pts, mut lonlat): (Vec<V3>, Vec<(f64, f64)>) = self.dense_lonlat(l).into_iter().unzip();
if pts.len() > 1 && pts.first() == pts.last() {
pts.pop();
lonlat.pop();
}
let n = pts.len();
if n < 3 {
return Vec::new();
}
let seen = |p: &V3| p.2 >= EPS;
if pts.iter().all(seen) {
let ring = unspiked(pts);
return if ring.len() >= 3 { vec![ring] } else { Vec::new() };
}
if !pts.iter().any(seen) {
return if self.holds_centre(l) { vec![rim(ccw)] } else { Vec::new() };
}
let start = (0..n).find(|&i| !seen(&pts[i])).unwrap();
let mut runs: Vec<(V3, Vec<V3>, V3)> = Vec::new();
let mut hidden: Vec<(usize, usize)> = Vec::new(); let mut current: Option<(V3, Vec<V3>, usize)> = None;
for k in 1..=n {
let (qi, pi) = ((start + k - 1) % n, (start + k) % n);
let (q, p) = (pts[qi], pts[pi]);
match (seen(&q), seen(&p)) {
(false, true) => current = Some((cross(q, p), vec![inward(p)], qi)),
(true, true) => {
if let Some((_, run, _)) = current.as_mut() {
run.push(inward(p));
}
}
(true, false) => {
if let Some((entry, run, before)) = current.take() {
runs.push((entry, run, cross(q, p)));
hidden.push((before, pi));
}
}
(false, false) => {}
}
}
let encloses = |a: usize, b: usize| {
let (from, to) = (hidden[a].1, hidden[b].0);
let len = (to + n - from) % n + 1;
let ll: Vec<(f64, f64)> = (0..len).map(|k| lonlat[(from + k) % n]).collect();
let twice: f64 = (0..ll.len()).map(|i| {
let (p, q) = (ll[i], ll[(i + 1) % ll.len()]);
p.0 * q.1 - q.0 * p.1
}).sum();
twice.abs() / 2.0 > 1.0 };
let angle = |p: &V3| p.1.atan2(p.0);
let along = |i: usize, j: usize| {
let (a, b) = (&runs[i].2, &runs[j].0);
let d = if ccw { angle(b) - angle(a) } else { angle(a) - angle(b) };
let d = d.rem_euclid(std::f64::consts::TAU);
if d < 1e-9 || std::f64::consts::TAU - d < 1e-9 {
if encloses(i, j) { std::f64::consts::TAU } else { 0.0 }
} else {
d
}
};
let mut used = vec![false; runs.len()];
let mut out = Vec::new();
for first in 0..runs.len() {
if used[first] {
continue;
}
let mut ring: Vec<V3> = Vec::new();
let mut i = first;
for _ in 0..=runs.len() {
used[i] = true;
let (entry, run, exit) = &runs[i];
ring.push(*entry);
ring.extend(run.iter().copied());
ring.push(*exit);
let next = (0..runs.len()).min_by(|&a, &b| along(i, a).total_cmp(&along(i, b))).unwrap();
ring.extend(horizon(*exit, along(i, next) * if ccw { 1.0 } else { -1.0 }));
if next == first {
break;
}
if used[next] {
break;
}
i = next;
}
let ring = unspiked(ring);
if ring.len() >= 3 {
out.push(ring);
}
}
out
}
fn holds_centre(&self, l: &LineString<f64>) -> bool {
let lat0 = self.sin0.atan2(self.cos0).to_degrees();
let (x, y) = (self.lon0, lat0);
let mut inside = false;
for w in l.0.windows(2) {
let (a, b) = (w[0], w[1]);
if (a.y > y) != (b.y > y) && x < a.x + (y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
inside
}
fn to_ring(&self, pts: Vec<V3>) -> LineString<f64> {
let mut ring: Vec<Coord<f64>> = pts.into_iter().map(|p| self.coord(p)).collect();
ring.push(ring[0]);
LineString::new(ring)
}
fn polygons(&self, p: &Polygon<f64>) -> Vec<Polygon<f64>> {
let turned = |l: &LineString<f64>, ccw: bool| {
if (signed_area(l) > 0.0) == ccw {
l.clone()
} else {
LineString::new(l.0.iter().rev().copied().collect())
}
};
let outsides = self.rings(&turned(p.exterior(), true), true);
if outsides.is_empty() {
return Vec::new();
}
let on_seam = p.exterior().0.iter().any(|c| c.x.abs() > 180.0 - SEAM)
&& outsides.iter().any(|o| {
let flat = LineString::new(o.iter().chain(o.first()).map(|p| Coord { x: p.0, y: p.1 }).collect::<Vec<_>>());
!geo::Validation::is_valid(&Polygon::new(flat, vec![]))
});
let (outsides, mut made): (Vec<Vec<V3>>, Vec<Vec<Vec<V3>>>) =
if on_seam { resolved(outsides) } else { outsides.into_iter().map(|o| (o, Vec::new())).collect() }.into_iter().unzip();
let holes: Vec<Vec<V3>> = p.interiors().iter().flat_map(|h| self.rings(&turned(h, false), false)).collect();
let flat = |r: &[V3]| LineString::new(r.iter().map(|p| Coord { x: p.0, y: p.1 }).collect::<Vec<_>>());
let shapes: Vec<Polygon<f64>> = outsides.iter().map(|o| Polygon::new(flat(o), vec![])).collect();
let mut given: Vec<Vec<Vec<V3>>> = std::mem::take(&mut made);
for h in holes {
let mid = h.iter().fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1));
let at = geo::Point::new(mid.0 / h.len() as f64, mid.1 / h.len() as f64);
let k = shapes.iter().position(|s| geo::Contains::contains(s, &at)).unwrap_or(0);
given[k].push(h);
}
outsides
.into_iter()
.zip(given)
.map(|(o, hs)| Polygon::new(self.to_ring(o), hs.into_iter().map(|h| self.to_ring(h)).collect()))
.collect()
}
}
const SLIVER: f64 = 1e-7;
fn resolved(outsides: Vec<Vec<V3>>) -> Vec<(Vec<V3>, Vec<Vec<V3>>)> {
use i_overlay::core::fill_rule::FillRule;
use i_overlay::float::simplify::SimplifyShape;
let paths: Vec<Vec<[f64; 2]>> = outsides.iter().filter(|r| r.len() >= 3).map(|r| r.iter().map(|p| [p.0, p.1]).collect()).collect();
let lift = |r: &Vec<[f64; 2]>| -> Vec<V3> { r.iter().map(|&[x, y]| (x, y, (1.0 - x * x - y * y).max(0.0).sqrt())).collect() };
let area = |r: &Vec<[f64; 2]>| (0..r.len()).map(|i| { let (a, b) = (r[i], r[(i + 1) % r.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>().abs() / 2.0;
paths
.simplify_shape(FillRule::NonZero)
.iter()
.filter_map(|shape| {
let (outer, holes) = shape.split_first()?;
(outer.len() >= 3 && area(outer) > SLIVER).then(|| (lift(outer), holes.iter().filter(|h| h.len() >= 3 && area(h) > SLIVER).map(lift).collect()))
})
.collect()
}
fn unspiked(pts: Vec<V3>) -> Vec<V3> {
let close = |a: &V3, b: &V3| (a.0 - b.0).abs() + (a.1 - b.1).abs() + (a.2 - b.2).abs() < 1e-9;
let mut out: Vec<V3> = Vec::with_capacity(pts.len());
for p in pts {
if out.last().is_some_and(|l| close(l, &p)) {
continue;
}
if out.len() >= 2 && close(&out[out.len() - 2], &p) {
out.pop();
continue;
}
out.push(p);
}
loop {
let n = out.len();
if n >= 2 && close(&out[0], &out[n - 1]) {
out.pop();
} else if n >= 3 && close(&out[1], &out[n - 1]) {
out.remove(0);
out.pop();
} else {
break;
}
}
out
}
const SEAM: f64 = 0.1;
const RIM_IN: f64 = 0.999_961_923_064_171;
fn inward(p: V3) -> V3 {
let r = p.0.hypot(p.1);
if r <= RIM_IN * (1.0 - EPS * EPS).sqrt() {
return p;
}
let k = RIM_IN * (1.0 - EPS * EPS).sqrt() / r;
let (x, y) = (p.0 * k, p.1 * k);
(x, y, (1.0 - x * x - y * y).max(0.0).sqrt())
}
fn rim(ccw: bool) -> Vec<V3> {
let r = (1.0 - EPS * EPS).sqrt();
(0..360)
.map(|k| {
let t = (k as f64).to_radians() * if ccw { 1.0 } else { -1.0 };
(r * t.cos(), r * t.sin(), EPS)
})
.collect()
}
fn wrap(lon: f64) -> f64 {
let l = (lon + 180.0).rem_euclid(360.0) - 180.0;
if l == -180.0 && lon > 0.0 { 180.0 } else { l }
}
fn cross(a: V3, b: V3) -> V3 {
let t = ((EPS - a.2) / (b.2 - a.2)).clamp(0.0, 1.0);
let p = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, EPS);
let r = (p.0 * p.0 + p.1 * p.1).sqrt().max(1e-12);
let k = (1.0 - EPS * EPS).sqrt() / r;
(p.0 * k, p.1 * k, EPS)
}
fn signed_area(l: &LineString<f64>) -> f64 {
l.0.windows(2).map(|w| w[0].x * w[1].y - w[1].x * w[0].y).sum()
}
fn horizon(a: V3, sweep: f64) -> Vec<V3> {
let ta = a.1.atan2(a.0);
let n = (sweep.abs().to_degrees() / STEP).ceil() as usize;
let r = (1.0 - EPS * EPS).sqrt();
(1..n)
.map(|k| {
let t = ta + sweep * k as f64 / n as f64;
(r * t.cos(), r * t.sin(), EPS)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use geo::Area;
#[test]
fn the_centre_is_the_origin_and_the_far_side_is_hidden() {
let o = Ortho::new(12.0, 42.0);
let (x, y) = o.forward(12.0, 42.0);
assert!(x.abs() < 1e-6 && y.abs() < 1e-6);
let (x, y) = o.forward(12.0 + 180.0, -42.0);
assert!(x.is_nan() && y.is_nan(), "the antipode");
let (x, y) = o.forward(13.0, 42.0);
assert!(x > 80_000.0 && y.abs() < 2_000.0, "east is right: {x} {y}");
let (lon, lat) = o.inverse(o.forward(40.0, 10.0).0, o.forward(40.0, 10.0).1).unwrap();
assert!((lon - 40.0).abs() < 1e-9 && (lat - 10.0).abs() < 1e-9);
assert_eq!(o.inverse(RADIUS * 1.01, 0.0), None);
}
#[test]
fn parsed_from_a_proj_string() {
let o = Ortho::parse("+proj=ortho +lat_0=42.5 +lon_0=-10").unwrap();
assert_eq!(o, Ortho::new(-10.0, 42.5));
assert_eq!(Ortho::parse("+proj=laea +lat_0=1"), None);
}
#[test]
fn a_line_over_the_horizon_is_cut_there() {
let o = Ortho::new(0.0, 0.0);
let l = LineString::from(vec![(0.0, 0.0), (170.0, 0.0)]);
let Geometry::MultiLineString(m) = o.visible(&Geometry::LineString(l)) else { panic!() };
assert_eq!(m.0.len(), 1);
let end = m.0[0].0.last().unwrap();
assert!((end.x - 90.0).abs() < 0.01, "{end:?}");
}
#[test]
fn an_area_over_the_horizon_is_closed_along_it() {
let o = Ortho::new(0.0, 0.0);
let band = Polygon::new(LineString::from(vec![(-60.0, -30.0), (150.0, -30.0), (150.0, 30.0), (-60.0, 30.0), (-60.0, -30.0)]), vec![]);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(band)) else { panic!() };
assert_eq!(m.0.len(), 1);
let xs: Vec<f64> = m.0[0].exterior().0.iter().map(|c| c.x).collect();
let east = xs.iter().cloned().fold(f64::MIN, f64::max);
assert!((east - 90.0).abs() < 0.01, "{east}");
let projected = m.0[0].exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>();
assert!(projected.iter().all(|p| p.0.is_finite()));
let area = Polygon::new(LineString::from(projected), vec![]).unsigned_area();
assert!(area > 1e13, "{area}");
let far = Polygon::new(LineString::from(vec![(120.0, -10.0), (150.0, -10.0), (150.0, 10.0), (120.0, 10.0), (120.0, -10.0)]), vec![]);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(far)) else { panic!() };
assert!(m.0.is_empty());
}
#[test]
fn a_ring_either_way_round_closes_on_the_same_side() {
let o = Ortho::new(0.0, 0.0);
let ring = vec![(-60.0, -80.0), (150.0, -80.0), (150.0, 10.0), (-60.0, 10.0), (-60.0, -80.0)];
let area = |pts: Vec<(f64, f64)>| {
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(pts), vec![]))) else { panic!() };
m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum::<f64>()
};
let (ccw, cw) = (area(ring.clone()), area(ring.into_iter().rev().collect()));
assert!(ccw > 1e13 && (ccw - cw).abs() < ccw * 1e-6, "{ccw} {cw}");
assert!(ccw < 0.75 * std::f64::consts::PI * RADIUS * RADIUS, "{ccw}");
}
#[test]
fn an_area_as_wide_as_the_world_fills_the_disc() {
let o = Ortho::new(-40.0, 30.0);
let disc = std::f64::consts::PI * RADIUS * RADIUS;
let world = vec![(-180.0, -85.0), (180.0, -85.0), (180.0, 85.0), (-180.0, 85.0), (-180.0, -85.0)];
for ring in [world.clone(), world.into_iter().rev().collect()] {
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(ring), vec![]))) else { panic!() };
let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
assert!((a / disc - 1.0).abs() < 1e-3, "{}", a / disc);
}
}
#[test]
fn a_far_area_reaching_into_sight_twice_is_two_pieces() {
let o = Ortho::new(0.0, 0.0);
let sea = vec![
(95.0, -40.0), (140.0, -40.0), (140.0, 40.0), (95.0, 40.0), (95.0, 30.0), (80.0, 30.0), (80.0, 20.0), (95.0, 20.0),
(95.0, -20.0), (80.0, -20.0), (80.0, -30.0), (95.0, -30.0), (95.0, -40.0),
];
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(sea), vec![]))) else { panic!() };
assert_eq!(m.0.len(), 2);
let disc = std::f64::consts::PI * RADIUS * RADIUS;
let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
assert!(a > 0.0 && a < 0.02 * disc, "{}", a / disc);
}
#[test]
fn a_world_sea_keeps_its_land_from_the_equator() {
let world = LineString::from(vec![(-180.0, -85.05), (180.0, -85.05), (180.0, 85.05), (-180.0, 85.05), (-180.0, -85.05)]);
let land = LineString::from(vec![(0.0, -30.0), (0.0, 30.0), (40.0, 30.0), (40.0, -30.0), (0.0, -30.0)]);
let sea = Polygon::new(world, vec![land]);
for lat in [10.0, 5.0, 0.0, -5.0, -10.0] {
let o = Ortho::new(20.0, lat);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(sea.clone())) else { panic!() };
let flat = |l: &LineString<f64>| Polygon::new(LineString::from(l.0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area();
let holes: usize = m.0.iter().map(|p| p.interiors().len()).sum();
let disc = std::f64::consts::PI * RADIUS * RADIUS;
let outs: Vec<f64> = m.0.iter().map(|p| flat(p.exterior()) / disc).collect();
eprintln!("lat {lat}: outsides {outs:?}, holes {holes}");
let centre = m.0.iter().find(|p| geo::Contains::contains(&Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]), &geo::Point::new(1.0, 1.0)));
assert!(centre.is_some_and(|p| p.interiors().len() == 1), "lat {lat}");
}
}
#[test]
fn a_ring_back_along_its_own_way_is_no_area() {
let mut pts: Vec<(f64, f64)> = (0..=360).map(|i| (-180.0 + i as f64, 85.0)).collect();
pts.extend((0..=360).rev().map(|i| (-180.0 + i as f64, 85.0)));
for lat in [0.0, 3.0, 5.0, 10.0] {
let o = Ortho::new(20.0, lat);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(pts.clone()), vec![]))) else { panic!() };
let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
assert!(a < 1.0, "lat {lat}: {a}");
}
}
#[test]
fn a_world_sea_has_no_seam_down_the_antimeridian() {
let o = Ortho::new(-170.0, 10.0);
let e = 179.999_899_790_331_74;
let world = Polygon::new(LineString::from(vec![(-e, -85.0), (e, -85.0), (e, 85.0), (-e, 85.0), (-e, -85.0)]), vec![]);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(world)) else { panic!() };
let near_seam = m.0.iter().flat_map(|p| p.exterior().0.iter()).filter(|c| (c.x.abs() - 180.0).abs() < 1e-3 && c.y.abs() < 60.0).count();
assert_eq!(near_seam, 0, "no points down the antimeridian");
let disc = std::f64::consts::PI * RADIUS * RADIUS;
let a: f64 = m.0.iter().map(|p| Polygon::new(LineString::from(p.exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>()), vec![]).unsigned_area()).sum();
assert!((a / disc - 1.0).abs() < 0.02, "still the disc: {}", a / disc);
}
#[test]
fn two_tiles_meeting_at_the_antimeridian_join_without_a_seam() {
use geo::{BooleanOps, MapCoords};
let o = Ortho::new(-178.3, 4.0);
let square = |x0: f64, x1: f64| Polygon::new(LineString::from(vec![(x0, -10.5), (x1, -10.5), (x1, 10.5), (x0, 10.5), (x0, -10.5)]), vec![]);
let flat = |p: Polygon<f64>| {
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(p)) else { panic!() };
m.map_coords(|c| {
let (x, y) = o.forward(c.x, c.y);
Coord { x, y }
})
};
let joined = flat(square(169.5, 180.0)).union(&flat(square(-180.0, -170.5)));
assert_eq!(joined.0.len(), 1);
assert!(joined.0[0].interiors().is_empty());
}
#[test]
fn a_hidden_ring_round_the_centre_is_the_disc() {
let o = Ortho::new(0.0, 89.0);
let ring = LineString::from(vec![(-180.0, -10.0), (180.0, -10.0), (180.0, 89.5), (-180.0, 89.5), (-180.0, -10.0)]);
assert!(o.holds_centre(&ring));
}
#[test]
fn a_shore_along_the_rim_still_makes_an_area() {
let o = Ortho::new(0.0, 0.0);
let mut ring = vec![(95.0, -3.0)];
ring.extend((0..=10).map(|k| (89.995, -2.5 + k as f64 * 0.5)));
ring.extend([(95.0, 3.0), (95.0, -3.0)]);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(Polygon::new(LineString::from(ring), vec![]))) else { panic!() };
let pr = |l: &LineString<f64>| LineString::from(l.0.iter().map(|c| { let (x, y) = o.forward(c.x, c.y); (x, -y) }).collect::<Vec<_>>());
let cut = geo::MultiPolygon::new(m.0.iter().map(|p| Polygon::new(pr(p.exterior()), vec![])).collect());
use geo::Validation;
assert!(cut.is_valid(), "the cut crosses itself");
let united = crate::geom::union_multi([&cut]);
assert!(cut.unsigned_area() > 0.0);
assert!((united.unsigned_area() / cut.unsigned_area() - 1.0).abs() < 1e-3, "{} {}", united.unsigned_area(), cut.unsigned_area());
}
#[test]
fn a_ring_that_starts_out_of_sight_still_closes() {
let o = Ortho::new(0.0, 0.0);
let band = Polygon::new(LineString::from(vec![(150.0, -30.0), (150.0, 30.0), (-60.0, 30.0), (-60.0, -30.0), (150.0, -30.0)]), vec![]);
let Geometry::MultiPolygon(m) = o.visible(&Geometry::Polygon(band)) else { panic!() };
assert_eq!(m.0.len(), 1);
assert!(m.0[0].exterior().0.iter().all(|c| c.x.is_finite() && c.y.is_finite()));
let projected = m.0[0].exterior().0.iter().map(|c| o.forward(c.x, c.y)).collect::<Vec<_>>();
assert!(Polygon::new(LineString::from(projected), vec![]).unsigned_area() > 1e13);
}
}