diff --git a/AGENTS.md b/AGENTS.md index cc1e04852f..fda5a3c515 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -153,6 +153,11 @@ the pull request which of these it reaches and why the rest don't apply: `cargo xtask test-hygiene` (also in CI) requires `// test-wait: reason` on timer waits in tests and `#[ignore = "reason"]` on ignored tests, and refuses an `assert_eq!` or `assert_ne!` (or `debug_assert_*`) whose two sides are the same tokens; prefer completion or progress signals, and a fixed expected value. +`clippy.toml` refuses the four sphere measures in `rustgis-geom` (`haversine_m`, `geodesic_length_m`, +`geodesic_ring_perimeter_m`, `geodesic_ring_area_m2`): the Earth measures on the WGS 84 ellipsoid +(`wgs84_distance_m`, `wgs84_length_m`, `wgs84_step_m`, `wgs84_ring_perimeter_area_m2`), and a call kept on +the sphere, for another body or a comparison it can't change, says why in its +`#[expect(clippy::disallowed_methods, reason = "…")]`. `cargo xtask memory` (in CI on Linux) fails when a command line workflow's peak memory grows past its limit in `xtask/memory-limits.txt`; a change that lowers one commits the lower limit with it. `cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly diff --git a/clippy.toml b/clippy.toml index 7bada5473b..c7a236bd4f 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,3 +1,14 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true allow-panic-in-tests = true + +# The Earth measures on the WGS 84 ellipsoid (`wgs84_distance_m`, `wgs84_length_m`, +# `wgs84_ring_perimeter_area_m2`), as the Measure tool does (#939, #2568). These measure on a sphere: +# a call says why with `#[expect(clippy::disallowed_methods, reason = "…")]`, for another body +# (scaled by `Body`) or a comparison the sphere can't change. +disallowed-methods = [ + { path = "rustgis_geom::haversine_m", reason = "the sphere; the Earth measures with `wgs84_distance_m`" }, + { path = "rustgis_geom::geodesic_length_m", reason = "the sphere; the Earth measures with `wgs84_length_m`" }, + { path = "rustgis_geom::geodesic_ring_perimeter_m", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" }, + { path = "rustgis_geom::geodesic_ring_area_m2", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" }, +] diff --git a/crates/analysis/src/geodesic.rs b/crates/analysis/src/geodesic.rs index 0ac8d71145..ac0048954f 100644 --- a/crates/analysis/src/geodesic.rs +++ b/crates/analysis/src/geodesic.rs @@ -322,6 +322,10 @@ impl Plane { /// from the same edge straight in the analysis plane ([`lonlat_to_plane`]: Web Mercator within /// ±85.05°, straight in lon/lat beyond) by more than `tolerance` meters at its quarter points /// or midpoint. + #[expect( + clippy::disallowed_methods, + reason = "a tolerance for splitting an edge, not a measurement: ellipsoid distances are within 0.6% of the sphere's" + )] fn strays(&self, a: GC, b: GC, la: Coord, lb: Coord, tolerance: f64) -> bool { let at = |t: f64| self.0.inverse(Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y))); // `b` on `a`'s side of the antimeridian, so the straight edge is the short one. @@ -495,6 +499,7 @@ fn finite(parts: &[Vec]) -> Vec> { parts.iter().map(|p| p.iter().copied().filter(|c| c.is_finite()).collect::>()).filter(|p| !p.is_empty()).collect() } +#[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")] fn fits(pts: &[Coord], centre: Coord) -> bool { pts.iter().all(|c| haversine_m(centre, *c) <= ONE_PIECE_M) } @@ -504,6 +509,7 @@ fn stretched(parts: &[Vec], metres: f64) -> Vec> { let mut out = Vec::new(); for part in parts { let d = densify(part); + #[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")] let near = |a: usize, b: usize| d.get(a).zip(d.get(b)).is_some_and(|(a, b)| haversine_m(*a, *b) <= STRETCH_M); let mut start = 0; loop { @@ -528,6 +534,7 @@ fn stretched(parts: &[Vec], metres: f64) -> Vec> { /// A line with every edge split along its geodesic on WGS 84 into pieces of at most [`DENSIFY_M`], or /// longer ones for a line so long it would gain more than [`MAX_ADDED`] vertices. +#[expect(clippy::disallowed_methods, reason = "the densify step: it sets how many vertices an edge gains, not a measurement")] fn densify(pts: &[Coord]) -> Vec { let step = DENSIFY_M.max(rustgis_geom::geodesic_length_m(pts) / MAX_ADDED); let mut out: Vec = pts.first().copied().into_iter().collect(); diff --git a/crates/analysis/src/join.rs b/crates/analysis/src/join.rs index 655ecff801..0668f452c4 100644 --- a/crates/analysis/src/join.rs +++ b/crates/analysis/src/join.rs @@ -10,7 +10,9 @@ //! they are found there and measured straight, in the system's unit times its length. use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value}; -use rustgis_geom::{Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, wgs84_distance_m}; +use rustgis_geom::{ + Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, wgs84_distance_m, wgs84_length_m, wgs84_ring_perimeter_area_m2, +}; use serde_json::Value as Json; /// Whether a coordinate is a place on the Earth in lon/lat: finite, with a latitude of ±90° at most @@ -229,20 +231,24 @@ fn lon_gap(a: &Extent, b: &Extent) -> f64 { [-360.0, 0.0, 360.0].iter().map(|k| (b.min_x + k - a.max_x).max(a.min_x - (b.max_x + k)).max(0.0)).fold(f64::INFINITY, f64::min) } -/// The ground area (square metres) of a lon/lat polygon geometry, holes taken out. +/// The ground area (square metres) of a lon/lat polygon geometry on the WGS 84 ellipsoid, holes +/// taken out, as the Measure tool gives it. NaN for a ring whose winding is ambiguous. pub fn area_m2(g: &Geometry) -> f64 { let Geometry::Polygon(polys) = g else { return 0.0 }; polys .iter() .flat_map(|rings| rings.iter().enumerate()) - .map(|(i, r)| if i == 0 { geodesic_ring_area_m2(r) } else { -geodesic_ring_area_m2(r) }) + .map(|(i, r)| { + let (_, area) = wgs84_ring_perimeter_area_m2(r); + if i == 0 { area } else { -area } + }) .sum() } -/// The ground length (metres) of a lon/lat line geometry. +/// The ground length (metres) of a lon/lat line geometry on the WGS 84 ellipsoid. pub fn length_m(g: &Geometry) -> f64 { let Geometry::Line(parts) = g else { return 0.0 }; - parts.iter().map(|p| geodesic_length_m(p)).sum() + parts.iter().map(|p| wgs84_length_m(p)).sum() } /// How the values of a join field's matches become one value in a one-to-one join. @@ -495,6 +501,7 @@ mod tests { /// The ground distance from `p` to a line, by sampling each edge finely along its great circle. /// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid, /// whose distances are within 0.6% of the sphere's. + #[expect(clippy::disallowed_methods, reason = "the test ranks samples on the sphere and measures the nearest on the ellipsoid")] fn brute(p: Coord, line: &[Coord]) -> f64 { let samples: Vec<(Coord, f64)> = line .windows(2) @@ -506,6 +513,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test tells the ellipsoid's distance from the sphere's")] fn distances_are_on_the_wgs84_ellipsoid() { // 0.0904369° north of the equator is 10,000 m on WGS 84 (GeographicLib) but 10,056 m on the // mean sphere: within 10 km in the measure, and not ruled out before it (#888). @@ -518,6 +526,59 @@ mod tests { assert!(search_box(&ea, 10_000.0).is_some_and(|e| e.max_y >= b.y)); } + /// Spatial Join's Largest overlap ranks overlaps by their area or length on the WGS 84 + /// ellipsoid, as the Measure tool measures them. A 1° square on the equator, listed first, and a + /// band at 60°N that the ellipsoid makes 0.5% larger but the sphere 0.5% smaller: the band + /// wins. Likewise for a line along a meridian through a 1° zone and a shorter one at 60°N. + #[test] + #[expect(clippy::disallowed_methods, reason = "the test sets the sphere's ranking against the ellipsoid's")] + fn largest_overlap_ranks_overlaps_on_the_ellipsoid() { + use crate::{Inputs, Output}; + use rustgis_data::{Field, GeometryType}; + use rustgis_geom::{geodesic_length_m, geodesic_ring_area_m2}; + use std::collections::HashMap; + struct Layers(HashMap); + impl Inputs for Layers { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.0.get(layer) + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + } + let ring = |x0: f64, x1: f64, y0: f64, y1: f64| { + vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)] + }; + let zones = |band_top: f64| { + let mut ds = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + for (name, r) in [("equator", ring(0.0, 1.0, 0.0, 1.0)), ("north", ring(0.0, 1.0, 60.0, band_top))] { + ds.push(Some(Geometry::Polygon(vec![vec![r]])), vec![Value::Text(name.into())]); + } + ds + }; + let joined = |target: Dataset, zones: Dataset| { + let layers = Layers(HashMap::from([("t".to_string(), target), ("zones".to_string(), zones)])); + let r = crate::run("spatialJoin", &layers, &serde_json::json!({"target": "t", "join": "zones", "match": "Largest overlap"})); + let Ok(crate::ToolResult { output: Output::Layer(ds), .. }) = r else { panic!("a layer") }; + ds.field_index("join_zone").map(|i| ds.value(0, i).clone()) + }; + let north = Some(Value::Text("north".into())); + + let (square, band) = (ring(0.0, 1.0, 0.0, 1.0), ring(0.0, 1.0, 60.0, 62.054)); + let area = |r: &Vec| wgs84_ring_perimeter_area_m2(r).1; + assert!(area(&band) > area(&square) * 1.004 && geodesic_ring_area_m2(&band) < geodesic_ring_area_m2(&square) * 0.996); + let mut parcel = Dataset::new("t", GeometryType::Polygon, vec![]); + parcel.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 1.0, -1.0, 63.0)]])), vec![]); + assert_eq!(joined(parcel, zones(62.054)), north); + + let (near_equator, near_pole) = ([Coord::new(0.5, 0.0), Coord::new(0.5, 1.0)], [Coord::new(0.5, 60.0), Coord::new(0.5, 60.995)]); + assert!(wgs84_length_m(&near_pole) > wgs84_length_m(&near_equator) * 1.002); + assert!(geodesic_length_m(&near_pole) < geodesic_length_m(&near_equator) * 0.996); + let mut road = Dataset::new("t", GeometryType::Polyline, vec![]); + road.push(Some(Geometry::Line(vec![vec![Coord::new(0.5, -1.0), Coord::new(0.5, 63.0)]])), vec![]); + assert_eq!(joined(road, zones(60.995)), north); + } + #[test] fn an_integer_sum_takes_decimals_over_the_whole_i64_range() { let sum = Merge { field: 0, rule: Rule::Sum, delimiter: String::new() }; diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index a57a97d5e9..b6b35599a7 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -295,6 +295,10 @@ fn shortest_route_with( /// The closest point on any of `segs` to `p`: (segment, fraction along it, the point, metres /// away). With `within`, only segments whose box comes within about that many metres of `p` are /// measured; one farther can't be within it, so a nearer one is never missed. +#[expect( + clippy::disallowed_methods, + reason = "a lower bound that skips candidates, scaled to the ellipsoid's smallest radius; the distance kept is the ellipsoid's" +)] fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option) -> Result, String> { crate::control::check()?; let window = within.and_then(|m| snap_window(p, m)); @@ -1733,6 +1737,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test compares the sphere's ranking with the ellipsoid's")] fn snap_acceptance_uses_the_nearest_ellipsoidal_candidate() { let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); // At the equator, 0.001 degrees east is nearer on the sphere than 0.001003 diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 4be519e3fe..68dd220612 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -411,6 +411,10 @@ pub fn weighted_overlay(criteria: &[(Vec, f64)]) -> Result, String } /// Metres between two longitude/latitude points. +#[expect( + clippy::disallowed_methods, + reason = "the elevation profile's distances stay on the sphere for now: a solve per path vertex costs about 20 times as much on the ellipsoid, and the profile commands run on the command thread" +)] fn dist_m(a: Coord, b: Coord) -> f64 { rustgis_geom::haversine_m(a, b) } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 644fd8a0cf..9c7b83a4b8 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3840,6 +3840,7 @@ const ELLIPSOID_STRETCH: f64 = 1.005; /// (Leaving out a vertex only shortens a part.) Coordinates are folded and clamped as GeographicLib /// takes them, so the bound holds for any finite ones. In a projected system's own plane, the bound /// is the edges' flat metres, as the walk adds them up, and a hair more. +#[expect(clippy::disallowed_methods, reason = "an upper bound, stretched by `ELLIPSOID_STRETCH` to cover the ellipsoid's longer paths")] fn length_bound(line: &[Vec], ring: bool) -> f64 { if let Some(unit) = crate::convert::own_unit_m() { let mut verts = line.iter().flatten().filter(|c| c.is_finite()); @@ -11139,6 +11140,7 @@ mod tests { /// The distance on WGS 84 (km) from `c` to a line, sampled every `step` metres along it. /// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid, /// whose distances are within 0.6% of the sphere's. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn km_to_every(c: Coord, line: &[Coord], step: f64) -> f64 { let samples: Vec<(Coord, f64)> = line .windows(2) @@ -11203,6 +11205,7 @@ mod tests { } /// Points along the geodesic from `a` to `b` on WGS 84, at most 20 m apart. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn geodesic_samples(a: Coord, b: Coord) -> Vec { use geo::InterpolatePoint; let n = (rustgis_geom::haversine_m(a, b) / 20.0).ceil().max(1.0) as usize; @@ -11216,6 +11219,7 @@ mod tests { /// its nearest point is strictly between the ends: the nearest sample on the sphere (among /// every 50th, then its neighbours), then the nearest point on the ellipsoid along the geodesic /// either side of it, by golden-section search to well under a millimetre. + #[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")] fn m_to_geodesic(c: Coord, samples: &[Coord]) -> (f64, bool) { use geo::InterpolatePoint; let near = |range: std::ops::Range, step: usize| { diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 1427c9e7b0..0a64dd7719 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -819,6 +819,10 @@ fn plane_at<'a>(geoms: impl IntoIterator, steps: &mut Cente let mut last = a; for k in 1..=n as usize { let q = if k as f64 >= n { b } else { at(k as f64 / n) }; + #[expect( + clippy::disallowed_methods, + reason = "weighs a centre by its pieces' lengths, not a measurement; polar edits wait on #2032 step C2f-6" + )] edges.add_weighted(at((k as f64 - 0.5) / n), haversine_m(last, q)); last = q; } @@ -1412,6 +1416,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { let mut dists: Vec = Vec::new(); if ground { dists.try_reserve(parts.iter().map(Vec::len).sum()).map_err(|_| "not enough memory to split the selected lines")?; + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] dists.extend( parts .iter() @@ -1465,6 +1473,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { // nearer than the one found. let unsure = d > steps.floor; // At a vertex (to within a millimeter), the parts meet there, without it repeated. + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] let at_end = [part.get(si), part.get(si + 1)].into_iter().flatten().find(|v| rustgis_geom::haversine_m(**v, q) < 0.001); let q = at_end.copied().unwrap_or(q); let mut first: Vec = part.iter().take(si + 1).copied().collect(); @@ -1474,6 +1486,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult { let mut second = vec![q]; second.extend(part.iter().skip(si + 1).copied().skip_while(|c| *c == q)); // At (or within a centimetre of) the line's ends isn't a split. + #[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" + )] let near = |a: Option<&Coord>| a.is_some_and(|a| rustgis_geom::haversine_m(*a, q) < 0.01); if first.len() < 2 || second.len() < 2 || near(first.first()) || near(second.last()) { whole += usize::from(unsure); @@ -1545,6 +1561,10 @@ struct SplitSteps { /// a millimeter, nearest first, while it could hold a point nearer than the nearest found, or than /// `bound`. Each distance takes one of the command's `steps`; once they're spent, the nearest /// found (the nearer end, at first) stands, and `steps` notes how near the rest might be. +#[expect( + clippy::disallowed_methods, + reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6" +)] fn nearest_on_ground(at: Coord, (a, b): (Coord, Coord), (da, db): (f64, f64), bound: f64, steps: &mut SplitSteps) -> Option<(f64, Coord)> { const STEP_DEG: f64 = 22.5; const PIECES_MIN: usize = 8; @@ -2891,6 +2911,7 @@ mod tests { } #[test] + #[expect(clippy::disallowed_methods, reason = "the test checks the split's search on the sphere it uses")] fn a_split_searches_a_segment_within_its_budget() { // From 89°N on 0°, along 88°N from 30°W to 30°E: searched, its nearest point is on 0°, a // kilometer nearer than its ends, and the search takes a few dozen of the budget; with diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7039e1ab51..7cc5f9a639 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1909,6 +1909,10 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { } // On the Earth, each leg's length on the sphere (as the profile below spaces its // samples) and on the ellipsoid; the flat length is the ellipsoid's. + #[expect( + clippy::disallowed_methods, + reason = "the sphere spaces the profile's samples, as `rasterops::profile` does; the lengths are the ellipsoid's" + )] let legs: Vec<(f64, f64)> = if earth { pts.windows(2) .map(|w| match w { @@ -1919,6 +1923,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { } else { Vec::new() }; + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let flat = if earth { legs.iter().map(|l| l.1).sum() } else { body.length(rustgis_geom::geodesic_length_m(&pts)) }; // Along the surface when there's an elevation raster. The profile spaces its samples // along the path on the sphere; on the Earth each step's ground run is taken from the @@ -1954,6 +1959,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult { if rustgis_geom::ring_area_is_ambiguous(&ring) { return Err("the area is ambiguous: 1 ring winds beyond one whole surface".into()); } + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let (perimeter, area) = if earth { rustgis_geom::wgs84_ring_perimeter_area_m2(&ring) } else { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 43a34c3e0b..633c80f4e1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -17750,6 +17750,7 @@ fn exporting_a_raster_as_a_cog() { /// Mensuration measures the Earth on the WGS 84 ellipsoid, as the Measure tool does, so the same /// points give the same numbers in both; another body keeps its sphere (#2568). #[test] +#[expect(clippy::disallowed_methods, reason = "the test tells the ellipsoid's area from the sphere's")] fn mensuration_measures_the_earth_on_the_ellipsoid() { use rustgis_geom::Coord; let mut s = world(); @@ -42152,6 +42153,7 @@ fn scripts_refuse_edits_to_streamed_layers() { /// A map on Mars (#223): the body switcher puts a Mars basemap under it, its measurements and /// scale are Mars', and the project keeps the body; back on the Earth the Mars basemap goes. #[test] +#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn celestial_bodies_set_the_basemap_and_the_measurements() { let mut s = Session::new(Project::default()); let earth = |s: &mut Session| { diff --git a/crates/engine/tests/integration/polar_edits.rs b/crates/engine/tests/integration/polar_edits.rs index c276253845..82d679750e 100644 --- a/crates/engine/tests/integration/polar_edits.rs +++ b/crates/engine/tests/integration/polar_edits.rs @@ -298,6 +298,7 @@ fn points_around_a_pole_moved_keep_their_longitudes_as_written() { } #[test] +#[expect(clippy::disallowed_methods, reason = "the test finds the nearest point as the split does, on the sphere")] fn a_split_beyond_85_degrees_cuts_at_the_point_nearest_on_the_ground() { // From 86°N on 0° to 89°N on 60°E, straight in longitude and latitude. Its nearest point to // 88.5°N on 0° is near 47°E on the ground, while the plane's would be near 13°E. @@ -389,6 +390,7 @@ fn a_split_too_long_to_search_in_full_says_so() { } #[test] +#[expect(clippy::disallowed_methods, reason = "the test finds the nearest point as the split does, on the sphere")] fn a_split_along_an_edge_going_around_a_pole_finds_its_nearest_turn() { // One edge from 87°N to 89°N, straight in longitude and latitude, going twice around the pole: // asked at 87.56°N on 144°W, it's cut where it comes nearest, as a fine sampling finds. diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index c6f77797a5..ae52ab0e9e 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -492,6 +492,7 @@ fn slope_runs_on_a_raster_layer() { } #[test] +#[expect(clippy::disallowed_methods, reason = "a rough check of a buffer's area, to within 5%")] fn vector_tools_work_in_metres_and_return_lonlat() { let Some(f) = setup() else { return }; let r = rustgis_analysis::run("geolibre:buffer_vector", &f, &json!({"input": "pts", "distance": "1000"})).unwrap(); diff --git a/crates/geom/src/body.rs b/crates/geom/src/body.rs index 0bc6a3a9e5..af1b94e8bc 100644 --- a/crates/geom/src/body.rs +++ b/crates/geom/src/body.rs @@ -88,6 +88,7 @@ mod tests { use super::*; #[test] + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn bodies_scale_measurements_by_their_radius() { assert_eq!(Body::get("earth").ratio(), 1.0); assert_eq!(Body::get("nope").id, "earth"); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 618ea9754a..5c8eb7fcfc 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -451,6 +451,27 @@ pub fn wgs84_direct(c: Coord, azimuth_deg: f64, dist_m: f64) -> (Coord, f64) { (Coord::new(lon, lat), azi2) } +/// The distance (metres) between two nearby lon/lat points on the WGS 84 ellipsoid, for the many +/// short steps of a long line (a route's): from the ellipsoid's radii of curvature along and across +/// the meridian at the two points' mean latitude, within a millionth of [`wgs84_distance_m`] for a +/// step of up to 0.05° in latitude and in longitude below 89°, and [`wgs84_distance_m`] itself for +/// any other. It costs a few operations, where a geodesic solve costs about 20 times a haversine. +/// NaN for a coordinate that isn't finite. +pub fn wgs84_step_m(a: Coord, b: Coord) -> f64 { + if !a.is_finite() || !b.is_finite() { + return f64::NAN; + } + let (dlat, dlon) = (b.y - a.y, wrap_lon(b.x - a.x)); + if dlat.abs() > 0.05 || dlon.abs() > 0.05 || a.y.abs().max(b.y.abs()) > 89.0 { + return wgs84_distance_m(a, b); + } + let (s, c) = ((a.y + b.y) / 2.0).to_radians().sin_cos(); + let w2 = 1.0 - WGS84_E2 * s * s; + let across = WGS84_A / w2.sqrt(); + let along = across * (1.0 - WGS84_E2) / w2; + (along * dlat.to_radians()).hypot(across * c * dlon.to_radians()) +} + /// 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). @@ -735,6 +756,7 @@ fn ring_lon_steps(ring: &[Coord]) -> Vec<(f64, bool)> { /// [`ring_lon_steps`]), which is its whole parallel. The sphere's counterpart of /// [`wgs84_ring_perimeter_area_m2`]'s perimeter; [`geodesic_length_m`] of the closed ring counts /// a full turn as nothing, the distance between its two ends. +#[expect(clippy::disallowed_methods, reason = "the sphere's own perimeter, for other bodies scaled by `Body`")] pub fn geodesic_ring_perimeter_m(ring: &[Coord]) -> f64 { if ring.len() < 2 { return 0.0; @@ -1015,6 +1037,7 @@ pub fn format_dms(c: Coord) -> String { format!("{} {ew} {} {ns}", dms(c.x), dms(c.y)) } +#[expect(clippy::disallowed_methods, reason = "tests check the sphere's formulas, against the ellipsoid's among others")] #[cfg(test)] mod tests { use super::*; @@ -1549,6 +1572,29 @@ mod tests { assert!(geodesic_destination(Coord::new(10.0, 50.0), 90.0, f64::NAN).x.is_nan()); } + /// A short step measured from the ellipsoid's radii agrees with the geodesic solve to within a + /// millionth, at every latitude below 89° and across the antimeridian; a longer step, or one by + /// a pole, is the solve itself. + #[test] + fn wgs84_steps_agree_with_the_geodesic() { + let mut worst: f64 = 0.0; + for lat in (-89..=88).map(f64::from) { + for (dx, dy) in [(0.05, 0.0), (0.0, 0.05), (0.05, 0.05), (-0.03, 0.01), (1e-5, -2e-5)] { + for lon in [-179.98, -12.0, 0.0, 179.99] { + let (a, b) = (Coord::new(lon, lat), Coord::new(lon + dx, lat + dy)); + let exact = wgs84_distance_m(a, b); + worst = worst.max((wgs84_step_m(a, b) - exact).abs() / exact); + } + } + } + assert!(worst < 1e-6, "{worst}"); + let far = (Coord::new(10.0, 40.0), Coord::new(10.2, 40.0)); + assert_eq!(wgs84_step_m(far.0, far.1), wgs84_distance_m(far.0, far.1)); + let polar = (Coord::new(10.0, 89.5), Coord::new(10.01, 89.5)); + assert_eq!(wgs84_step_m(polar.0, polar.1), wgs84_distance_m(polar.0, polar.1)); + assert!(wgs84_step_m(Coord::new(f64::NAN, 0.0), Coord::new(0.0, 0.0)).is_nan()); + } + #[test] fn geodesic_length_matches_summed_haversine_across_the_antimeridian() { let poly = [Coord::new(0.0, 0.0), Coord::new(10.0, 20.0), Coord::new(179.0, -30.0), Coord::new(-179.0, -31.0)]; diff --git a/crates/geom/tests/geodesic_identities.rs b/crates/geom/tests/geodesic_identities.rs index bff49cd89d..75f0830849 100644 --- a/crates/geom/tests/geodesic_identities.rs +++ b/crates/geom/tests/geodesic_identities.rs @@ -8,6 +8,7 @@ //! Pull requests run a fixed seed; the nightly a new one with more cases. A failure gives its seed //! and the smallest input found. To run a seed again, or deeper: //! `PROPERTY_SEED=7 PROPERTY_CASES=50000 cargo test -p rustgis-geom --test geodesic_identities`. +#![expect(clippy::disallowed_methods, reason = "the properties hold for the sphere's measures as for the ellipsoid's")] use proptest::prelude::*; use proptest::test_runner::{Config, RngAlgorithm, TestCaseError, TestRng, TestRunner}; use rustgis_geom::{Coord, geodesic_ring_area_m2, geodesic_ring_perimeter_m, haversine_m, wgs84_distance_m, wgs84_ring_perimeter_area_m2}; diff --git a/crates/map/src/projection.rs b/crates/map/src/projection.rs index e87833a28e..a8f2f44608 100644 --- a/crates/map/src/projection.rs +++ b/crates/map/src/projection.rs @@ -474,6 +474,7 @@ impl Domain { } } + #[expect(clippy::disallowed_methods, reason = "a cap's radius is an angle on the sphere, so the sphere decides what it holds")] pub fn contains(&self, c: Coord) -> bool { match *self { Domain::World => true, @@ -741,6 +742,7 @@ impl Projector { /// bar's direction; north-south on the projection's edge) compared with the great-circle /// distance it covers, on the sphere Web Mercator's scale uses so both agree. Falls back to /// the unit size where no step stays in the projection. + #[expect(clippy::disallowed_methods, reason = "Web Mercator's scale is the sphere's: with `MERCATOR_R` this matches its scale factor")] pub fn ground_per_unit(&self, at: Coord) -> f64 { let Some(c) = self.inverse(at) else { return self.to_meter }; let step = 1000.0 / self.to_meter; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 796e8c7a27..9698047631 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3893,6 +3893,10 @@ fn upright_markers_with(map: &mut Map, view: &View, margin: f64, env: &Env) -> V let own = layer.dataset.features.get(row).and_then(|f| f.geometry.as_ref())?.extent(); Some(to_lonlat.as_ref().map_or(rustgis_geom::Extent::EMPTY, |t| t.feature_extent(&own))) }); + #[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance, tested for each feature every frame: a cut-off, not a measurement, within 0.6% of the ellipsoid's at its edge; the renderer and the map view test it alike" + )] if let (Some((centre, d)), Some(e)) = (clip, lonlat) { let near = Coord::new(centre.x.clamp(e.min_x, e.max_x), centre.y.clamp(e.min_y, e.max_y)); if e.is_empty() || rustgis_geom::haversine_m(centre, near) > d { @@ -4256,6 +4260,10 @@ impl Drop for TiltGlint { /// Leaves out of `rows` the features of `dataset` entirely beyond `d` metres of `centre` (the /// map's view distance, lon/lat): one reaching into it (its box's nearest point within the /// distance) is kept, one with no geometry isn't. +#[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance, tested for each feature every frame: a cut-off, not a measurement, within 0.6% of the ellipsoid's at its edge; the renderer and the map view test it alike" +)] pub(crate) fn within_view_distance(rows: &mut [bool], dataset: &rustgis_data::Dataset, centre: Coord, d: f64) { // Each box in longitude/latitude, from the dataset's own coordinates: none is drawn when they // can't be converted, as `Layer::projected_in` draws none. diff --git a/crates/tiles/src/routing.rs b/crates/tiles/src/routing.rs index 97d06e87f1..3930e85729 100644 --- a/crates/tiles/src/routing.rs +++ b/crates/tiles/src/routing.rs @@ -5,7 +5,7 @@ //! Answers are asked for in OSRM's form, whose steps carry a maneuver (its type and direction), //! an instruction, the street, and spoken announcements. -use rustgis_geom::{Coord, haversine_m}; +use rustgis_geom::{Coord, wgs84_step_m}; use serde_json::{Value, json}; /// The public Valhalla server (FOSSGIS), the default. @@ -237,7 +237,8 @@ fn route(r: &Value) -> Option { match line.last() { Some(last) if *last == p => {} Some(last) => { - let d = along.last().copied().unwrap_or(0.0) + haversine_m(*last, p); + // On the ellipsoid, a few operations a step: a route can hold half a million. + let d = along.last().copied().unwrap_or(0.0) + wgs84_step_m(*last, p); line.push(p); along.push(d); } @@ -525,6 +526,18 @@ mod tests { assert!(explain("http status: 400").contains("no route")); } + /// Distances along a route are on the WGS 84 ellipsoid, as the Measure tool's are, and so is + /// the route's length when the server doesn't give one. + #[test] + fn a_route_without_a_distance_measures_its_line_on_the_ellipsoid() { + let r = Router::new(None).unwrap(); + let routes = r.parse(ANSWER.replace(r#""duration":302.776,"distance":1921.553,"#, r#""duration":302.776,"#).as_bytes()).unwrap(); + let a = &routes[0]; + let ellipsoid = rustgis_geom::wgs84_length_m(&a.line); + assert!((a.distance_m / ellipsoid - 1.0).abs() < 1e-6, "{} m, {ellipsoid} m on the ellipsoid", a.distance_m); + assert_eq!(a.along.last().copied(), Some(a.distance_m)); + } + #[test] fn typed_places() { assert_eq!(parse_latlon("52.52, 13.405"), Some(Coord::new(13.405, 52.52))); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 3294b12a16..74c3666fe0 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -2380,6 +2380,10 @@ pub(crate) fn text_graphic_at(app: &RustGisApp, ctx: &egui::Context, rect: Rect, let to_lonlat = l.dataset.lonlat_conversion().ok()?; (0..l.dataset.features.len()).rev().filter(|r| drawn.get(*r) == Some(&true)).find_map(|row| { let g = l.dataset.features.get(row)?.geometry.as_ref()?; + #[expect( + clippy::disallowed_methods, + reason = "View Clipping's draw distance: picks only what the renderer draws, by its test (`within_view_distance`)" + )] if let Some((centre, d)) = clip { // No extent (an empty geometry, or one whose conversion isn't a number): nothing // of it is drawn, and clamping to its extent would panic. @@ -3827,10 +3831,12 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: // 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(); + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let measure_length = |pts: &[Coord]| { if body.is_earth() { wgs84_length_m(pts) } else { body.length(geodesic_length_m(pts)) } }; // Perimeter and area in the map body's measurement model. + #[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")] let measure_ring = |ring: &[Coord]| { if body.is_earth() { wgs84_ring_perimeter_area_m2(ring) diff --git a/crates/ui-egui/tests/integration/measurement_units.rs b/crates/ui-egui/tests/integration/measurement_units.rs index 3bee6331ac..037b51a6c3 100644 --- a/crates/ui-egui/tests/integration/measurement_units.rs +++ b/crates/ui-egui/tests/integration/measurement_units.rs @@ -393,6 +393,7 @@ fn measurement_unit_choice_is_saved_restored_and_available_to_scripts() { } #[test] +#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere")] fn moon_measure_readout_uses_its_sphere_instead_of_wgs84() { let mut h = harness(); h.state_mut().run("map.body", json!({"name": "moon", "basemap": false})).unwrap(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index bf2ff77153..bc414ba407 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -602,9 +602,8 @@ and features, before changing any fields. The attribute table's Calculate Geomet same for its chosen rows. Spatial Join's Largest overlap refuses affected selected target or join features before writing output. Ordinary polar caps and whole-world rectangles remain measurable. Measure Area explains the ambiguity and still shows the perimeter. -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). The same WGS 84 -measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the +Spatial Join's **Largest overlap** ranks overlaps by their area or length on the same ellipsoid. +The same WGS 84 measure backs the attribute table's **Calculate Geometry** (`edit.calculateGeometry`), the [expressions](expressions.md#values)' `$area`, `$perimeter` and `$length`, 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