diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index e6100aeac1..ef7a2e7c9c 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -4,6 +4,8 @@ use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Po use rustgis_data::Geometry; use rustgis_geom::{Coord, lonlat_to_merc, merc_to_lonlat}; +/// Projects without folding the longitude: a ring kept unwrapped across the antimeridian (as a +/// geodesic buffer is) stays one piece, rather than folding its far vertex across the world. fn gc(c: Coord) -> GC { let m = lonlat_to_merc(c); GC { x: m.x, y: m.y } @@ -79,3 +81,24 @@ pub fn from_line(ml: &MultiLineString) -> Option { pub fn from_point(p: &Point) -> Geometry { Geometry::Point(back(&p.0)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_antimeridian_ring_stays_a_sliver_through_geo() { + // Unwrapped across the antimeridian (179.9° to 180.1°): about 22 km wide in Mercator, not + // a band folded to the far west, and it comes back to the same longitudes. + let ring = + vec![Coord::new(179.9, 0.0), Coord::new(180.1, 0.0), Coord::new(180.1, 1.0), Coord::new(179.9, 1.0), Coord::new(179.9, 0.0)]; + let mp = to_multipolygon(&Geometry::Polygon(vec![vec![ring.clone()]])).unwrap(); + let xs: Vec = mp.0.iter().flat_map(|p| p.exterior().0.iter().map(|c| c.x)).collect(); + let width = xs.iter().copied().fold(f64::NEG_INFINITY, f64::max) - xs.iter().copied().fold(f64::INFINITY, f64::min); + assert!(width > 20_000.0 && width < 25_000.0, "{width}"); + let back: Vec = mp.0.iter().flat_map(|p| p.exterior().0.iter().map(|c| merc_to_lonlat(Coord::new(c.x, c.y)))).collect(); + for (a, b) in ring.iter().zip(back.iter()) { + assert!((a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9, "{a:?} → {b:?}"); + } + } +} diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 68e868e32b..5f65738c30 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -392,6 +392,19 @@ mod tests { assert_eq!(explode(&Geometry::MultiPoint(vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)])).len(), 2); } + #[test] + fn a_point_across_the_antimeridian_is_covered_by_its_polygon() { + // A polygon kept unwrapped (179.9° to 180.1°) covers a point at 180.05°, which is -179.95° once + // folded: the point is covered, not reported as outside the polygon. + let ring = + vec![Coord::new(179.9, 0.0), Coord::new(180.1, 0.0), Coord::new(180.1, 1.0), Coord::new(179.9, 1.0), Coord::new(179.9, 0.0)]; + let mut ds = Dataset::new("p", GeometryType::Polygon, vec![]); + ds.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![]); + let mut pts = Dataset::new("pt", GeometryType::Point, vec![]); + pts.push(Some(Geometry::Point(Coord::new(180.05, 0.5))), vec![]); + assert!(not_covered(&pts, &[0], &ds).errors.is_empty()); + } + #[test] fn long_paths_are_checked_not_skipped() { // 10,000 segments zigzagging east without crossing... diff --git a/crates/engine/tests/antimeridian_edit.rs b/crates/engine/tests/antimeridian_edit.rs new file mode 100644 index 0000000000..e49a430d24 --- /dev/null +++ b/crates/engine/tests/antimeridian_edit.rs @@ -0,0 +1,37 @@ +//! Editing a shape kept unwrapped across 180° (as a geodesic buffer returns one) keeps it narrow (#940). + +use rustgis_engine::{ + Project, Session, + data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value}, + geom::Coord, +}; +use serde_json::json; + +/// A selected, editable polygon with unwrapped antimeridian coordinates. +fn across_180() -> (Session, u32) { + let c = Coord::new; + let ring = vec![c(179.6, 10.0), c(180.2, 10.0), c(180.2, 10.3), c(179.6, 10.3), c(179.6, 10.0)]; + let mut data = Dataset::new("Across", GeometryType::Polygon, vec![Field::new("n", FieldType::Integer)]); + data.features = vec![Feature { id: 1, geometry: Some(Geometry::Polygon(vec![vec![ring]])), attrs: vec![Value::Int(0)] }].into(); + let mut s = Session::new(Project::new("Across 180")); + let id = s.map_mut().add_dataset(data); + s.active_layer = Some(id); + s.map_mut().editing.settings.enabled = true; + s.map_mut().layer_mut(id).unwrap().selection = vec![0]; + (s, id) +} + +#[test] +fn small_edits_keep_a_polygon_across_180_narrow() { + for (cmd, params) in + [("edit.move", json!({"dx": 1000.0, "dy": 0.0})), ("edit.rotate", json!({"angle": 10.0})), ("edit.scale", json!({"factor": 1.01}))] + { + let (mut s, id) = across_180(); + let before = s.map().layer(id).unwrap().dataset.features[0].geometry.clone(); + s.run(cmd, ¶ms).unwrap(); + assert_ne!(s.map().layer(id).unwrap().dataset.features[0].geometry, before, "{cmd} must change coordinates"); + let Some(Geometry::Polygon(p)) = &s.map().layer(id).unwrap().dataset.features[0].geometry else { panic!("{cmd}") }; + let (lo, hi) = p[0][0].iter().fold((f64::MAX, f64::MIN), |(a, b), c| (a.min(c.x), b.max(c.x))); + assert!(hi - lo < 1.0, "{cmd}: the polygon is now {:.1}° wide", hi - lo); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 9df0674294..c61454cdbf 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -146,12 +146,26 @@ impl Extent { } } -/// Longitude/latitude (degrees) → Web Mercator metres. Latitude is clamped to ±85.05°. +/// Longitude/latitude (degrees) → Web Mercator metres, without folding the longitude: one past +/// ±180° lands past the world's edge (±20,037,508.34 m), so a shape kept unwrapped across the +/// antimeridian (as `geodesic_interpolate` and `Aeqd::inverse` keep one, and a geodesic buffer +/// returns) stays the sliver it is, and `merc_to_lonlat` returns the longitude it was given. Edits, +/// overlays and hulls rely on that. Latitude is clamped to ±85.05°. A caller that needs one point +/// inside the world uses [`lonlat_to_merc_folded`] (#940). pub fn lonlat_to_merc(c: Coord) -> Coord { let lat = c.y.clamp(-MAX_LAT, MAX_LAT).to_radians(); Coord::new(MERCATOR_R * c.x.to_radians(), MERCATOR_R * (std::f64::consts::FRAC_PI_4 + lat / 2.0).tan().ln()) } +/// Like [`lonlat_to_merc`], but a longitude outside −180..180 folds into that range, so a single +/// point projects onto the world, never metres past its edge. Do not project the vertices of a +/// shape with it: an edge from 179.9° to 180.1° would become one across the whole map. A +/// non-finite longitude stays broken rather than quietly becoming the prime meridian. +pub fn lonlat_to_merc_folded(c: Coord) -> Coord { + let lon = if !c.x.is_finite() || (c.x >= -180.0 && c.x <= 180.0) { c.x } else { wrap_lon(c.x % 360.0) }; + lonlat_to_merc(Coord::new(lon, c.y)) +} + /// Web Mercator metres → longitude/latitude (degrees). pub fn merc_to_lonlat(c: Coord) -> Coord { let lon = (c.x / MERCATOR_R).to_degrees(); @@ -159,12 +173,19 @@ pub fn merc_to_lonlat(c: Coord) -> Coord { Coord::new(lon, lat) } -/// Projects a lon/lat extent to Web Mercator. +/// Projects a lon/lat extent to Web Mercator, preserving unwrapped longitudes for spans below +/// 360°. A span of a full turn or more maps to the standard world bounds. pub fn extent_to_merc(e: &Extent) -> Extent { if e.is_empty() { return *e; } - Extent::from_points(lonlat_to_merc(Coord::new(e.min_x, e.min_y)), lonlat_to_merc(Coord::new(e.max_x, e.max_y))) + // Preserve an unwrapped antimeridian extent instead of folding its corners separately. + // A full turn or more covers the world, independent of the starting longitude. + let (sw, ne) = (lonlat_to_merc(Coord::new(e.min_x, e.min_y)), lonlat_to_merc(Coord::new(e.max_x, e.max_y))); + let world = MERCATOR_R * std::f64::consts::PI; + let (west, east) = + if e.max_x.is_finite() && e.min_x.is_finite() && e.max_x - e.min_x >= 360.0 { (-world, world) } else { (sw.x, ne.x) }; + Extent::from_points(Coord::new(west, sw.y), Coord::new(east, ne.y)) } /// Great-circle distance between two lon/lat points (metres); NaN for non-finite coordinates. @@ -489,6 +510,55 @@ mod tests { assert!(wgs84_distance_m(c(0.0, f64::NEG_INFINITY), c(0.0, 0.0)).is_nan()); } + #[test] + fn an_extent_across_the_antimeridian_stays_a_sliver() { + // A geodesic buffer near 180° comes back unwrapped (179.9° to 180.1°): about 22 km wide, not + // the whole world. + let e = extent_to_merc(&Extent::new(179.9, 0.0, 180.1, 1.0)); + assert!(e.width() > 20_000.0 && e.width() < 25_000.0, "{}", e.width()); + // Inside the world nothing changes; a wider-than-world extent is the world. + let plain = extent_to_merc(&Extent::new(-10.0, 0.0, 10.0, 1.0)); + assert!((plain.width() - 2.0 * MERCATOR_R * 10f64.to_radians()).abs() < 1e-6); + let all = extent_to_merc(&Extent::new(-540.0, 0.0, 540.0, 1.0)); + assert!((all.width() - 2.0 * MERCATOR_R * std::f64::consts::PI).abs() < 1e-6); + // A full turn from Greenwich is the world too, at the world's edges, not 0 to twice the edge. + let turn = extent_to_merc(&Extent::new(0.0, 0.0, 360.0, 1.0)); + let world = MERCATOR_R * std::f64::consts::PI; + assert!((turn.min_x + world).abs() < 1e-6 && (turn.max_x - world).abs() < 1e-6, "{turn:?}"); + } + + #[test] + fn mercator_keeps_longitudes_outside_the_world_unless_folded() { + // Unwrapped, 185° round-trips (an edit of a shape across the antimeridian stays narrow). + let past = lonlat_to_merc(Coord::new(185.0, 0.0)); + assert!((merc_to_lonlat(past).x - 185.0).abs() < 1e-9); + assert!(past.x > MERCATOR_R * std::f64::consts::PI); + // Folded, 185° is -175° on the world: the same place, never past its edge. + let folded = lonlat_to_merc_folded(Coord::new(185.0, 0.0)); + let there = lonlat_to_merc(Coord::new(-175.0, 0.0)); + assert!((folded.x - there.x).abs() < 1e-6 && folded.y == there.y); + assert!(folded.x.abs() <= MERCATOR_R * std::f64::consts::PI, "{}", folded.x); + // Reduce the longitude before adding 180 degrees: at 2^60 that addition loses bits. + for lon in [2f64.powi(60), -2f64.powi(60), f64::MAX, -f64::MAX, -540.0, -180.0, 180.0, 540.0] { + let reduced = lon % 360.0; + let expected = if reduced > 180.0 { + reduced - 360.0 + } else if reduced < -180.0 { + reduced + 360.0 + } else { + reduced + }; + let actual = lonlat_to_merc_folded(Coord::new(lon, 0.0)); + // Either sign of 180 degrees denotes the seam. + let delta = (merc_to_lonlat(actual).x - expected).abs(); + assert!(delta < 1e-9 || (delta - 360.0).abs() < 1e-9, "{lon}: {actual:?}"); + assert!(actual.x.abs() <= MERCATOR_R * std::f64::consts::PI); + } + // A broken longitude stays broken, never a plausible place near Greenwich. + assert!(lonlat_to_merc_folded(Coord::new(f64::NAN, 0.0)).x.is_nan()); + assert!(lonlat_to_merc_folded(Coord::new(f64::INFINITY, 0.0)).x.is_infinite()); + } + #[test] fn wgs84_near_hemisphere_rings_keep_the_spherical_side() { // Both sides of the equator: the spherical and ellipsoidal hemisphere areas differ.