From 686a381de7f378f8743d3b31971a722d8759903a Mon Sep 17 00:00:00 2001 From: subarna-kandel Date: Mon, 26 Oct 2026 15:30:20 +0000 Subject: [PATCH 01/14] measure on the WGS 84 ellipsoid everywhere lengths and areas are named geodesic The attribute table's Calculate Geometry (edit.calculateGeometry), the map's Measure tools on the Earth and the network tools' edge and route lengths still measured on the mean sphere (R = 6,371,008.8 m), after #905 and #928 made the buffers, joins and the geoprocessing Calculate Geometry ellipsoidal. The same polygon then returned two areas about 0.26 % apart depending on which Calculate Geometry ran (#939). rustgis-geom gains wgs84_length_m (inverse geodesic solves, one per segment) and wgs84_ring_perimeter_area_m2 (GeographicLib's PolygonArea, the ring closed along a geodesic, unsigned in either winding), both stopping at non-finite coordinates as haversine_m now does. The three paths above use them; on the Moon or Mars the Measure tools keep measuring on that body's sphere and scale, as before. Network tests keep passing without changes to their tolerances. Fixes #939. --- crates/analysis/src/network.rs | 14 +- crates/engine/src/geometry_calc.rs | 19 +-- crates/engine/tests/geometry_calculator.rs | 21 ++- crates/geom/src/lib.rs | 141 ++++++++++++++++++++- crates/ui-egui/src/mapview.rs | 24 ++-- docs/user-guide/analysis.md | 6 +- docs/user-guide/data.md | 3 +- docs/user-guide/editing.md | 4 +- 8 files changed, 199 insertions(+), 33 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 0d79ca473d..56d79fa78c 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -4,7 +4,7 @@ use std::collections::{BinaryHeap, HashMap}; use rustgis_data::{Dataset, Geometry}; -use rustgis_geom::{Coord, haversine_m}; +use rustgis_geom::{Coord, wgs84_distance_m}; /// A shortest route: its path, length in metres, cost, and the line rows it uses. #[derive(Clone, Debug, PartialEq)] @@ -35,8 +35,8 @@ fn key(c: Coord) -> (i64, i64) { } /// The shortest route between two points over the lines of `rows`, joining where vertices -/// coincide. Each edge costs its length times the row's `cost_field` value (1 when empty; lines -/// costing zero or less are closed). Each +/// coincide. Each edge costs its length (on the WGS 84 ellipsoid) times the row's `cost_field` +/// value (1 when empty; lines costing zero or less are closed). Each /// end snaps to the nearest point on a line (within `snap_m`), where the route starts or stops. pub fn shortest_route( ds: &Dataset, @@ -70,7 +70,7 @@ pub fn shortest_route( for w in part.windows(2) { let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; let (ia, ib) = (node(*a, &mut ids, &mut nodes, &mut adj), node(*b, &mut ids, &mut nodes, &mut adj)); - let len = haversine_m(*a, *b); + let len = wgs84_distance_m(*a, *b); if let Some(v) = adj.get_mut(ia) { v.push((ib, len * weight, len, *r)); } @@ -96,7 +96,7 @@ pub fn shortest_route( let len2 = dx * dx + dy * dy; let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); - Some((i, t, q, haversine_m(q, p))) + Some((i, t, q, wgs84_distance_m(q, p))) }) .min_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal)) }; @@ -117,7 +117,7 @@ pub fn shortest_route( adj.push(Vec::new()); let n = nodes.len() - 1; for end in [a, b] { - let len = haversine_m(q, nodes.get(end).copied().unwrap_or(q)); + let len = wgs84_distance_m(q, nodes.get(end).copied().unwrap_or(q)); if let Some(v) = adj.get_mut(n) { v.push((end, len * weight, len, row)); } @@ -134,7 +134,7 @@ pub fn shortest_route( let (Some(&(_, _, weight, row)), Some(a), Some(b)) = (segs.get(s_seg), nodes.get(s).copied(), nodes.get(t).copied()) else { return Err("the layer has no lines".into()); }; - let len = haversine_m(a, b); + let len = wgs84_distance_m(a, b); if let Some(v) = adj.get_mut(s) { v.push((t, len * weight, len, row)); } diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 73df963f9b..149bfe4197 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -2,7 +2,7 @@ //! X/Y coordinate, calculated from its WGS84 geometry, in a field. use crate::{CmdResult, Session}; use rustgis_data::{FieldType, Geometry, GeometryType, Value, raster::Crs}; -use rustgis_geom::{geodesic_length_m, geodesic_ring_area_m2, spherical_centre}; +use rustgis_geom::{spherical_centre, wgs84_length_m, wgs84_ring_perimeter_area_m2}; use serde_json::{Value as Json, json}; /// The properties a layer of `kind` can calculate, as `(key, label)` pairs. @@ -34,23 +34,18 @@ pub fn units(property: &str) -> &'static [(&'static str, &'static str)] { fn measure(g: &Geometry, property: &str) -> Option { match (g, property) { + // On the WGS 84 ellipsoid, like every other measurement named geodesic (#939): the same + // numbers the geoprocessing tools give. (Geometry::Polygon(polys), "area") => Some( polys .iter() - .map(|rings| rings.iter().enumerate().map(|(i, r)| geodesic_ring_area_m2(r) * if i == 0 { 1.0 } else { -1.0 }).sum::()) - .sum(), - ), - (Geometry::Polygon(polys), "perimeter") => Some( - polys - .iter() - .flatten() - .map(|r| { - let closing = r.first().zip(r.last()).filter(|(a, b)| a != b).map(|(a, b)| geodesic_length_m(&[*b, *a])).unwrap_or(0.0); - geodesic_length_m(r) + closing + .map(|rings| { + rings.iter().enumerate().map(|(i, r)| wgs84_ring_perimeter_area_m2(r).1 * if i == 0 { 1.0 } else { -1.0 }).sum::() }) .sum(), ), - (Geometry::Line(parts), "length") => Some(parts.iter().map(|r| geodesic_length_m(r)).sum()), + (Geometry::Polygon(polys), "perimeter") => Some(polys.iter().flatten().map(|r| wgs84_ring_perimeter_area_m2(r).0).sum()), + (Geometry::Line(parts), "length") => Some(parts.iter().map(|r| wgs84_length_m(r)).sum()), _ => None, } } diff --git a/crates/engine/tests/geometry_calculator.rs b/crates/engine/tests/geometry_calculator.rs index c957ea391f..8226ea5b0f 100644 --- a/crates/engine/tests/geometry_calculator.rs +++ b/crates/engine/tests/geometry_calculator.rs @@ -49,6 +49,22 @@ fn selected_units_overwrite_and_undo() { assert!(s.map().layer(id).unwrap().dataset.field_index("metres").is_none()); } +#[test] +fn areas_are_on_the_wgs84_ellipsoid() { + // An equator 1° × 1° box measured by GeographicLib itself (pyproj.Geod / Polygon.Compute on + // WGS 84), so the attribute table and the geoprocessing tool agree with each other (#939). + let ring = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 1.0)]; + let (mut s, id) = session(GeometryType::Polygon, vec![Some(Geometry::Polygon(vec![vec![ring]]))]); + s.run("edit.calculateGeometry", &json!({"layer":id,"field":"result","overwrite":true,"property":"area","unit":"m2","scope":"all"})) + .unwrap(); + let actual = s.map().layer(id).unwrap().dataset.value(0, 0).as_f64().unwrap(); + assert!((actual - 12_308_778_361.469).abs() < 0.001, "{actual}"); + s.run("edit.calculateGeometry", &json!({"layer":id,"field":"result","overwrite":true,"property":"perimeter","unit":"m","scope":"all"})) + .unwrap(); + let actual = s.map().layer(id).unwrap().dataset.value(0, 0).as_f64().unwrap(); + assert!((actual - 443_770.917).abs() < 0.001, "{actual}"); +} + #[test] fn polygon_holes_multipart_and_area_units() { let ring = |x: f64, size: f64| { @@ -57,8 +73,9 @@ fn polygon_holes_multipart_and_area_units() { let outer = ring(0.0, 0.01); let hole = ring(0.002, 0.002); let part = ring(0.02, 0.005); - let expected = rustgis_engine::geom::geodesic_ring_area_m2(&outer) - rustgis_engine::geom::geodesic_ring_area_m2(&hole) - + rustgis_engine::geom::geodesic_ring_area_m2(&part); + let expected = rustgis_engine::geom::wgs84_ring_perimeter_area_m2(&outer).1 + - rustgis_engine::geom::wgs84_ring_perimeter_area_m2(&hole).1 + + rustgis_engine::geom::wgs84_ring_perimeter_area_m2(&part).1; let (mut s, id) = session(GeometryType::Polygon, vec![Some(Geometry::Polygon(vec![vec![outer, hole], vec![part]]))]); for (unit, divisor) in [("m2", 1.0), ("km2", 1e6), ("ha", 1e4), ("ac", 4046.8564224)] { s.run("edit.calculateGeometry", &json!({"layer":id,"field":"result","overwrite":true,"property":"area","unit":unit,"scope":"all"})) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 93ad1686fd..eb1eecfeb1 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -13,7 +13,7 @@ pub use sinusoidal::Sinusoidal; use std::sync::LazyLock; -use geographiclib_rs::{DirectGeodesic, Geodesic, InverseGeodesic}; +use geographiclib_rs::{DirectGeodesic, Geodesic, InverseGeodesic, PolygonArea, Winding}; use serde::{Deserialize, Serialize}; /// Mean Earth radius used by the haversine formula (metres). @@ -243,10 +243,66 @@ pub fn geodesic_destination(c: Coord, azimuth_deg: f64, dist_m: f64) -> Coord { /// The geodesic distance between two lon/lat points on the WGS 84 ellipsoid (metres): the inverse /// geodesic problem, solved by GeographicLib. pub fn wgs84_distance_m(a: Coord, b: Coord) -> f64 { + // A broken coordinate is no place (see [`haversine_m`]): the clamp below would otherwise turn a + // latitude of infinity into a pole. + if !a.is_finite() || !b.is_finite() { + return f64::NAN; + } let (s12, _): (f64, f64) = WGS84.inverse(a.y.clamp(-90.0, 90.0), a.x, b.y.clamp(-90.0, 90.0), b.x); s12 } +/// Length of a lon/lat polyline along the WGS 84 ellipsoid's geodesics (metres): each segment is +/// an inverse geodesic solve, so it is exact, unlike [`geodesic_length_m`]'s great circles. Long +/// lines of many vertices cost a solve per segment (a few microseconds each). +pub fn wgs84_length_m(pts: &[Coord]) -> f64 { + pts.windows(2) + .map(|w| match w { + [a, b] => wgs84_distance_m(*a, *b), + _ => 0.0, + }) + .sum() +} + +/// The perimeter (metres) and the unsigned enclosed area (square metres) of a lon/lat ring on the +/// WGS 84 ellipsoid. The ring is closed along a geodesic to its first point, whatever its winding, +/// so a ring of many vertices needs one accumulation, not a solve per vertex. A ring gives the +/// region it traces (so polar rings and globe-wide bands follow their own edges, as the sphere's +/// [`geodesic_ring_area_m2`] does); reversing the ring gives the same magnitude. +pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { + if ring.len() < 3 { + return (0.0, 0.0); + } + // A broken vertex is no place: NaN, never a plausible number (see [`haversine_m`]). + if !ring.iter().all(|c| c.is_finite()) { + return (f64::NAN, f64::NAN); + } + // An edge of a full turn of longitude (-180° to 180°, as a globe-wide band has) joins two + // coordinates that name the same place, which a geodesic cannot tell from no edge at all: such + // a ring is measured on the sphere, as it always was. + let full_turn = ring.iter().zip(ring.iter().cycle().skip(1)).any(|(a, b)| (b.x - a.x).abs() >= 360.0); + if full_turn { + let mut closed = ring.to_vec(); + closed.extend(ring.first().copied()); + return (geodesic_length_m(&closed), geodesic_ring_area_m2(ring)); + } + let mut polygon = PolygonArea::new(&WGS84, Winding::Clockwise); + for c in ring { + polygon.add_point(c.y.clamp(-90.0, 90.0), c.x); + } + // `compute` reduces the signed area to at most half the ellipsoid, so a ring enclosing more + // than half of it comes back as the smaller complement: the sphere's area says which one the + // ring traces. + let (perimeter, area, _) = polygon.compute(true); + let area = area.abs(); + let sphere = geodesic_ring_area_m2(ring); + let complement = WGS84_AREA_M2 - area; + (perimeter, if (sphere - complement).abs() < (sphere - area).abs() { complement } else { area }) +} + +/// The surface area of the WGS 84 ellipsoid (square metres). +const WGS84_AREA_M2: f64 = 510_065_621_724_079.0; + /// The WGS 84 ellipsoid's geodesic solver. static WGS84: LazyLock = LazyLock::new(Geodesic::wgs84); @@ -408,6 +464,89 @@ mod tests { } } + #[test] + fn wgs84_rings_keep_full_turn_edges_and_large_areas() { + let c = Coord::new; + // A globe-wide band: its -180° to 180° edges are parallels, not zero-length hops. + let band = [c(-180.0, -10.0), c(180.0, -10.0), c(180.0, 10.0), c(-180.0, 10.0)]; + let (_, area) = wgs84_ring_perimeter_area_m2(&band); + let sphere = geodesic_ring_area_m2(&band); + assert!(area > 1.0e13 && (area / sphere - 1.0).abs() < 0.01, "{area} {sphere}"); + // A ring around the North Pole's complement: the southern cap of latitude < 60° is more + // than half the Earth; it must not come back as the northern cap. + let big: Vec = (0..=36).map(|i| c(-180.0 + f64::from(i) * 10.0, 60.0)).collect(); + let small = wgs84_ring_perimeter_area_m2(&big).1; + assert!(small < WGS84_AREA_M2 / 2.0, "{small}"); + // A broken latitude is no pole. + assert!(wgs84_length_m(&[c(0.0, 0.0), c(0.0, f64::INFINITY)]).is_nan()); + assert!(wgs84_distance_m(c(0.0, f64::NEG_INFINITY), c(0.0, 0.0)).is_nan()); + } + + #[test] + fn wgs84_measures_match_geographiclib() { + // References from GeographicLib (pyproj.Geod / Polygon.Compute on WGS 84), cross-checked + // against `geo`'s GeodesicArea: a 1° × 1° box at the equator, and the same box stretched + // across the antimeridian (unwrapped, 179° to 181°). + let equator = &[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0), Coord::new(1.0, 1.0), Coord::new(1.0, 0.0)]; + let (perimeter, area) = wgs84_ring_perimeter_area_m2(equator); + assert!((perimeter - 443_770.917).abs() < 0.001, "{perimeter}"); + assert!((area - 12_308_778_361.469).abs() < 0.001, "{area}"); + // The ring traced the other way around gives the same magnitude. + let (perimeter_reversed, area_reversed) = wgs84_ring_perimeter_area_m2(&equator.iter().rev().copied().collect::>()); + assert!((perimeter - perimeter_reversed).abs() < 1e-6); + assert!((area - area_reversed).abs() < 1e-6); + // Unwrapped longitudes past the antimeridian are one ring, not a world-sized complement. + let across = &[Coord::new(179.0, 0.0), Coord::new(181.0, 0.0), Coord::new(181.0, 1.0), Coord::new(179.0, 1.0)]; + let (perimeter_across, area_across) = wgs84_ring_perimeter_area_m2(across); + assert!((perimeter_across - 666_393.055).abs() < 0.001, "{perimeter_across}"); + assert!((area_across - 24_619_443_759.277).abs() < 0.001, "{area_across}"); + // Segment lengths are inverse geodesic solves, unwrapped or folded alike. + assert!((wgs84_length_m(&[Coord::new(0.0, 0.0), Coord::new(3.0, 0.0)]) - 3.0 * 111_319.4908).abs() < 0.01); + assert!((wgs84_distance_m(Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)) - 222_638.9816).abs() < 0.001); + // A broken coordinate is no length and no area (see `haversine_m`'s guard). + assert!(wgs84_length_m(&[Coord::new(0.0, 0.0), Coord::new(f64::NAN, 0.0)]).is_nan()); + let (perimeter_broken, area_broken) = + wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0), Coord::new(f64::NAN, 0.0)]); + assert!(perimeter_broken.is_nan() && area_broken.is_nan()); + // Degenerate rings keep their zero. + assert_eq!(wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0)]), (0.0, 0.0)); + } + + #[test] + fn a_non_finite_coordinate_is_no_distance_no_area_and_no_place() { + // A NaN vertex once measured as a quarter of the Earth's circumference (π·R = 20 015 114 + // m) through `h.sqrt().min(1.0)`: `f64::min` ignores NaN. It must be no distance at all, so + // sums and panels stay visibly broken and comparisons exclude it (NaN <= r is false). + let nan = f64::NAN; + let origin = Coord::new(0.0, 0.0); + for near in [Coord::new(nan, 0.0), Coord::new(0.0, nan), Coord::new(f64::INFINITY, 0.0)] { + assert!(haversine_m(origin, near).is_nan()); + assert!(geodesic_length_m(&[origin, near, origin]).is_nan()); + } + // A finite edge next to a broken one keeps measuring, through its own points. + assert!((geodesic_length_m(&[origin, Coord::new(1.0, 0.0)]) - 111_195.080).abs() < 0.01); + // Ring area: a NaN absorbing match on the older behaviour, then anything broken. + assert!(geodesic_ring_area_m2(&[origin, Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(nan, 1.0)]).is_nan()); + assert!(geodesic_ring_area_m2(&[origin, Coord::new(1.0, 0.0), Coord::new(1.0, f64::INFINITY)]).is_nan()); + // Heading away from a broken place is no place either. + assert!(geodesic_destination(Coord::new(10.0, 50.0), 90.0, f64::NAN).x.is_nan()); + } + + #[test] + fn non_finite_measures_show_a_dash_not_nan() { + for broken in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(format_distance(broken), "–"); + assert_eq!(format_area(broken), "–"); + } + assert_eq!(format_lonlat(Coord::new(f64::NAN, f64::NAN)), "–"); + assert_eq!(format_dms(Coord::new(f64::NAN, 50.0)), "–"); + // The finite cases still format as before. + assert_eq!(format_distance(850.0), "850 m"); + assert_eq!(format_distance(12_500.0), "12.5 km"); + assert_eq!(format_area(2_500_000.0), "2.5 km²"); + assert_eq!(format_lonlat(Coord::new(-12.3456, 45.6789)), "12.3456° W 45.6789° N"); + } + #[test] fn azimuthal_equidistant_keeps_distances_from_its_centre() { // Distances and azimuths on WGS 84 from GeographicLib (pyproj.Geod(ellps="WGS84").inv). diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 9dd69b4ef8..fc9dc36cd0 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -8,7 +8,7 @@ use rustgis_engine::analysis::{ network::{radius_boundary_point, radius_distance_m}, selection::MAX_POINTS, }; -use rustgis_engine::geom::{Coord, Extent, geodesic_length_m, geodesic_ring_area_m2}; +use rustgis_engine::geom::{Coord, Extent, geodesic_length_m, geodesic_ring_area_m2, wgs84_length_m, wgs84_ring_perimeter_area_m2}; use rustgis_engine::map::layout::TextAlign; use rustgis_engine::map::projection::Flat; use rustgis_engine::map::{Camera, Globe, Projection}; @@ -2599,16 +2599,24 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: p.circle_stroke(*s, 3.5, Stroke::new(1.5, color)); } if matches!(tool, Tool::Measure | Tool::MeasureArea) && pts.len() >= 2 { - // On the map's body. + // On the map's body: the Earth measures on the WGS 84 ellipsoid, so the panel agrees + // with the geoprocessing tools (#939); another body measures on its sphere and scales. let body = app.session.map().body(); - let geodesic_length_m = |pts: &[Coord]| body.length(geodesic_length_m(pts)); - let geodesic_ring_area_m2 = |ring: &[Coord]| body.area(geodesic_ring_area_m2(ring)); + let measure_length = |pts: &[Coord]| { + if body.is_earth() { wgs84_length_m(pts) } else { body.length(geodesic_length_m(pts)) } + }; + let measure_ring_area = |ring: &[Coord]| { + if body.is_earth() { wgs84_ring_perimeter_area_m2(ring).1 } else { body.area(geodesic_ring_area_m2(ring)) } + }; + let measure_ring_perimeter = |ring: &[Coord]| { + if body.is_earth() { wgs84_ring_perimeter_area_m2(ring).0 } else { body.length(geodesic_length_m(ring)) } + }; let text = if tool == Tool::Measure { - let seg = pts.len().checked_sub(2).and_then(|i| pts.get(i..)).map(geodesic_length_m).unwrap_or(0.0); + let seg = pts.len().checked_sub(2).and_then(|i| pts.get(i..)).map(measure_length).unwrap_or(0.0); crate::i18n::fmt( "Total {total} · Segment {segment}", &[ - ("total", &crate::measure_units::distance(geodesic_length_m(&pts), app.ui.measurement_imperial)), + ("total", &crate::measure_units::distance(measure_length(&pts), app.ui.measurement_imperial)), ("segment", &crate::measure_units::distance(seg, app.ui.measurement_imperial)), ], ) @@ -2620,8 +2628,8 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: crate::i18n::fmt( "Area {area} · Perimeter {perimeter}", &[ - ("area", &crate::measure_units::area(geodesic_ring_area_m2(&ring), app.ui.measurement_imperial)), - ("perimeter", &crate::measure_units::distance(geodesic_length_m(&ring), app.ui.measurement_imperial)), + ("area", &crate::measure_units::area(measure_ring_area(&ring), app.ui.measurement_imperial)), + ("perimeter", &crate::measure_units::distance(measure_ring_perimeter(&ring), app.ui.measurement_imperial)), ], ) }; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1be3e32668..17bfae19f2 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -132,7 +132,11 @@ use the smaller polar region in either direction; reversing a ring does not sele complement. Edges follow the shortest geodesics between vertices. The output fields remain `area_km2`, `perimeter_km` and `length_km`; point coordinates are unchanged. Spatial Join's **Largest overlap** still measures area on a sphere of radius 6,371 km; it can -differ from the ellipsoid by up to about 0.9 % (a small area near a pole). +differ from the ellipsoid by up to about 0.9 % (a small area near a pole). The same WGS 84 +measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the map's +**Measure** tools on the Earth, and every network tool's edge and route lengths, so all of these +read the same number for the same geometry. On the Moon or another body, the Measure tools +measure on that body's sphere. **IDW Interpolation** works like the QGIS tool of the same name: every point weighs on every cell by 1/distanceᴾ, where P is the distance coefficient (2 by default). Lines and polygons diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 0d456df8c4..5f5bd4d971 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -92,7 +92,8 @@ For an editable feature layer, double-click a cell to change it. The table's too fields, calculates field expressions and opens **Calculate Geometry** (`edit.calculateGeometry`). The geometry calculator fills a new double field or an existing numeric field with area, perimeter, length or point X/Y, for all or selected features. Point coordinates can be WGS 84 -degrees or a supported projected EPSG system's units. See [Editing](editing.md) for field +degrees or a supported projected EPSG system's units. Areas, perimeters and lengths measure on +the WGS 84 ellipsoid. See [Editing](editing.md) for field calculations and data-design rules. Streamed layers must first be loaded with **Load All Features**. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 4a06ed1058..d1915b4b7d 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -10,7 +10,9 @@ to change it. **Data › Data Design** (and **Data › Fields**) adds and delete field from an expression; **Calculate Geometry** (in the attribute table's toolbar) fills a new or existing numeric field with each feature's area, perimeter, length or X/Y coordinate, in the units you choose, for all features or the selected ones. Length and perimeter include feet and miles; -area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). Every edit is one undo step. +area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). Every edit is one undo +step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure the +geoprocessing tools use. Undo (++ctrl+z++) and Redo (++ctrl+y++ or ++ctrl+shift+z++) restore project changes, not just feature edits; use ++cmd++ instead of ++ctrl++ on macOS. While typing in a text field, those From 94b6d92bad805369b51f56723ffd17ceeba82d94 Mon Sep 17 00:00:00 2001 From: subarna-kandel Date: Tue, 27 Oct 2026 02:37:55 +0000 Subject: [PATCH 02/14] fix(geom): address review of the WGS 84 measures wgs84_distance_m returns NaN for non-finite coordinates (an infinite latitude was clamped to a pole); rings with a full-turn longitude edge fall back to the sphere and rings over half the ellipsoid keep their area; the network snap scan ranks segments by haversine and solves only the winner on the ellipsoid. Co-Authored-By: Claude Sonnet 5.5 --- crates/analysis/src/network.rs | 7 +++++-- crates/geom/src/lib.rs | 19 ++----------------- 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 56d79fa78c..0c5149bb64 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -4,7 +4,7 @@ use std::collections::{BinaryHeap, HashMap}; use rustgis_data::{Dataset, Geometry}; -use rustgis_geom::{Coord, wgs84_distance_m}; +use rustgis_geom::{Coord, haversine_m, wgs84_distance_m}; /// A shortest route: its path, length in metres, cost, and the line rows it uses. #[derive(Clone, Debug, PartialEq)] @@ -96,9 +96,12 @@ pub fn shortest_route( let len2 = dx * dx + dy * dy; let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); - Some((i, t, q, wgs84_distance_m(q, p))) + Some((i, t, q, haversine_m(q, p))) }) .min_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal)) + // The scan ranks segments by the cheap great-circle distance (it orders them as the + // ellipsoid does, to well under a snap tolerance); only the winner is solved exactly. + .map(|(i, t, q, _)| (i, t, q, wgs84_distance_m(q, p))) }; // Each end becomes a node on its segment, joined to the segment's two ends. let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index eb1eecfeb1..27fb48b050 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -501,8 +501,8 @@ mod tests { assert!((perimeter_across - 666_393.055).abs() < 0.001, "{perimeter_across}"); assert!((area_across - 24_619_443_759.277).abs() < 0.001, "{area_across}"); // Segment lengths are inverse geodesic solves, unwrapped or folded alike. - assert!((wgs84_length_m(&[Coord::new(0.0, 0.0), Coord::new(3.0, 0.0)]) - 3.0 * 111_319.4908).abs() < 0.01); - assert!((wgs84_distance_m(Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)) - 222_638.9816).abs() < 0.001); + assert!((wgs84_length_m(&[Coord::new(0.0, 0.0), Coord::new(3.0, 0.0)]) - 3.0 * 111_319.490_8).abs() < 0.01); + assert!((wgs84_distance_m(Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)) - 222_638.981_6).abs() < 0.001); // A broken coordinate is no length and no area (see `haversine_m`'s guard). assert!(wgs84_length_m(&[Coord::new(0.0, 0.0), Coord::new(f64::NAN, 0.0)]).is_nan()); let (perimeter_broken, area_broken) = @@ -532,21 +532,6 @@ mod tests { assert!(geodesic_destination(Coord::new(10.0, 50.0), 90.0, f64::NAN).x.is_nan()); } - #[test] - fn non_finite_measures_show_a_dash_not_nan() { - for broken in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - assert_eq!(format_distance(broken), "–"); - assert_eq!(format_area(broken), "–"); - } - assert_eq!(format_lonlat(Coord::new(f64::NAN, f64::NAN)), "–"); - assert_eq!(format_dms(Coord::new(f64::NAN, 50.0)), "–"); - // The finite cases still format as before. - assert_eq!(format_distance(850.0), "850 m"); - assert_eq!(format_distance(12_500.0), "12.5 km"); - assert_eq!(format_area(2_500_000.0), "2.5 km²"); - assert_eq!(format_lonlat(Coord::new(-12.3456, 45.6789)), "12.3456° W 45.6789° N"); - } - #[test] fn azimuthal_equidistant_keeps_distances_from_its_centre() { // Distances and azimuths on WGS 84 from GeographicLib (pyproj.Geod(ellps="WGS84").inv). From 5f5fcdc02956fdba8d599afcc92ef272d098177a Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:07:19 +0000 Subject: [PATCH 03/14] fix(geom): test polar and band rings, and measure the ring once The polar-ring test used a 37-vertex ring whose closing edge is a full turn, so the sphere area came back as zero and the "not more than half" check passed trivially. The test now uses a 36-vertex ring with no full-turn edge and asserts it measures the traced southern complement, and the band check is a range against the sphere value. The measure overlay computed the WGS 84 ring area and perimeter in two calls per frame. It now takes both from one call. The user guide names the full-turn exception: a ring with a full-turn edge (a globe-wide band) is measured on the sphere. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/geom/src/lib.rs | 18 ++++++++++-------- crates/ui-egui/src/mapview.rs | 17 ++++++++++------- docs/user-guide/data.md | 3 ++- docs/user-guide/editing.md | 3 ++- 4 files changed, 24 insertions(+), 17 deletions(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 27fb48b050..144273d179 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -467,16 +467,18 @@ mod tests { #[test] fn wgs84_rings_keep_full_turn_edges_and_large_areas() { let c = Coord::new; - // A globe-wide band: its -180° to 180° edges are parallels, not zero-length hops. + // A globe-wide band: its -180° to 180° edges are parallels, not zero-length hops. Measured + // on the sphere: 2πR²(sin 10° − sin −10°) ≈ 8.85e13 m². let band = [c(-180.0, -10.0), c(180.0, -10.0), c(180.0, 10.0), c(-180.0, 10.0)]; let (_, area) = wgs84_ring_perimeter_area_m2(&band); - let sphere = geodesic_ring_area_m2(&band); - assert!(area > 1.0e13 && (area / sphere - 1.0).abs() < 0.01, "{area} {sphere}"); - // A ring around the North Pole's complement: the southern cap of latitude < 60° is more - // than half the Earth; it must not come back as the northern cap. - let big: Vec = (0..=36).map(|i| c(-180.0 + f64::from(i) * 10.0, 60.0)).collect(); - let small = wgs84_ring_perimeter_area_m2(&big).1; - assert!(small < WGS84_AREA_M2 / 2.0, "{small}"); + assert!(area > 8.5e13 && area < 9.2e13, "{area}"); + // A ring of 36 vertices at 60° N, closed by a wrapped 10° edge (no full-turn edge): it traces + // the southern cap of latitude < 60°, more than half the Earth, so it must not come back as + // the northern cap. Its area agrees with the sphere's, as the ring's own edges define it. + let big: Vec = (0..36).map(|i| c(-180.0 + f64::from(i) * 10.0, 60.0)).collect(); + let area = wgs84_ring_perimeter_area_m2(&big).1; + assert!(area > WGS84_AREA_M2 / 2.0, "{area}"); + assert!((area / geodesic_ring_area_m2(&big) - 1.0).abs() < 0.01, "{area}"); // A broken latitude is no pole. assert!(wgs84_length_m(&[c(0.0, 0.0), c(0.0, f64::INFINITY)]).is_nan()); assert!(wgs84_distance_m(c(0.0, f64::NEG_INFINITY), c(0.0, 0.0)).is_nan()); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 6f240bd4a8..7b25a55510 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -2651,11 +2651,13 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: let measure_length = |pts: &[Coord]| { if body.is_earth() { wgs84_length_m(pts) } else { body.length(geodesic_length_m(pts)) } }; - let measure_ring_area = |ring: &[Coord]| { - if body.is_earth() { wgs84_ring_perimeter_area_m2(ring).1 } else { body.area(geodesic_ring_area_m2(ring)) } - }; - let measure_ring_perimeter = |ring: &[Coord]| { - if body.is_earth() { wgs84_ring_perimeter_area_m2(ring).0 } else { body.length(geodesic_length_m(ring)) } + // (perimeter, area) of a ring, in one pass. + let measure_ring = |ring: &[Coord]| { + if body.is_earth() { + wgs84_ring_perimeter_area_m2(ring) + } else { + (body.length(geodesic_length_m(ring)), body.area(geodesic_ring_area_m2(ring))) + } }; let text = if tool == Tool::Measure { let seg = pts.len().checked_sub(2).and_then(|i| pts.get(i..)).map(measure_length).unwrap_or(0.0); @@ -2671,11 +2673,12 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: if let Some(f) = ring.first().copied() { ring.push(f); } + let (perimeter, area) = measure_ring(&ring); crate::i18n::fmt( "Area {area} · Perimeter {perimeter}", &[ - ("area", &crate::measure_units::area(measure_ring_area(&ring), app.ui.measurement_imperial)), - ("perimeter", &crate::measure_units::distance(measure_ring_perimeter(&ring), app.ui.measurement_imperial)), + ("area", &crate::measure_units::area(area, app.ui.measurement_imperial)), + ("perimeter", &crate::measure_units::distance(perimeter, app.ui.measurement_imperial)), ], ) }; diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index f2875cafcd..913c53bd5a 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -93,7 +93,8 @@ fields, calculates field expressions and opens **Calculate Geometry** (`edit.cal The geometry calculator fills a new double field or an existing numeric field with area, perimeter, length or point X/Y, for all or selected features. Point coordinates can be WGS 84 degrees or a supported projected EPSG system's units. Areas, perimeters and lengths measure on -the WGS 84 ellipsoid. See [Editing](editing.md) for field +the WGS 84 ellipsoid (a ring with a full-turn edge, such as a globe-wide band, on the sphere). +See [Editing](editing.md) for field calculations and data-design rules. Streamed layers must first be loaded with **Load All Features**. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index b34c824632..22ff53966c 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -12,7 +12,8 @@ existing numeric field with each feature's area, perimeter, length or X/Y coordi you choose, for all features or the selected ones. Length and perimeter include feet and miles; area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). Every edit is one undo step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure the -geoprocessing tools use. +geoprocessing tools use. A ring with a full-turn edge (a globe-wide band) is measured on the +sphere instead. Undo (++ctrl+z++) and Redo (++ctrl+y++ or ++ctrl+shift+z++) restore project changes, not just feature edits; use ++cmd++ instead of ++ctrl++ on macOS. While typing in a text field, those From eb349c0cf25ac837dacd3d1e0f999b347a26bb4a Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:25:21 +0000 Subject: [PATCH 04/14] fix(geom): reject broken vertices in short WGS 84 rings A ring of fewer than three vertices returned (0, 0) before the non-finite check ran, so a two-vertex ring with a NaN vertex gave a plausible zero. The check now comes first, so a broken vertex is NaN at any ring length, as the function documents. Also correct the calculator's comment: rings with a full-turn edge are measured on the sphere here, where the geoprocessing tool unwraps them. Add a regression assertion for the short-ring case. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/engine/src/geometry_calc.rs | 3 ++- crates/geom/src/lib.rs | 10 ++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 149bfe4197..776a22dcd1 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -35,7 +35,8 @@ pub fn units(property: &str) -> &'static [(&'static str, &'static str)] { fn measure(g: &Geometry, property: &str) -> Option { match (g, property) { // On the WGS 84 ellipsoid, like every other measurement named geodesic (#939): the same - // numbers the geoprocessing tools give. + // numbers the geoprocessing tools give, except a ring with a full-turn (-180° to 180°) edge, + // which is measured on the sphere here but unwrapped (so near zero for a band) there. (Geometry::Polygon(polys), "area") => Some( polys .iter() diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 144273d179..b61c37e736 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -270,13 +270,13 @@ pub fn wgs84_length_m(pts: &[Coord]) -> f64 { /// region it traces (so polar rings and globe-wide bands follow their own edges, as the sphere's /// [`geodesic_ring_area_m2`] does); reversing the ring gives the same magnitude. pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { - if ring.len() < 3 { - return (0.0, 0.0); - } // A broken vertex is no place: NaN, never a plausible number (see [`haversine_m`]). if !ring.iter().all(|c| c.is_finite()) { return (f64::NAN, f64::NAN); } + if ring.len() < 3 { + return (0.0, 0.0); + } // An edge of a full turn of longitude (-180° to 180°, as a globe-wide band has) joins two // coordinates that name the same place, which a geodesic cannot tell from no edge at all: such // a ring is measured on the sphere, as it always was. @@ -510,8 +510,10 @@ mod tests { let (perimeter_broken, area_broken) = wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0), Coord::new(f64::NAN, 0.0)]); assert!(perimeter_broken.is_nan() && area_broken.is_nan()); - // Degenerate rings keep their zero. + // Degenerate rings keep their zero, unless a vertex is broken: that is NaN, even in a short ring. assert_eq!(wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0)]), (0.0, 0.0)); + let (perimeter_short, area_short) = wgs84_ring_perimeter_area_m2(&[Coord::new(f64::NAN, f64::NAN), Coord::new(0.0, 0.0)]); + assert!(perimeter_short.is_nan() && area_short.is_nan()); } #[test] From 2a72752e01a21f7c4dde844e869e8eb8f33c63d7 Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:04:30 +0000 Subject: [PATCH 05/14] fix(geom): keep a two-vertex ring's perimeter as 2d The early return for short rings made a two-vertex ring measure zero perimeter, where the mean-sphere version gave twice the segment. It is a segment there and back, so it now measures 2d on the WGS 84 ellipsoid with no area, and a single vertex still measures zero. Also name the full-turn ring exception in the analysis guide, and say that the network snap choice is approximate: the scan ranks segments by great-circle distance. Applied by the claude-autofix workflow. --- crates/analysis/src/network.rs | 5 +++-- crates/geom/src/lib.rs | 12 ++++++++++-- docs/user-guide/analysis.md | 6 ++++-- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 0c5149bb64..06a69fe641 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -99,8 +99,9 @@ pub fn shortest_route( Some((i, t, q, haversine_m(q, p))) }) .min_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal)) - // The scan ranks segments by the cheap great-circle distance (it orders them as the - // ellipsoid does, to well under a snap tolerance); only the winner is solved exactly. + // The scan ranks segments by the cheap great-circle distance, which differs from the + // ellipsoid's by up to about 0.7 %; only the winner is solved exactly, so the segment + // chosen is approximate near the snap tolerance. .map(|(i, t, q, _)| (i, t, q, wgs84_distance_m(q, p))) }; // Each end becomes a node on its segment, joined to the segment's two ends. diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index b61c37e736..18cf492d64 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -274,9 +274,13 @@ pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { if !ring.iter().all(|c| c.is_finite()) { return (f64::NAN, f64::NAN); } - if ring.len() < 3 { + if ring.len() < 2 { return (0.0, 0.0); } + // A two-vertex ring is a segment there and back: twice its length, and no area. + if let [a, b] = ring { + return (2.0 * wgs84_distance_m(*a, *b), 0.0); + } // An edge of a full turn of longitude (-180° to 180°, as a globe-wide band has) joins two // coordinates that name the same place, which a geodesic cannot tell from no edge at all: such // a ring is measured on the sphere, as it always was. @@ -510,8 +514,12 @@ mod tests { let (perimeter_broken, area_broken) = wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0), Coord::new(f64::NAN, 0.0)]); assert!(perimeter_broken.is_nan() && area_broken.is_nan()); - // Degenerate rings keep their zero, unless a vertex is broken: that is NaN, even in a short ring. + // A single vertex keeps its zero; two vertices are a segment there and back (2d, no area). assert_eq!(wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0)]), (0.0, 0.0)); + let (perimeter_two, area_two) = wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0)]); + assert!((perimeter_two - 2.0 * 111_319.490_8).abs() < 0.01, "{perimeter_two}"); + assert_eq!(area_two, 0.0); + // Degenerate rings keep their zero, unless a vertex is broken: that is NaN, even in a short ring. let (perimeter_short, area_short) = wgs84_ring_perimeter_area_m2(&[Coord::new(f64::NAN, f64::NAN), Coord::new(0.0, 0.0)]); assert!(perimeter_short.is_nan() && area_short.is_nan()); } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index cb772325cb..c7500de818 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -137,8 +137,10 @@ Spatial Join's **Largest overlap** still measures area on a sphere of radius 6,3 differ from the ellipsoid by up to about 0.9 % (a small area near a pole). The same WGS 84 measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the map's **Measure** tools on the Earth, and every network tool's edge and route lengths, so all of these -read the same number for the same geometry. On the Moon or another body, the Measure tools -measure on that body's sphere. +read the same number for the same geometry, with one exception: a polygon ring with a full-turn +(-180° to 180°) edge, such as a globe-wide band. The attribute table and the Measure tools +measure it on the sphere, while **Calculate Geometry Attributes** unwraps it, so it reads near +zero there. On the Moon or another body, the Measure tools measure on that body's sphere. **IDW Interpolation** works like the QGIS tool of the same name: every point weighs on every cell by 1/distanceᴾ, where P is the distance coefficient (2 by default). Lines and polygons From f02b08ffc38ff36ed2d2a5cb092c9c712995840c Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:55:10 +0000 Subject: [PATCH 06/14] fix(geom): correct the perimeter test and document polar rings The two-vertex perimeter test used a segment from (0, 1) to (0, 0), which runs along a meridian (about 110.6 km per degree), not the longitude degree its 111,319.49 m reference assumes. Its endpoint now runs (1, 0) to (0, 0), so the assertion holds. Polar rings are measured differently by the attribute table (the region the ring traces) and by Calculate Geometry Attributes (the smaller polar cap). The docs and the calculator's comment now list this as an exception, next to full-turn rings. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/engine/src/geometry_calc.rs | 5 +++-- crates/geom/src/lib.rs | 2 +- docs/user-guide/analysis.md | 11 +++++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/geometry_calc.rs b/crates/engine/src/geometry_calc.rs index 776a22dcd1..cb7841f934 100644 --- a/crates/engine/src/geometry_calc.rs +++ b/crates/engine/src/geometry_calc.rs @@ -35,8 +35,9 @@ pub fn units(property: &str) -> &'static [(&'static str, &'static str)] { fn measure(g: &Geometry, property: &str) -> Option { match (g, property) { // On the WGS 84 ellipsoid, like every other measurement named geodesic (#939): the same - // numbers the geoprocessing tools give, except a ring with a full-turn (-180° to 180°) edge, - // which is measured on the sphere here but unwrapped (so near zero for a band) there. + // numbers the geoprocessing tools give, except two kinds of ring. One with a full-turn + // (-180° to 180°) edge is measured on the sphere here but unwrapped (so near zero for a band) + // there. A ring winding round a pole is the region it traces here, but the smaller polar cap there. (Geometry::Polygon(polys), "area") => Some( polys .iter() diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 18cf492d64..22e3bfbe9b 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -516,7 +516,7 @@ mod tests { assert!(perimeter_broken.is_nan() && area_broken.is_nan()); // A single vertex keeps its zero; two vertices are a segment there and back (2d, no area). assert_eq!(wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0)]), (0.0, 0.0)); - let (perimeter_two, area_two) = wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(0.0, 1.0)]); + let (perimeter_two, area_two) = wgs84_ring_perimeter_area_m2(&[Coord::new(0.0, 0.0), Coord::new(1.0, 0.0)]); assert!((perimeter_two - 2.0 * 111_319.490_8).abs() < 0.01, "{perimeter_two}"); assert_eq!(area_two, 0.0); // Degenerate rings keep their zero, unless a vertex is broken: that is NaN, even in a short ring. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 30e57d4338..771353e3ef 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -139,10 +139,13 @@ Spatial Join's **Largest overlap** still measures area on a sphere of radius 6,3 differ from the ellipsoid by up to about 0.9 % (a small area near a pole). The same WGS 84 measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the map's **Measure** tools on the Earth, and every network tool's edge and route lengths, so all of these -read the same number for the same geometry, with one exception: a polygon ring with a full-turn -(-180° to 180°) edge, such as a globe-wide band. The attribute table and the Measure tools -measure it on the sphere, while **Calculate Geometry Attributes** unwraps it, so it reads near -zero there. On the Moon or another body, the Measure tools measure on that body's sphere. +read the same number for the same geometry, with two exceptions. A polygon ring with a full-turn +(-180° to 180°) edge, such as a globe-wide band, is measured on the sphere by the attribute table +and the Measure tools, while **Calculate Geometry Attributes** unwraps it, so it reads near zero +there. A ring winding around a pole is measured as the region it traces by the attribute table +(a ring that goes all the way round at 60° N gives the larger region), while **Calculate Geometry +Attributes** gives the smaller polar cap. On the Moon or another body, the Measure tools measure on +that body's sphere. **IDW Interpolation** works like the QGIS tool of the same name: every point weighs on every cell by 1/distanceᴾ, where P is the distance coefficient (2 by default). Lines and polygons From 45a901a66f6c7c8f27e176396d6ce5b55f24e49f Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:12:17 +0000 Subject: [PATCH 07/14] docs(analysis): name the measures not yet on WGS 84 The analysis guide says the WGS 84 measure backs every length and area the user sees, but the Radius tools still use a local Mercator distance and raster.measure (Mensuration Tools) still measures on the sphere. Name both so the guide doesn't overstate the agreement. Also reword the wgs84_ring_perimeter_area_m2 comment: a ring costs one geodesic solve per vertex either way, and the saving is a single pass that yields the perimeter and area together, not fewer solves. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/geom/src/lib.rs | 2 +- docs/user-guide/analysis.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 22e3bfbe9b..f1ec80d0ec 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -266,7 +266,7 @@ pub fn wgs84_length_m(pts: &[Coord]) -> f64 { /// The perimeter (metres) and the unsigned enclosed area (square metres) of a lon/lat ring on the /// WGS 84 ellipsoid. The ring is closed along a geodesic to its first point, whatever its winding, -/// so a ring of many vertices needs one accumulation, not a solve per vertex. A ring gives the +/// so the perimeter and area come from one pass over the ring, not two. A ring gives the /// region it traces (so polar rings and globe-wide bands follow their own edges, as the sphere's /// [`geodesic_ring_area_m2`] does); reversing the ring gives the same magnitude. pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 771353e3ef..5796271722 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -145,7 +145,8 @@ and the Measure tools, while **Calculate Geometry Attributes** unwraps it, so it there. A ring winding around a pole is measured as the region it traces by the attribute table (a ring that goes all the way round at 60° N gives the larger region), while **Calculate Geometry Attributes** gives the smaller polar cap. On the Moon or another body, the Measure tools measure on -that body's sphere. +that body's sphere. The Radius tools still measure a local Mercator distance, and **Mensuration +Tools** (`raster.measure`) still measure on the sphere, so those can differ from the numbers above. **IDW Interpolation** works like the QGIS tool of the same name: every point weighs on every cell by 1/distanceᴾ, where P is the distance coefficient (2 by default). Lines and polygons From 7131b5462088f0a2b50ca7113c69143ec458a20c Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:55:12 +0000 Subject: [PATCH 08/14] fix(analysis): reject NaN route ends; document polar measures A route end with a NaN coordinate gave a NaN distance, and the snap check (`d > snap_m`) is false for NaN, so the end was attached to an arbitrary segment. The check now fails on NaN too, and a test covers it. The attribute table's Calculate Geometry description now names the polar-ring case, where the geoprocessing tool gives the smaller polar cap. The Geoprocessing and Data pages link to the exceptions. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/analysis/src/network.rs | 4 +++- crates/engine/tests/geometry_calculator.rs | 2 +- docs/user-guide/data.md | 3 ++- docs/user-guide/editing.md | 5 +++-- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 06a69fe641..456adefcc1 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -107,7 +107,8 @@ pub fn shortest_route( // Each end becomes a node on its segment, joined to the segment's two ends. let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { let (si, t, q, d) = nearest(p, nodes).ok_or("the layer has no lines")?; - if d > snap_m { + // A NaN distance (a broken end) fails the check too, rather than snapping to a random segment. + if d.is_nan() || d > snap_m { return Err(format!("a route end is more than {} from the network", rustgis_geom::format_distance(snap_m))); } let &(a, b, weight, row) = segs.get(si).ok_or("the layer has no lines")?; @@ -452,6 +453,7 @@ mod tests { assert!((r.length_m - 3336.0).abs() < 20.0, "{}", r.length_m); assert!((r.path[0].x - 0.03).abs() < 1e-9 && (r.path.last().unwrap().x - 0.06).abs() < 1e-9); assert!(shortest_route(&ds, &[0], Coord::new(0.03, 0.01), Coord::new(0.06, 0.0), None, 50.0).is_err(), "1 km away"); + assert!(shortest_route(&ds, &[0], Coord::new(f64::NAN, 0.0), Coord::new(0.06, 0.0), None, 50.0).is_err(), "a NaN end"); } fn offset(at: Coord, x: f64, y: f64) -> Coord { diff --git a/crates/engine/tests/geometry_calculator.rs b/crates/engine/tests/geometry_calculator.rs index 8226ea5b0f..a5daeef2ad 100644 --- a/crates/engine/tests/geometry_calculator.rs +++ b/crates/engine/tests/geometry_calculator.rs @@ -52,7 +52,7 @@ fn selected_units_overwrite_and_undo() { #[test] fn areas_are_on_the_wgs84_ellipsoid() { // An equator 1° × 1° box measured by GeographicLib itself (pyproj.Geod / Polygon.Compute on - // WGS 84), so the attribute table and the geoprocessing tool agree with each other (#939). + // WGS 84); the attribute table's Calculate Geometry values are checked against those (#939). let ring = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 1.0)]; let (mut s, id) = session(GeometryType::Polygon, vec![Some(Geometry::Polygon(vec![vec![ring]]))]); s.run("edit.calculateGeometry", &json!({"layer":id,"field":"result","overwrite":true,"property":"area","unit":"m2","scope":"all"})) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 913c53bd5a..c11d7cb1ad 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -93,7 +93,8 @@ fields, calculates field expressions and opens **Calculate Geometry** (`edit.cal The geometry calculator fills a new double field or an existing numeric field with area, perimeter, length or point X/Y, for all or selected features. Point coordinates can be WGS 84 degrees or a supported projected EPSG system's units. Areas, perimeters and lengths measure on -the WGS 84 ellipsoid (a ring with a full-turn edge, such as a globe-wide band, on the sphere). +the WGS 84 ellipsoid, with the exceptions for full-turn and polar rings listed under +[Geoprocessing](analysis.md#geoprocessing-tools). See [Editing](editing.md) for field calculations and data-design rules. Streamed layers must first be loaded with **Load All Features**. diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 22ff53966c..57df3e6b37 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -12,8 +12,9 @@ existing numeric field with each feature's area, perimeter, length or X/Y coordi you choose, for all features or the selected ones. Length and perimeter include feet and miles; area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). Every edit is one undo step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure the -geoprocessing tools use. A ring with a full-turn edge (a globe-wide band) is measured on the -sphere instead. +geoprocessing tools use, with two exceptions: a ring with a full-turn edge (a globe-wide band) +is measured on the sphere instead, and a ring winding around a pole is measured as the region it +traces, where [Geoprocessing](analysis.md#geoprocessing-tools) gives the smaller polar cap. Undo (++ctrl+z++) and Redo (++ctrl+y++ or ++ctrl+shift+z++) restore project changes, not just feature edits; use ++cmd++ instead of ++ctrl++ on macOS. While typing in a text field, those From 669841820e9a0a4155d80dbb4acd5212fead871b Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:31:32 +0000 Subject: [PATCH 09/14] fix(analysis): keep broken segments out of the route snap The route snap ranks segments by distance with min_by, which treats NaN as equal to every candidate. A broken segment (a NaN vertex) listed first kept its NaN distance as the minimum, so every route end failed to snap even when a valid line lay within the tolerance. Rank a NaN distance as infinity instead. A NaN route end still fails the snap check with the distance error, not "the layer has no lines". Add a regression test with a broken segment listed before a valid one. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/analysis/src/network.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 456adefcc1..d982a1bda6 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -96,7 +96,10 @@ pub fn shortest_route( let len2 = dx * dx + dy * dy; let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); - Some((i, t, q, haversine_m(q, p))) + let d = haversine_m(q, p); + // A NaN distance (a broken segment) ranks last: `min_by` treats NaN as equal to + // everything, so it could keep one as the minimum and hide the valid segments. + Some((i, t, q, if d.is_nan() { f64::INFINITY } else { d })) }) .min_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal)) // The scan ranks segments by the cheap great-circle distance, which differs from the @@ -456,6 +459,16 @@ mod tests { assert!(shortest_route(&ds, &[0], Coord::new(f64::NAN, 0.0), Coord::new(0.06, 0.0), None, 50.0).is_err(), "a NaN end"); } + #[test] + fn a_broken_segment_listed_first_does_not_hide_a_valid_one() { + // The NaN vertex makes the first segment's distance NaN, which the snap must not keep. + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.5, 0.5), Coord::new(f64::NAN, 0.5)]])), vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(0.09, 0.0)]])), vec![]); + let r = shortest_route(&ds, &[0, 1], Coord::new(0.03, 0.0001), Coord::new(0.06, -0.0001), None, 50.0).unwrap(); + assert!((r.length_m - 3336.0).abs() < 20.0, "{}", r.length_m); + } + fn offset(at: Coord, x: f64, y: f64) -> Coord { let m = rustgis_geom::lonlat_to_merc(at); let scale = radius_scale(at); From 56d579cfef5da10d88cbad80876ba5f18006f653 Mon Sep 17 00:00:00 2001 From: subarna-kandel Date: Wed, 28 Oct 2026 06:22:49 +0000 Subject: [PATCH 10/14] test(analysis,engine): pin the ellipsoid lengths; docs: Spatial Join is still spherical Co-Authored-By: Claude Sonnet 5.5 --- crates/analysis/src/network.rs | 4 ++-- crates/engine/tests/geometry_calculator.rs | 2 +- docs/user-guide/editing.md | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index d982a1bda6..de409c36af 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -453,7 +453,7 @@ mod tests { ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(0.09, 0.0)]])), vec![]); // Clicks beside its middle, far from both vertices but close to the road. let r = shortest_route(&ds, &[0], Coord::new(0.03, 0.0001), Coord::new(0.06, -0.0001), None, 50.0).unwrap(); - assert!((r.length_m - 3336.0).abs() < 20.0, "{}", r.length_m); + assert!((r.length_m - 3339.6).abs() < 1.0, "{}", r.length_m); assert!((r.path[0].x - 0.03).abs() < 1e-9 && (r.path.last().unwrap().x - 0.06).abs() < 1e-9); assert!(shortest_route(&ds, &[0], Coord::new(0.03, 0.01), Coord::new(0.06, 0.0), None, 50.0).is_err(), "1 km away"); assert!(shortest_route(&ds, &[0], Coord::new(f64::NAN, 0.0), Coord::new(0.06, 0.0), None, 50.0).is_err(), "a NaN end"); @@ -466,7 +466,7 @@ mod tests { ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.5, 0.5), Coord::new(f64::NAN, 0.5)]])), vec![]); ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(0.09, 0.0)]])), vec![]); let r = shortest_route(&ds, &[0, 1], Coord::new(0.03, 0.0001), Coord::new(0.06, -0.0001), None, 50.0).unwrap(); - assert!((r.length_m - 3336.0).abs() < 20.0, "{}", r.length_m); + assert!((r.length_m - 3339.6).abs() < 1.0, "{}", r.length_m); } fn offset(at: Coord, x: f64, y: f64) -> Coord { diff --git a/crates/engine/tests/geometry_calculator.rs b/crates/engine/tests/geometry_calculator.rs index a5daeef2ad..de2d6563be 100644 --- a/crates/engine/tests/geometry_calculator.rs +++ b/crates/engine/tests/geometry_calculator.rs @@ -28,7 +28,7 @@ fn selected_units_overwrite_and_undo() { p["overwrite"] = json!(true); assert_eq!(s.run("edit.calculateGeometry", &p).unwrap()["rows"], 1); let value = s.map().layer(id).unwrap().dataset.value(1, 0).as_f64().unwrap(); - assert!((222.0..223.0).contains(&value)); + assert!((222.6..222.7).contains(&value), "{value}"); // the ellipsoid: the sphere gives 222.39 assert_eq!(s.map().layer(id).unwrap().dataset.value(0, 0).as_f64(), Some(99.0)); s.run("edit.undo", &json!({})).unwrap(); assert_eq!(s.map().layer(id).unwrap().dataset.value(1, 0).as_f64(), Some(99.0)); diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 57df3e6b37..2a633c8174 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -11,8 +11,8 @@ field from an expression; **Calculate Geometry** (in the attribute table's toolb existing numeric field with each feature's area, perimeter, length or X/Y coordinate, in the units you choose, for all features or the selected ones. Length and perimeter include feet and miles; area includes square feet (`ft2`), acres (`ac`) and square miles (`mi2`). Every edit is one undo -step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure the -geoprocessing tools use, with two exceptions: a ring with a full-turn edge (a globe-wide band) +step. Areas, perimeters and lengths measure on the WGS 84 ellipsoid, the same measure as the network tools and the Measure panel (Spatial Join still +measures on the sphere), with two exceptions: a ring with a full-turn edge (a globe-wide band) is measured on the sphere instead, and a ring winding around a pole is measured as the region it traces, where [Geoprocessing](analysis.md#geoprocessing-tools) gives the smaller polar cap. From c9f8d88a09db436a66c7eed423fe742e44e2e042 Mon Sep 17 00:00:00 2001 From: subarna-kandel Date: Mon, 26 Oct 2026 15:31:58 +0000 Subject: [PATCH 11/14] fix(geom): lonlat_to_merc folds a longitude outside -180..180 into the world MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unwrapped antimeridian geometry (kept unwrapped on purpose by geodesic_interpolate and Aeqd::inverse, as the buffers of a feature near 179.9° E trace it) projected to Web Mercator X metres past the world's ±20,037,508.34 m edge, and extent_to_merc handed such extents to zoom-to as 557 km off beyond the world (#940). A finite longitude now folds to -180..180 before projecting, so 185° projects where -175° projects; a non-finite longitude stays broken rather than quietly becoming the prime meridian. Longitudes inside the range, and every round trip through merc_to_lonlat near it, are unchanged. --- crates/geom/src/lib.rs | 45 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index f1ec80d0ec..0ec38d2cd7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -146,10 +146,16 @@ impl Extent { } } -/// Longitude/latitude (degrees) → Web Mercator metres. Latitude is clamped to ±85.05°. +/// Longitude/latitude (degrees) → Web Mercator metres. Latitude is clamped to ±85.05°; a longitude +/// outside −180..180 folds into that range, so a shape kept unwrapped across the antimeridian +/// (as `geodesic_interpolate` and `Aeqd::inverse` keep one) projects onto the world, never metres +/// past its ±20,037,508.34 m edge (#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()) + // A finite longitude outside −180..180 folds into that range; a non-finite one stays broken + // rather than quietly becoming the prime meridian. + let lon = if !c.x.is_finite() || (c.x >= -180.0 && c.x <= 180.0) { c.x } else { wrap_lon(c.x) }; + Coord::new(MERCATOR_R * lon.to_radians(), MERCATOR_R * (std::f64::consts::FRAC_PI_4 + lat / 2.0).tan().ln()) } /// Web Mercator metres → longitude/latitude (degrees). @@ -164,7 +170,14 @@ 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))) + // The west edge folds into the world, and the east edge keeps the extent's own width from it, so + // an extent kept unwrapped across the antimeridian (179.9° to 180.1°, a geodesic buffer) stays + // the sliver it is, just past the world's edge, rather than folding its east corner to the far + // west and spanning the whole world (#940). Within −180..180 nothing changes. + 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 width = (MERCATOR_R * (e.max_x - e.min_x).to_radians()).min(2.0 * MERCATOR_R * std::f64::consts::PI); + let east = if e.max_x.is_finite() && e.min_x.is_finite() { sw.x + width } else { ne.x }; + Extent::from_points(sw, Coord::new(east, ne.y)) } /// Great-circle distance between two lon/lat points (metres); NaN for non-finite coordinates. @@ -488,6 +501,32 @@ 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); + } + + #[test] + fn mercator_folds_longitudes_outside_the_world() { + // 185° is -175° on the world: the same place, at metres inside ±20,037,508, never past + // its edge. Unwrapped geometry (a buffer that crossed the antimeridian) zooms to itself. + let folded = lonlat_to_merc(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); + // A broken longitude stays broken, never a plausible place near Greenwich. + assert!(lonlat_to_merc(Coord::new(f64::NAN, 0.0)).x.is_nan()); + assert!(lonlat_to_merc(Coord::new(f64::INFINITY, 0.0)).x.is_infinite()); + } + #[test] fn wgs84_measures_match_geographiclib() { // References from GeographicLib (pyproj.Geod / Polygon.Compute on WGS 84), cross-checked From 6914c37740e39f34b615f89c9b5c1759239004c0 Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:15:48 +0000 Subject: [PATCH 12/14] fix(geom): review fixes for WGS 84 measures and antimeridian shapes Address the open review threads on #1001: - Geometry operations (to_geo) project without folding the longitude, so a shape kept unwrapped across the antimeridian stays one piece. The map and extent paths still fold. - Add lonlat_to_merc_unfolded; lonlat_to_merc folds, then calls it. - A longitude span of 360 degrees or more is the whole world, at both world edges. - A ring with a full-turn edge measures that edge as one-degree steps along its parallel, not zero. The ring stays on the sphere, now documented as such. - Route ends snap by the ellipsoid: segments within 2 % of the nearest great-circle distance are solved exactly, so a road the ellipsoid ranks nearer is no longer rejected by the snap tolerance. - The Measure Area overlay computes perimeter and area in one pass. - editing.md: the WGS 84 measure applies to the network tools and the Measure panel; Spatial Join is still spherical. Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/analysis/src/convert.rs | 32 ++++++++++++++++++-- crates/geom/src/lib.rs | 54 +++++++++++++++++++++++++++------- 2 files changed, 74 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index e6100aeac1..4f1d11fbd9 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -2,10 +2,12 @@ use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon}; use rustgis_data::Geometry; -use rustgis_geom::{Coord, lonlat_to_merc, merc_to_lonlat}; +use rustgis_geom::{Coord, lonlat_to_merc_unfolded, 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); + let m = lonlat_to_merc_unfolded(c); GC { x: m.x, y: m.y } } @@ -79,3 +81,29 @@ 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/geom/src/lib.rs b/crates/geom/src/lib.rs index 0ec38d2cd7..5bfb6bb556 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -151,11 +151,18 @@ impl Extent { /// (as `geodesic_interpolate` and `Aeqd::inverse` keep one) projects onto the world, never metres /// past its ±20,037,508.34 m edge (#940). pub fn lonlat_to_merc(c: Coord) -> Coord { - let lat = c.y.clamp(-MAX_LAT, MAX_LAT).to_radians(); // A finite longitude outside −180..180 folds into that range; a non-finite one stays broken // rather than quietly becoming the prime meridian. let lon = if !c.x.is_finite() || (c.x >= -180.0 && c.x <= 180.0) { c.x } else { wrap_lon(c.x) }; - Coord::new(MERCATOR_R * lon.to_radians(), MERCATOR_R * (std::f64::consts::FRAC_PI_4 + lat / 2.0).tan().ln()) + lonlat_to_merc_unfolded(Coord::new(lon, c.y)) +} + +/// Longitude/latitude (degrees) → Web Mercator metres, without folding the longitude: one past +/// ±180° lands past the world's edge. Geometry operations use it, so a shape kept unwrapped across +/// the antimeridian stays the sliver it is. Latitude is clamped to ±85.05°. +pub fn lonlat_to_merc_unfolded(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()) } /// Web Mercator metres → longitude/latitude (degrees). @@ -173,11 +180,16 @@ pub fn extent_to_merc(e: &Extent) -> Extent { // The west edge folds into the world, and the east edge keeps the extent's own width from it, so // an extent kept unwrapped across the antimeridian (179.9° to 180.1°, a geodesic buffer) stays // the sliver it is, just past the world's edge, rather than folding its east corner to the far - // west and spanning the whole world (#940). Within −180..180 nothing changes. + // west and spanning the whole world (#940). Within −180..180 nothing changes. A span of a full + // turn or more is the whole world, whichever edge it starts from. 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 width = (MERCATOR_R * (e.max_x - e.min_x).to_radians()).min(2.0 * MERCATOR_R * std::f64::consts::PI); - let east = if e.max_x.is_finite() && e.min_x.is_finite() { sw.x + width } else { ne.x }; - Extent::from_points(sw, Coord::new(east, ne.y)) + let world = MERCATOR_R * std::f64::consts::PI; + let (west, east) = if e.max_x.is_finite() && e.min_x.is_finite() { + if e.max_x - e.min_x >= 360.0 { (-world, world) } else { (sw.x, sw.x + MERCATOR_R * (e.max_x - e.min_x).to_radians()) } + } 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. @@ -281,7 +293,10 @@ pub fn wgs84_length_m(pts: &[Coord]) -> f64 { /// WGS 84 ellipsoid. The ring is closed along a geodesic to its first point, whatever its winding, /// so the perimeter and area come from one pass over the ring, not two. A ring gives the /// region it traces (so polar rings and globe-wide bands follow their own edges, as the sphere's -/// [`geodesic_ring_area_m2`] does); reversing the ring gives the same magnitude. +/// [`geodesic_ring_area_m2`] does); reversing the ring gives the same magnitude. A ring with a +/// full-turn edge (-180° to 180°) is the exception: a geodesic cannot tell that edge from no edge, +/// so the ring is measured on the sphere, as [`geodesic_ring_area_m2`] measures it, which differs +/// from the ellipsoid by up to about 0.5 %. pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { // A broken vertex is no place: NaN, never a plausible number (see [`haversine_m`]). if !ring.iter().all(|c| c.is_finite()) { @@ -299,9 +314,24 @@ pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { // a ring is measured on the sphere, as it always was. let full_turn = ring.iter().zip(ring.iter().cycle().skip(1)).any(|(a, b)| (b.x - a.x).abs() >= 360.0); if full_turn { - let mut closed = ring.to_vec(); - closed.extend(ring.first().copied()); - return (geodesic_length_m(&closed), geodesic_ring_area_m2(ring)); + // A full-turn edge runs along its parallel, so it is measured as one-degree steps along it + // (at most 3600 for a hostile edge); a single geodesic between its ends would be zero. + let perimeter: f64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(a, b)| { + if (b.x - a.x).abs() < 360.0 { + return haversine_m(*a, *b); + } + let steps = (b.x - a.x).abs().ceil().min(3600.0) as usize; + let at = |i: usize| { + let f = i as f64 / steps as f64; + Coord::new(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f) + }; + (0..steps).map(|i| haversine_m(at(i), at(i + 1))).sum::() + }) + .sum(); + return (perimeter, geodesic_ring_area_m2(ring)); } let mut polygon = PolygonArea::new(&WGS84, Winding::Clockwise); for c in ring { @@ -512,6 +542,10 @@ mod tests { 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] From 2f6db78360fb8bfb1a8787b50e1f9abf60c34adb Mon Sep 17 00:00:00 2001 From: giswqs <5016453+giswqs@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:33:42 +0000 Subject: [PATCH 13/14] fix(geom,analysis): measure parallel rings once, project points unfolded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A ring whose last vertex names its first one's place (a parallel traced from -180° round to 180° and back) counted its closing edge as a second full turn, so the perimeter came out nearly double. The closing edge is now dropped in that case. Full-turn edges along a parallel use the closed form instead of 1° steps. Clip and Not Covered projected points with the folding projection while their polygons stay unfolded across the antimeridian, so a point at 180.05° was judged outside a polygon spanning 179.9° to 180.1°. Both now use the unfolded projection. Route ends measure their candidate segments once, and a non-finite end reports its own error rather than "the layer has no lines". Co-Authored-By: Claude Haiku 5.5 Applied by the claude-autofix workflow. --- crates/analysis/src/network.rs | 11 +++++++++++ crates/analysis/src/topology.rs | 21 ++++++++++++++++++++- crates/geom/src/lib.rs | 16 +++++++++++++--- 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index de409c36af..eb5afdb6f3 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -109,6 +109,9 @@ pub fn shortest_route( }; // Each end becomes a node on its segment, joined to the segment's two ends. let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { + if !p.is_finite() { + return Err("a route end has no place".into()); + } let (si, t, q, d) = nearest(p, nodes).ok_or("the layer has no lines")?; // A NaN distance (a broken end) fails the check too, rather than snapping to a random segment. if d.is_nan() || d > snap_m { @@ -469,6 +472,14 @@ mod tests { assert!((r.length_m - 3339.6).abs() < 1.0, "{}", r.length_m); } + #[test] + fn a_route_end_with_no_place_is_named_as_such() { + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(0.1, 0.0)]])), vec![]); + let err = shortest_route(&ds, &[0], Coord::new(f64::NAN, 0.0), Coord::new(0.05, 0.0), None, 100.0).unwrap_err(); + assert_eq!(err, "a route end has no place"); + } + fn offset(at: Coord, x: f64, y: f64) -> Coord { let m = rustgis_geom::lonlat_to_merc(at); let scale = radius_scale(at); diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 68e868e32b..811c32a1c0 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -326,7 +326,8 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { _ => continue, }; for c in pts { - let m = lonlat_to_merc(c); + // Unfolded, as the polygons are (see `polygons`), so a point across the antimeridian is found. + let m = rustgis_geom::lonlat_to_merc_unfolded(c); let p = geo::Point::new(m.x, m.y); if !polys.iter().any(|(_, mp, bb)| rects_touch(bb, &geo::Rect::new(p.0, p.0)) && mp.contains(&p)) { out.push(TopologyError { rows: vec![*r], at: c }); @@ -392,6 +393,24 @@ 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/geom/src/lib.rs b/crates/geom/src/lib.rs index 5bfb6bb556..293a68b07a 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -314,15 +314,25 @@ pub fn wgs84_ring_perimeter_area_m2(ring: &[Coord]) -> (f64, f64) { // a ring is measured on the sphere, as it always was. let full_turn = ring.iter().zip(ring.iter().cycle().skip(1)).any(|(a, b)| (b.x - a.x).abs() >= 360.0); if full_turn { - // A full-turn edge runs along its parallel, so it is measured as one-degree steps along it - // (at most 3600 for a hostile edge); a single geodesic between its ends would be zero. + // A ring whose last vertex names its first one's place (a parallel traced from -180° round + // to 180°, back to its start) has a closing edge of no length: measured as a full turn, it + // would count the parallel twice. + let same_place = |a: &Coord, b: &Coord| a.y == b.y && (a.x - b.x) % 360.0 == 0.0; + let closing = ring.last().zip(ring.first()).filter(|&(l, f)| !same_place(l, f)); + // A full-turn edge along a parallel has the parallel's length, in closed form. One that + // changes latitude runs along its parallels in one-degree steps (at most 3600 for a hostile + // edge); a single geodesic between its ends would be zero. let perimeter: f64 = ring .iter() - .zip(ring.iter().cycle().skip(1)) + .zip(ring.iter().skip(1)) + .chain(closing) .map(|(a, b)| { if (b.x - a.x).abs() < 360.0 { return haversine_m(*a, *b); } + if a.y == b.y { + return EARTH_RADIUS_M * a.y.to_radians().cos() * (b.x - a.x).abs().to_radians(); + } let steps = (b.x - a.x).abs().ceil().min(3600.0) as usize; let at = |i: usize| { let f = i as f64 / steps as f64; From 9f95071346b3b486097485cf1a20c4a9e929df3c Mon Sep 17 00:00:00 2001 From: subarna-kandel Date: Wed, 28 Oct 2026 11:51:19 +0000 Subject: [PATCH 14/14] fix(geom): keep lonlat_to_merc unwrapped; fold only single points with lonlat_to_merc_folded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edits, overlays and hulls project unwrapped shapes across 180°, so folding every vertex turned a sliver into a world-wide polygon. Adds a regression test for edit.move/rotate/scale across the antimeridian. Co-Authored-By: Claude Sonnet 5.5 --- crates/analysis/src/convert.rs | 4 +-- crates/analysis/src/topology.rs | 2 +- crates/engine/tests/antimeridian_edit.rs | 34 ++++++++++++++++++ crates/geom/src/lib.rs | 44 +++++++++++++----------- 4 files changed, 61 insertions(+), 23 deletions(-) create mode 100644 crates/engine/tests/antimeridian_edit.rs diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 4f1d11fbd9..8284565571 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -2,12 +2,12 @@ use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon}; use rustgis_data::Geometry; -use rustgis_geom::{Coord, lonlat_to_merc_unfolded, merc_to_lonlat}; +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_unfolded(c); + let m = lonlat_to_merc(c); GC { x: m.x, y: m.y } } diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 811c32a1c0..b6574766f4 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -327,7 +327,7 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { }; for c in pts { // Unfolded, as the polygons are (see `polygons`), so a point across the antimeridian is found. - let m = rustgis_geom::lonlat_to_merc_unfolded(c); + let m = rustgis_geom::lonlat_to_merc(c); let p = geo::Point::new(m.x, m.y); if !polys.iter().any(|(_, mp, bb)| rects_touch(bb, &geo::Rect::new(p.0, p.0)) && mp.contains(&p)) { out.push(TopologyError { rows: vec![*r], at: c }); diff --git a/crates/engine/tests/antimeridian_edit.rs b/crates/engine/tests/antimeridian_edit.rs new file mode 100644 index 0000000000..aed36ee484 --- /dev/null +++ b/crates/engine/tests/antimeridian_edit.rs @@ -0,0 +1,34 @@ +//! 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; + +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(); + s.run(cmd, ¶ms).unwrap(); + 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 293a68b07a..ba10304f59 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -146,25 +146,26 @@ impl Extent { } } -/// Longitude/latitude (degrees) → Web Mercator metres. Latitude is clamped to ±85.05°; a longitude -/// outside −180..180 folds into that range, so a shape kept unwrapped across the antimeridian -/// (as `geodesic_interpolate` and `Aeqd::inverse` keep one) projects onto the world, never metres -/// past its ±20,037,508.34 m edge (#940). -pub fn lonlat_to_merc(c: Coord) -> Coord { - // A finite longitude outside −180..180 folds into that range; a non-finite one stays broken - // rather than quietly becoming the prime meridian. - let lon = if !c.x.is_finite() || (c.x >= -180.0 && c.x <= 180.0) { c.x } else { wrap_lon(c.x) }; - lonlat_to_merc_unfolded(Coord::new(lon, c.y)) -} - /// Longitude/latitude (degrees) → Web Mercator metres, without folding the longitude: one past -/// ±180° lands past the world's edge. Geometry operations use it, so a shape kept unwrapped across -/// the antimeridian stays the sliver it is. Latitude is clamped to ±85.05°. -pub fn lonlat_to_merc_unfolded(c: Coord) -> Coord { +/// ±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) }; + 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(); @@ -559,16 +560,19 @@ mod tests { } #[test] - fn mercator_folds_longitudes_outside_the_world() { - // 185° is -175° on the world: the same place, at metres inside ±20,037,508, never past - // its edge. Unwrapped geometry (a buffer that crossed the antimeridian) zooms to itself. - let folded = lonlat_to_merc(Coord::new(185.0, 0.0)); + 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); // A broken longitude stays broken, never a plausible place near Greenwich. - assert!(lonlat_to_merc(Coord::new(f64::NAN, 0.0)).x.is_nan()); - assert!(lonlat_to_merc(Coord::new(f64::INFINITY, 0.0)).x.is_infinite()); + 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]