From 868222ec7d22302dfe829fb673d9f7eddd7809f6 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 22:46:33 +0100 Subject: [PATCH 1/9] Overlays and spatial relations work in their first input's own projected system (#2032 C2e-2) --- crates/analysis/src/convert.rs | 87 +++++++++++++++++++-- crates/analysis/src/lib.rs | 77 +++++++++++++++---- crates/analysis/src/parallel.rs | 19 +++++ crates/analysis/src/tools.rs | 30 ++++++-- crates/engine/src/cmd/gp.rs | 5 +- crates/engine/src/tests/held_layers.rs | 101 +++++++++++++++++++++++++ docs/user-guide/analysis.md | 13 +++- 7 files changed, 298 insertions(+), 34 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index b718851036..8a120940ac 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -1,25 +1,85 @@ -//! Conversions between RustGIS geometry and `geo` types, in the analysis plane -//! ([`rustgis_geom::lonlat_to_plane`]): Web Mercator meters within ±85.05°, carried on to the poles -//! beyond, so polar geometry isn't clamped onto 85.05° (#1033). +//! Conversions between RustGIS geometry and `geo` types, in the plane a run works in +//! ([`Plane`]): for a run in longitude/latitude, the analysis plane +//! ([`rustgis_geom::lonlat_to_plane`]), Web Mercator meters within ±85.05°, carried on to the poles +//! beyond, so polar geometry isn't clamped onto 85.05° (#1033); for a run in its first input's own +//! projected system (#2032 C2e), that system's own coordinates, as they are. use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon}; use rustgis_data::Geometry; use rustgis_geom::{Coord, lonlat_to_plane, plane_to_lonlat}; +/// The plane a run's geometry is worked on in. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Plane { + /// Longitude/latitude, worked on in the analysis plane ([`rustgis_geom::lonlat_to_plane`]), + /// with the poles and the antimeridian where they are in it. + #[default] + Analysis, + /// A projected system's own coordinates, worked on as they are: a plane with no poles or + /// antimeridian in it (#2032 C2e). + Own, +} + +thread_local! { + static PLANE: std::cell::Cell = const { std::cell::Cell::new(Plane::Analysis) }; +} + +/// The plane of the run on this thread ([`install_plane`]): [`Plane::Analysis`] unless a run in a +/// projected system installed [`Plane::Own`]. The threads of [`crate::parallel`] take it over from +/// the thread that starts them. +pub fn plane() -> Plane { + PLANE.with(std::cell::Cell::get) +} + +/// Puts the plane back as it was when dropped. +pub struct PlaneInstalled(Plane); + +impl Drop for PlaneInstalled { + fn drop(&mut self) { + PLANE.with(|p| p.set(self.0)); + } +} + +/// Makes `plane` the plane of the work on this thread until the guard is dropped. +pub fn install_plane(plane: Plane) -> PlaneInstalled { + PlaneInstalled(PLANE.with(|p| p.replace(plane))) +} + +/// A place of a run's geometry in its plane ([`plane`]): in the analysis plane for +/// longitude/latitude, as it is in a projected system's own. +pub fn to_plane(c: Coord) -> Coord { + match plane() { + Plane::Analysis => lonlat_to_plane(c), + Plane::Own => c, + } +} + +/// A place in the run's plane back in its geometry's coordinates, undoing [`to_plane`]. +pub fn from_plane(c: Coord) -> Coord { + match plane() { + Plane::Analysis => plane_to_lonlat(c), + Plane::Own => c, + } +} + /// 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_plane(c); + let m = to_plane(c); GC { x: m.x, y: m.y } } fn back(c: &GC) -> Coord { - plane_to_lonlat(Coord::new(c.x, c.y)) + from_plane(Coord::new(c.x, c.y)) } /// The poles something spanning latitudes `south` to `north` reaches (to within -/// [`rustgis_geom::POLE_TOLERANCE`]): the North Pole, then the South Pole. +/// [`rustgis_geom::POLE_TOLERANCE`]): the North Pole, then the South Pole. None in a projected +/// system's own plane ([`Plane::Own`]), whose y is no latitude. pub(crate) fn reaches_poles(south: f64, north: f64) -> (bool, bool) { + if plane() == Plane::Own { + return (false, false); + } (north >= 90.0 - rustgis_geom::POLE_TOLERANCE, south <= -90.0 + rustgis_geom::POLE_TOLERANCE) } @@ -94,6 +154,21 @@ pub fn from_point(p: &Point) -> Geometry { mod tests { use super::*; + /// In a projected system's own plane a place is worked on as it is, and nothing reaches a + /// pole however large its y; the analysis plane is put back after. + #[test] + fn a_projected_systems_plane_is_its_own_coordinates() { + let c = Coord::new(683_944.533_251, 5_397_122.834_867); + { + let _own = install_plane(Plane::Own); + assert_eq!((to_plane(c), from_plane(c)), (c, c)); + assert_eq!(reaches_poles(-10_000_000.0, 10_000_000.0), (false, false)); + } + assert_eq!(plane(), Plane::Analysis); + assert_eq!(reaches_poles(-90.0, 90.0), (true, true)); + assert_ne!(to_plane(Coord::new(10.0, 10.0)), Coord::new(10.0, 10.0)); + } + #[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 diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index a5173ec5bb..d0e876a708 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -177,6 +177,12 @@ pub trait Inputs { /// for a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]), /// that system when it is a projected one. Its outputs are made in the same system. fn dataset(&self, layer: &str) -> Option<&Dataset>; + /// The system the run works in: the one [`Inputs::dataset`] gives layers in, and its outputs + /// are made in. Longitude/latitude unless the tool works in its first input's own projected + /// system ([`ToolSpec::works_in_own_system`]); the run's plane follows it ([`convert::Plane`]). + fn work_crs(&self) -> rustgis_data::raster::Crs { + rustgis_data::raster::Crs::LonLat + } /// A standalone table by its id: an input given as a number, which no name is taken for. fn table(&self, _id: u32) -> Option<&Dataset> { None @@ -233,7 +239,9 @@ pub struct ToolSpec { /// The built-in tools that work in their first input's own coordinate system when it is a /// projected one, rather than in longitude/latitude ([`ToolSpec::works_in_own_system`]): those /// whose results don't depend on the system's units or shape beyond what the input's own -/// coordinates give (attributes, vertices, envelopes, validity). +/// coordinates give (attributes, vertices, envelopes, validity), and the overlays and spatial +/// relations, worked on in its plane rather than the analysis plane. Areas they report are +/// still measured on the ground. const OWN_SYSTEM_TOOLS: &[&str] = &[ "summaryStatistics", "pivotTable", @@ -248,6 +256,21 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[ "merge", "checkGeometry", "repairGeometry", + // Overlays and spatial relations, worked on in the system's plane (#2032 C2e-2). + "clip", + "erase", + "intersect", + "identity", + "union", + "symmetricalDifference", + "update", + "split", + "dissolve", + "convexHull", + "featureToPoint", + "countPoints", + "selectByLocation", + "spatialJoin", ]; impl ToolSpec { @@ -255,8 +278,11 @@ impl ToolSpec { /// one: its inputs are given to it in that system ([`Inputs::dataset`]), the others converted /// into it, and its outputs are held there. Every other tool, and every external one, works in /// longitude/latitude. - pub fn works_in_own_system(&self) -> bool { - OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) + /// + /// For some it depends on `params`: Select Layer By Location and Spatial Join measure no + /// distance only without a search distance, or with a match that measures none. + pub fn works_in_own_system(&self, params: &Value) -> bool { + OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) && !tools::measures_distance(self.id, params) } /// Whether the tool reads the geometry of the layer its parameter `param` names, rather than @@ -680,16 +706,27 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result runner(spec, inputs, &p), - None => (spec.run)(inputs, &p), - }; - with_pole_loop_notes(result, spec, inputs, &p) + in_plane(inputs, || { + validate_pole_inputs(spec, inputs, &p)?; + let result = match source_of(spec) { + Some((_, runner)) => runner(spec, inputs, &p), + None => (spec.run)(inputs, &p), + }; + with_pole_loop_notes(result, spec, inputs, &p) + }) })) .unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.name))) } +/// `work` in the plane of the system `inputs` are given in ([`Inputs::work_crs`]): the analysis +/// plane for longitude/latitude, a projected system's own coordinates otherwise +/// ([`convert::Plane::Own`]). +fn in_plane(inputs: &dyn Inputs, work: impl FnOnce() -> T) -> T { + let plane = if inputs.work_crs() == rustgis_data::raster::Crs::LonLat { convert::Plane::Analysis } else { convert::Plane::Own }; + let _plane = convert::install_plane(plane); + work() +} + /// A tool's result with [`pole_loop_note`] added: to its messages, or to a refusal of polygons /// with no area (Clip's `none of the 1 feature(s) of 'loop' covers anything: a polygon with no /// area`) that names a layer with such rings, which they may be the reason for; then only those @@ -697,6 +734,9 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result, spec: &ToolSpec, inputs: &dyn Inputs, p: &Value) -> Result { match result { + // No pole in a projected system's own plane for a ring to loop around. + Ok(r) if convert::plane() == convert::Plane::Own => Ok(r), + Err(e) if convert::plane() == convert::Plane::Own => Err(e), Ok(mut r) => { r.messages.extend(pole_loop_note(spec, inputs, p, |_| true)); Ok(r) @@ -736,7 +776,6 @@ const READ_AREAS_IN_THE_PLANE: &[&str] = &[ "selectByLocation", "featureToPoint", "dissolve", - "tabulateIntersection", ]; /// Whether a tool reads every row of an input whatever is selected in it. @@ -802,6 +841,10 @@ fn pole_loop_note(spec: &ToolSpec, inputs: &dyn Inputs, p: &Value, read: impl Fn /// Validates the rows a pole-aware tool reads, on either execution path. fn validate_pole_inputs(spec: &ToolSpec, inputs: &dyn Inputs, p: &Value) -> Result<(), String> { + // A projected system's y is no latitude, and its plane has no poles. + if convert::plane() == convert::Plane::Own { + return Ok(()); + } if matches!( spec.id, "clip" @@ -878,12 +921,14 @@ pub fn run_resolved( run_under(tool.spec.name, control, || { let params = tool.resolve_params(params)?; std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - validate_pole_inputs(tool.spec, inputs, ¶ms)?; - let result = match tool.runner { - Some(runner) => runner(tool.spec, inputs, ¶ms), - None => (tool.spec.run)(inputs, ¶ms), - }; - with_pole_loop_notes(result, tool.spec, inputs, ¶ms) + in_plane(inputs, || { + validate_pole_inputs(tool.spec, inputs, ¶ms)?; + let result = match tool.runner { + Some(runner) => runner(tool.spec, inputs, ¶ms), + None => (tool.spec.run)(inputs, ¶ms), + }; + with_pole_loop_notes(result, tool.spec, inputs, ¶ms) + }) })) .unwrap_or_else(|_| Err(format!("{} failed unexpectedly", tool.spec.name))) }) diff --git a/crates/analysis/src/parallel.rs b/crates/analysis/src/parallel.rs index c826429800..a13d224851 100644 --- a/crates/analysis/src/parallel.rs +++ b/crates/analysis/src/parallel.rs @@ -106,6 +106,7 @@ pub(crate) fn for_each_row( return Ok(()); } let run = control::current(); + let plane = crate::convert::plane(); let still = rustgis_data::source::remote::current_still(); let rows = std::sync::Mutex::new(rows.enumerate()); let failed = AtomicBool::new(false); @@ -113,6 +114,7 @@ pub(crate) fn for_each_row( rustgis_data::source::remote::with_optional_still(still.clone(), || { let _stop = StopOnPanic(&failed); let _run = control::install(run.clone()); + let _plane = crate::convert::install_plane(plane); let mut s = scratch(); let mut taken = Vec::with_capacity(BATCH); while !failed.load(Ordering::Relaxed) && !control::cancelled() { @@ -209,6 +211,7 @@ fn try_map_by>( .collect(); } let run = control::current(); + let plane = crate::convert::plane(); let still = rustgis_data::source::remote::current_still(); let next = AtomicUsize::new(0); let failed = AtomicBool::new(false); @@ -216,6 +219,7 @@ fn try_map_by>( rustgis_data::source::remote::with_optional_still(still.clone(), || { let _stop = StopOnPanic(&failed); let _run = control::install(run.clone()); + let _plane = crate::convert::install_plane(plane); let mut s = scratch(); let mut made = Vec::new(); while !failed.load(Ordering::Relaxed) { @@ -500,6 +504,21 @@ mod tests { assert!(ran.load(std::sync::atomic::Ordering::Relaxed) < items.len() / 2, "{}", ran.load(std::sync::atomic::Ordering::Relaxed)); } + /// The threads a run starts work in its plane (#2032 C2e-2): a run in a projected system's own + /// plane isn't worked on in the analysis plane on the threads it hands rows or items to. + #[test] + fn the_threads_work_in_the_runs_plane() { + use crate::convert::{Plane, install_plane, plane}; + let _own = install_plane(Plane::Own); + let items: Vec = (0..5_000).collect(); + let planes = try_map_on(&items, 4, || (), |_, _, _| Ok::<_, Cancelled>(plane())).unwrap(); + assert!(planes.iter().all(|p| *p == Plane::Own)); + let seen = std::sync::Mutex::new(Vec::new()); + let mut rows = vec![0u8; 5_000]; + for_each_row(rows.chunks_mut(1), 4, || (), |_, _, _| seen.lock().unwrap().push(plane())).unwrap(); + assert!(seen.lock().unwrap().iter().all(|p| *p == Plane::Own)); + } + #[test] fn a_cancelled_run_stops_its_threads_and_counts_what_they_made() { for threads in [1, 4] { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index ac57dcc175..36da349aba 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1806,7 +1806,7 @@ fn part(g: &Geometry, mask: &MultiPolygon, inside: bool) -> Option Result { let points = |g: &Geometry| { let (mut these, mut gaps, mut poles) = (Vec::new(), 0usize, 0usize); g.for_each_vertex(|_, c| { - let m = if c.is_finite() { Some(rustgis_geom::lonlat_to_plane(c)) } else { None }; + let m = if c.is_finite() { Some(crate::convert::to_plane(c)) } else { None }; match m { Some(m) if m.x.abs() <= HULL_LIMIT_M && m.y.abs() <= HULL_LIMIT_M => { - poles += usize::from(c.y.abs() > 90.0); + // (A projected system's y is no latitude.) + poles += usize::from(crate::convert::plane() == crate::convert::Plane::Analysis && c.y.abs() > 90.0); these.push(geo::Point::new(m.x, m.y)); } _ => gaps += 1, @@ -3128,7 +3129,7 @@ fn convex_hull(inp: &dyn Inputs, p: &Json) -> Result { let first = *ring.first()?; let (a, _) = farthest(first); let (b, span) = farthest(a); - let back = |c: geo::Coord| rustgis_geom::plane_to_lonlat(Coord::new(c.x, c.y)); + let back = |c: geo::Coord| crate::convert::from_plane(Coord::new(c.x, c.y)); Some(if span > 0.0 { Geometry::Line(vec![vec![back(a), back(b)]]) } else { Geometry::Point(back(a)) }) }; let (mut flat, mut gaps, mut poles) = (0usize, 0usize, 0usize); @@ -5338,7 +5339,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result /// same transform and non-finite-coordinate filtering as [`to_geo`] followed by [`merc_extent`]. fn projected_extent(g: &Geometry) -> Extent { let mut ext = Extent::EMPTY; - g.for_each_coord(|c| ext.expand(rustgis_geom::lonlat_to_plane(c))); + g.for_each_coord(|c| ext.expand(crate::convert::to_plane(c))); ext } @@ -6731,6 +6732,17 @@ fn extent_contains(a: &Extent, b: &Extent) -> bool { !a.is_empty() && !b.is_empty() && a.min_x <= b.min_x && a.max_x >= b.max_x && a.min_y <= b.min_y && a.max_y >= b.max_y } +/// Whether a run of tool `id` with `params` measures a distance on the ground: Select Layer By +/// Location with a search distance, Spatial Join with a match that measures one. Such a run works +/// in longitude/latitude, where its distances are geodesic ([`crate::ToolSpec::works_in_own_system`]). +pub(crate) fn measures_distance(id: &str, params: &Json) -> bool { + match id { + "selectByLocation" => num(params, "distance").is_some_and(|d| d > 0.0), + "spatialJoin" => matches!(JoinMatch::parse(s(params, "match")), JoinMatch::Closest | JoinMatch::WithinDistance), + _ => false, + } +} + /// Whether a tool's parameter applies, given the values of the others (`value` gives one's /// value as text, empty when unset, which stands for its default). The Tools pane hides and leaves /// out one that doesn't. Spatial Join's search distance, units and distance field apply only to the @@ -7200,7 +7212,7 @@ impl Nearby<'_, '_> { /// geometries come with their forms in the analysis plane, where the test and the overlay work. fn shared_point(a: &Geometry, a_geo: &geo::Geometry, b: &Geometry, b_geo: &geo::Geometry) -> Option { use geo::LinesIter; - let back = |c: geo::Coord| rustgis_geom::plane_to_lonlat(Coord::new(c.x, c.y)); + let back = |c: geo::Coord| crate::convert::from_plane(Coord::new(c.x, c.y)); // Points answer with their own coordinates, not ones back from the plane. let point_on = |pts: &Geometry, other: &geo::Geometry| -> Option> { let pts: &[Coord] = match pts { @@ -7209,7 +7221,7 @@ fn shared_point(a: &Geometry, a_geo: &geo::Geometry, b: &Geometry, b_geo: & _ => return None, }; Some(pts.iter().copied().find(|c| { - let m = rustgis_geom::lonlat_to_plane(*c); + let m = crate::convert::to_plane(*c); other.intersects(&geo::Point::new(m.x, m.y)) })) }; @@ -7430,7 +7442,9 @@ fn spatial_join_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result let target_rows = rows(inp, p, "target", target); let join_rows = rows(inp, p, "join", join); - if mode == JoinMatch::LargestOverlap { + // A ring through both poles, whose area is ambiguous, is one in longitude/latitude: a projected + // system's own plane has none. + if mode == JoinMatch::LargestOverlap && crate::convert::plane() == crate::convert::Plane::Analysis { for (ds, selected) in [(target, &target_rows), (join, &join_rows)] { if let Some(message) = rustgis_data::ambiguous_area_message(selected.iter().filter_map(|&r| ds.features.get(r)?.geometry.as_ref())) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 87b2a22af3..117791dcb0 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1472,7 +1472,7 @@ fn work_system( full: &std::collections::HashMap, ) -> Crs { use rustgis_analysis::ParamKind as K; - let Some(spec) = spec.filter(|t| t.works_in_own_system()) else { return Crs::LonLat }; + let Some(spec) = spec.filter(|t| t.works_in_own_system(params)) else { return Crs::LonLat }; // The tool's first layer parameter, under its name or one of the names it also accepts // (Join Field's `input`), taken as the tool takes it: the first that isn't blank. A table // given by its number (read unconverted, [`Inputs::table`]) or by name leaves the run in @@ -1738,6 +1738,9 @@ impl Inputs for MapInputs<'_> { fn table(&self, id: u32) -> Option<&Dataset> { self.snap.tables.iter().find(|t| t.id == id).map(|t| &t.dataset) } + fn work_crs(&self) -> Crs { + self.work + } fn selection(&self, layer: &str) -> &[usize] { let Some(l) = self.snap.map.layer_by_name(layer) else { return &[] }; // Loaded selections and environment extents are already rows of the dataset returned diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 45e7be106f..8e0c02b497 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1552,3 +1552,104 @@ fn the_epsg_variants_fixture_opens_as_rustgis_own_systems() { let Some(Geometry::Point(l)) = back.features.first().and_then(|f| f.geometry.clone()) else { panic!("a point") }; assert!((l.x - 11.5).abs() < 1e-9 && (l.y - 48.7).abs() < 1e-9, "{l:?}"); } + +/// How far apart, in degrees, a place an overlay makes may be between a run in UTM and one in +/// longitude/latitude: an edge straight in UTM and the same edge straight in the analysis plane +/// (Web Mercator) part by up to about L²·tan φ / 8R at its middle, some 20 cm for the road's 3 km +/// edge here (21 cm, `Roads` clipped by `Area`, measured), so where it crosses another edge moves +/// by that much. Half a metre. Straight in UTM is the nearer of the two to the shortest way on the +/// ground. +const OVERLAID: f64 = 5e-6; + +/// Every place of `a` within `tol` degrees of one of `b`'s and the other way round, feature by +/// feature, in the same shapes. +fn assert_near(a: &[Option], b: &[Option], tol: f64, what: &str) { + assert_eq!(a.len(), b.len(), "{what}: feature count"); + for (i, (a, b)) in a.iter().zip(b).enumerate() { + assert_eq!(shape(a), shape(b), "{what}: feature {i}'s shape"); + let (mut ca, mut cb) = (Vec::new(), Vec::new()); + a.iter().for_each(|g| g.for_each_coord(|c| ca.push(c))); + b.iter().for_each(|g| g.for_each_coord(|c| cb.push(c))); + // As places, not in order: the overlay may start a ring at another of its vertices. + let near = |p: &Coord, of: &[Coord]| of.iter().any(|q| (p.x - q.x).abs() < tol && (p.y - q.y).abs() < tol); + for p in &ca { + assert!(near(p, &cb), "{what}: feature {i}: {p:?} not in {cb:?}"); + } + for q in &cb { + assert!(near(q, &ca), "{what}: feature {i}: {q:?} not in {ca:?}"); + } + } +} + +/// The overlays and spatial relations (#2032 C2e-2) work in UTM on layers held there, with no +/// pole or antimeridian check reading UTM's metres as degrees: each gives the features, attributes +/// and selections it gives for the same layers in longitude/latitude, its new layers are held in +/// UTM, and where the two planes' straight edges differ, the places they make are within +/// [`OVERLAID`] of each other. +#[test] +fn overlays_work_in_their_held_inputs_own_system() { + let mut ss = both(); + // A box across the parcels' grid, cutting some, covering some and missing others. + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut area = Dataset::new("Area", GeometryType::Polygon, fields); + let ring = [(11.502, 48.702), (11.523, 48.702), (11.523, 48.723), (11.502, 48.723), (11.502, 48.702)]; + area.push( + Some(Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]])), + vec![Cell::Text("a".into()), Cell::Int(7)], + ); + for (s, crs) in ss.iter_mut().zip([Crs::LonLat, UTM]) { + let mut a = area.clone(); + a.hold_in(crs).unwrap(); + s.map_mut().add_dataset(a); + } + let ids = |s: &Session| s.map().layers.iter().map(|l| l.id).collect::>(); + let attrs = |ds: &Dataset| { + (0..ds.features.len()).map(|r| (0..ds.fields.len()).map(|f| ds.value(r, f).to_string()).collect::>()).collect::>() + }; + for p in [ + json!({"tool": "clip", "params": {"input": "Parcels", "clip": "Area"}}), + json!({"tool": "clip", "params": {"input": "Roads", "clip": "Area"}}), + json!({"tool": "clip", "params": {"input": "Wells", "clip": "Area"}}), + json!({"tool": "erase", "params": {"input": "Parcels", "erase": "Area"}}), + json!({"tool": "intersect", "params": {"input": "Parcels", "overlay": "Area"}}), + json!({"tool": "identity", "params": {"input": "Parcels", "overlay": "Area"}}), + json!({"tool": "union", "params": {"input": "Parcels", "overlay": "Area"}}), + json!({"tool": "symmetricalDifference", "params": {"input": "Parcels", "overlay": "Area"}}), + json!({"tool": "update", "params": {"input": "Parcels", "update": "Area"}}), + json!({"tool": "split", "params": {"input": "Parcels", "split": "Area"}}), + json!({"tool": "dissolve", "params": {"input": "Parcels", "field": "name"}}), + json!({"tool": "featureToPoint", "params": {"input": "Parcels"}}), + json!({"tool": "countPoints", "params": {"polygons": "Area", "points": "Wells"}}), + json!({"tool": "spatialJoin", "params": {"target": "Parcels", "join": "Area", "match": "Intersects"}}), + ] { + let before = ids(&ss[0]); + run_both(&mut ss, "gp.run", &p); + let made: Vec = ids(&ss[0]).into_iter().filter(|id| !before.contains(id)).collect(); + assert!(!made.is_empty(), "{p}: no layer"); + for id in made { + let (a, b) = (&ss[0].map().layer(id).unwrap().dataset, &ss[1].map().layer(id).unwrap().dataset); + assert_eq!(b.coord_crs(), UTM, "{p}: {} held in", b.name); + assert!(!a.features.is_empty(), "{p}: {} is empty", a.name); + assert_eq!(attrs(a), attrs(b), "{p}: {}", a.name); + let geoms = |d: &Dataset| d.in_lonlat().unwrap().features.iter().map(|f| f.geometry.clone()).collect::>(); + assert_near(&geoms(a), &geoms(b), OVERLAID, &format!("{p}: {}", a.name)); + } + } + // The wells' hull is made of wells, exactly as held. (Which of them are its corners depends on + // the plane: the grid's middle well on two of its edges lies on the edge straight in Web + // Mercator, and just outside it in UTM, which turns and shears the grid a little.) + run_both(&mut ss, "gp.run", &json!({"tool": "convexHull", "params": {"input": "Wells", "output": "Hull"}})); + assert_eq!(ss[1].map().layer_by_name("Hull").unwrap().dataset.coord_crs(), UTM); + let wells = bits(&held_coords(&ss[1], "Wells")); + let hull = bits(&held_coords(&ss[1], "Hull")); + assert!(hull.len() >= 5 && hull.iter().all(|c| wells.contains(c)), "{hull:?}"); + // Select Layer By Location without a distance, and with one (geodesic, in longitude/latitude). + for p in [ + json!({"tool": "selectByLocation", "params": {"input": "Wells", "select": "Area"}}), + json!({"tool": "selectByLocation", "params": {"input": "Wells", "select": "Area", "distance": 0.5, "units": "Kilometers"}}), + ] { + run_both(&mut ss, "gp.run", &p); + assert_eq!(selected(&ss[0], "Wells"), selected(&ss[1], "Wells"), "{p}"); + assert!(!selected(&ss[1], "Wells").is_empty(), "{p}: nothing selected"); + } +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b45010c5ad..2191787c2c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -179,9 +179,16 @@ geodesic distances and areas, whatever system their layers are in. Some work in input's own coordinate system when it is a projected one, such as a UTM zone or a national grid: Summary Statistics, Pivot Table, Join Field, Select Layer By Attribute, Export Features, Merge, Polygon To Line, Split Line At Vertices, Feature Envelope To Polygon, Unsplit Line, Feature -Vertices To Points, Check Geometry and Repair Geometry. Their other inputs are converted into that -system for the run, and their new layers are kept in it, so the coordinates of what they copy stay -exactly as they were. If another input has a place that system can't hold, the tool works in +Vertices To Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, +Identity, Union, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry +(convex hull), Feature To Point and Summarize Within; and Select Layer By Location and +Spatial Join when they measure no distance (no search distance, a match other than Closest or +Within a distance). Their other inputs are converted into that system for the run, and their new +layers are kept in it, so the coordinates of what they copy stay exactly as they were. An overlay +there takes each edge as straight in that system, not in Web Mercator as it does in +longitude/latitude: where a long edge crosses another, the place it makes can lie a few +decimetres from where the same tool puts it in longitude/latitude (about 20 cm for a 3 km edge at +48°N), nearer the shortest way on the ground. If another input has a place that system can't hold, the tool works in longitude/latitude instead, and its message says so. A layer in longitude/latitude, Web Mercator or another geographic system is worked on in longitude/latitude, as before. From 7a11d8266651a10a27b726802625b8b85ddc4d8e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 06:24:43 +0100 Subject: [PATCH 2/9] Review: Largest overlap ranks overlaps in the system's own plane; a converted input's long edges are said; world projections stay in lon/lat; Tabulate Intersection's pole-loop notice restored; hull notices name the layer's units --- crates/analysis/src/lib.rs | 22 ++++++ crates/analysis/src/tools.rs | 35 +++++++-- crates/data/src/raster/crs.rs | 99 ++++++++++++++++++++++++++ crates/engine/src/cmd/gp.rs | 93 ++++++++++++++++++++++-- crates/engine/src/tests/held_layers.rs | 75 +++++++++++++++++++ docs/user-guide/analysis.md | 12 +++- 6 files changed, 320 insertions(+), 16 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index d0e876a708..7378d905b8 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -285,6 +285,27 @@ impl ToolSpec { OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) && !tools::measures_distance(self.id, params) } + /// Whether the tool crosses its inputs' edges with each other's (overlays and spatial + /// relations), where how an edge runs between its vertices decides the result, not only where + /// they are: a run in its first input's own system then says when another input's edges, + /// converted into it, run far from where a run in longitude/latitude takes them. + pub fn reads_edges(&self) -> bool { + matches!( + self.id, + "clip" + | "erase" + | "intersect" + | "identity" + | "union" + | "symmetricalDifference" + | "update" + | "split" + | "countPoints" + | "selectByLocation" + | "spatialJoin" + ) + } + /// Whether the tool reads the geometry of the layer its parameter `param` names, rather than /// only its attributes (Join Field's join table): one whose geometry it doesn't read needn't /// be converted into the system it works in. @@ -776,6 +797,7 @@ const READ_AREAS_IN_THE_PLANE: &[&str] = &[ "selectByLocation", "featureToPoint", "dissolve", + "tabulateIntersection", ]; /// Whether a tool reads every row of an input whatever is selected in it. diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 36da349aba..66823c425d 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1784,7 +1784,8 @@ fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { /// overlap with it, a line's stretches in it, the points in it or on its edge; outside, the rest. /// `None` when nothing is left, or only a shared edge or corner. /// -/// The mask's polygons are in the analysis plane, oriented as `union_all` leaves them. The +/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `union_all` +/// leaves them. The /// feature's may wind either way (the reference corpus has a clockwise parcel), but must not /// overlap each other: pass a feature of several polygons through [`dissolved`] first, once for all /// its masks. @@ -3204,8 +3205,12 @@ fn convex_hull(inp: &dyn Inputs, p: &Json) -> Result { out.geometry_type = first; } let out_kind = out.geometry_type; + // How far out a coordinate is too far, in the units the run works in. + let own = crate::convert::plane() == crate::convert::Plane::Own; + let too_far = + if own { format!("past {HULL_LIMIT_M:.0e} in the layer's own units") } else { "past about 9 million degrees".to_string() }; let gaps_note = (gaps > 0).then(|| { - format!("{gaps} vertex(es) passed over: a coordinate missing or infinite, or so far out that the hull can't take it (past about 9 million degrees)") + format!("{gaps} vertex(es) passed over: a coordinate missing or infinite, or so far out that the hull can't take it ({too_far})") }); let poles_note = (poles > 0).then(|| format!("{poles} vertex(es) with a latitude past a pole found (taken as that pole)")); // Nothing hulled, every feature skipped: an unusable result, so an error saying why, with the @@ -3233,8 +3238,14 @@ fn convex_hull(inp: &dyn Inputs, p: &Json) -> Result { n.saturating_sub(flat) ), }; + // On one straight line in the plane the run works in: in longitude/latitude, the map's. + let line = if own { + "points in one place or on one straight line in the layer's coordinate system".to_string() + } else { + "points in one place or on one straight line on the map (on one meridian or parallel, say; beyond 85.05° that includes points around a pole, which enclose a cap on the ground)".to_string() + }; r.messages.push(format!( - "Minimum Bounding Geometry: {flat} of {n} hulls have no area, so they are written as a point or a line: a single point, or points in one place or on one straight line on the map (on one meridian or parallel, say; beyond 85.05° that includes points around a pole, which enclose a cap on the ground); {layer}" + "Minimum Bounding Geometry: {flat} of {n} hulls have no area, so they are written as a point or a line: a single point, or {line}; {layer}" )); } Ok(r) @@ -6884,9 +6895,21 @@ fn ground_distance(t: &Geometry, t_geo: &geo::Geometry, j: &Geometry, j_geo } /// How much of a target lies in a join polygon: the ground area of a polygon's overlap, the ground -/// length of a line's. The geometries are in the analysis plane, polygons oriented for the overlay; -/// the overlap found is measured on the ground, in longitude/latitude. +/// length of a line's. The geometries are in the run's plane ([`crate::convert::plane`]), polygons +/// oriented for the overlay; in the analysis plane the overlap found is measured on the ground, in +/// longitude/latitude, and in a projected system's own plane by its area or length there, which +/// ranks overlaps of one target as the ground does. fn overlap(t_geo: &geo::Geometry, j_geo: &geo::Geometry) -> f64 { + if crate::convert::plane() == crate::convert::Plane::Own { + use geo::{Area, Euclidean, Length}; + return match (t_geo, j_geo) { + (geo::Geometry::MultiPolygon(t), geo::Geometry::MultiPolygon(j)) => t.intersection(j).unsigned_area(), + (geo::Geometry::MultiLineString(t), geo::Geometry::MultiPolygon(j)) => { + j.clip(t, false).0.iter().map(|l| Euclidean.length(l)).sum() + } + _ => 0.0, + }; + } match (t_geo, j_geo) { (geo::Geometry::MultiPolygon(t), geo::Geometry::MultiPolygon(j)) => { from_multipolygon(&t.intersection(j)).map_or(0.0, |g| crate::join::area_m2(&g)) @@ -6898,7 +6921,7 @@ fn overlap(t_geo: &geo::Geometry, j_geo: &geo::Geometry) -> f64 { } } -/// A geometry in the analysis plane, polygons oriented as the overlay needs. +/// A geometry in the run's plane ([`crate::convert::plane`]), polygons oriented as the overlay needs. fn oriented(g: &Geometry) -> geo::Geometry { match to_geo(g) { geo::Geometry::MultiPolygon(m) => geo::Geometry::MultiPolygon(m.orient(Direction::Default)), diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 772b6e408c..026e9b0e33 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -604,6 +604,91 @@ impl Crs { } } + /// Whether it is a projection of the whole world whose plane has the antimeridian as a seam + /// across it and the poles as lines (cylindrical and pseudocylindrical maps: World Mercator, + /// Plate Carrée, Robinson, Equal Earth, Mollweide and the like), by its PROJ method. A place + /// there may be a seam's width from its neighbour on the ground, so it isn't one tools work in + /// as a plane. Web Mercator is one too. + pub fn is_world_projection(self) -> bool { + const WORLD: &[&str] = &[ + "merc", + "eqc", + "cea", + "mill", + "gall", + "robin", + "eqearth", + "moll", + "eck1", + "eck2", + "eck3", + "eck4", + "eck5", + "eck6", + "wintri", + "natearth", + "natearth2", + "sinu", + "hammer", + "aitoff", + "kav5", + "kav7", + "wag1", + "wag2", + "wag3", + "wag4", + "wag5", + "wag6", + "wag7", + "loxim", + "mbtfps", + "mbt_s", + "goode", + "igh", + "vandg", + "vandg2", + "vandg3", + "vandg4", + "times", + "patterson", + "putp1", + "putp2", + "putp3", + "putp4p", + "putp5", + "putp6", + "quau", + "gins8", + "collg", + "crast", + "denoy", + "fahey", + "fouc", + "gn_sinu", + "hatano", + "larr", + "lask", + "nell", + "nell_h", + "urmfps", + "weren", + "boggs", + "bonne", + "comill", + "mbtfpq", + "fouc_s", + "wink1", + "wink2", + ]; + let proj4 = match self { + Crs::LonLat => return false, + Crs::WebMercator => return true, + Crs::Epsg(c) => epsg_proj4(c).map(|d| d.to_string()), + Crs::Custom(_) => self.custom_def().map(|d| d.proj4.clone()), + }; + proj4.is_some_and(|d| d.split_whitespace().filter_map(|t| t.strip_prefix("+proj=")).any(|m| WORLD.contains(&m))) + } + /// Whether its coordinates are geocentric (X, Y and Z from the Earth's centre), not a map's. pub fn is_geocentric(self) -> bool { match self { @@ -2464,6 +2549,20 @@ impl Transformer { mod tests { use super::*; + /// World projections, whose planes have the antimeridian as a seam, are told apart from regional + /// ones by their method. + #[test] + fn world_projections_are_told_apart() { + for c in [3395, 4087, 32662, 54030, 8857, 54009] { + let crs = Crs::parse(&format!("{c}")).or_else(|_| Crs::parse(&format!("ESRI:{c}"))).unwrap(); + assert!(crs.is_world_projection(), "{c}"); + } + for c in [32632, 2056, 25832, 3035, 31467, 3413] { + assert!(!Crs::from_epsg(c).unwrap().is_world_projection(), "{c}"); + } + assert!(Crs::WebMercator.is_world_projection() && !Crs::LonLat.is_world_projection()); + } + /// A saved code another variant stands for reads as that variant, so Web Mercator saved as /// `{"Epsg": 3857}` isn't taken for a projected system of its own. #[test] diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 117791dcb0..b5fd06ab3a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1455,12 +1455,13 @@ fn streamed_inputs( /// Whether a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]) /// works in `crs`: a projected system, whose coordinates are a plane's. Longitude/latitude, Web -/// Mercator and other geographic or geocentric systems keep the longitude/latitude path, whose -/// plane and geodesics their coordinates need. +/// Mercator and the other world projections (whose plane has the antimeridian as a seam and the +/// poles as lines, [`Crs::is_world_projection`]), and other geographic or geocentric systems, keep +/// the longitude/latitude path, whose plane and geodesics their coordinates need. /// /// [`ToolSpec::works_in_own_system`]: rustgis_analysis::ToolSpec::works_in_own_system fn works_in(crs: Crs) -> bool { - crs != Crs::LonLat && crs != Crs::WebMercator && !crs.is_geographic() && !crs.is_geocentric() + crs != Crs::LonLat && !crs.is_world_projection() && !crs.is_geographic() && !crs.is_geocentric() } /// The system a run works in: its first input's own ([`Dataset::coord_crs`]) when the tool works @@ -1536,8 +1537,9 @@ fn work_inputs( let work = work_system(map, spec, params, full); if work != Crs::LonLat { match inputs_in(map, tables, spec, params, full, work) { - Ok(converted) => { + Ok((converted, said)) => { full.extend(converted); + messages.extend(said); return Ok(work); } Err(e) => { @@ -1548,7 +1550,7 @@ fn work_inputs( } } } - let converted = inputs_in(map, tables, spec, params, full, Crs::LonLat)?; + let (converted, _) = inputs_in(map, tables, spec, params, full, Crs::LonLat)?; full.extend(converted); Ok(Crs::LonLat) } @@ -1563,8 +1565,25 @@ fn inputs_in( params: &Value, full: &std::collections::HashMap, work: Crs, -) -> Result, String> { +) -> Result<(std::collections::HashMap, Vec), String> { let mut converted = std::collections::HashMap::new(); + // What a run that crosses edges is told of an input's converted edges ([`bent_edges`]). + let mut said = Vec::new(); + let reads_edges = work != Crs::LonLat && spec.is_some_and(rustgis_analysis::ToolSpec::reads_edges); + let mut say = |original: &Dataset, c: &Dataset| -> Result<(), String> { + if reads_edges { + let (n, far) = bent_edges(original, c, work)?; + if n > 0 { + let name = spec.map_or("The tool", |t| t.name); + said.push(format!( + "{name}: {n} edge(s) of '{}', converted into {}, are taken straight there, up to {far:.0} m from where a run in longitude/latitude takes them (straight on a Web Mercator map); their vertices are where they were", + original.name, + work.label() + )); + } + } + Ok(()) + }; // Read only for its attributes in a run in its first input's system: as it is. (The first // input, if it is named there too, is in that system already.) let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; @@ -1573,6 +1592,7 @@ fn inputs_in( continue; } if let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { + say(ds, &c)?; converted.insert(key.clone(), c); } } @@ -1604,10 +1624,69 @@ fn inputs_in( .filter(|d| d.geometry_type != rustgis_data::GeometryType::None) && let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { + say(ds, &c)?; converted.insert(key, c); } } - Ok(converted) + Ok((converted, said)) +} + +/// How far, on the ground, an edge converted into another system may move from where a run in +/// longitude/latitude takes it before a run says so: a metre. +const BENT_M: f64 = 1.0; + +/// The edges of `original` that `converted`, its geometry converted vertex by vertex into `work`, +/// takes more than [`BENT_M`] from where a run in longitude/latitude takes them: straight in the +/// analysis plane there (Web Mercator, along a parallel for an edge running east), straight in +/// `work` here. Their count, and how far the farthest moved, in metres: measured at each edge's +/// middle, where the two part most, across the chord. An edge under +/// a kilometre in the analysis plane is passed over: its two readings part by under a metre short +/// of 88.9° from the equator (about L² tan φ / 8R). +fn bent_edges(original: &Dataset, converted: &Dataset, work: Crs) -> Result<(usize, f64), String> { + use rustgis_geom::{Coord, lonlat_to_plane, plane_to_lonlat}; + fn parts(g: &rustgis_data::Geometry) -> Vec<&[Coord]> { + match g { + rustgis_data::Geometry::Line(parts) => parts.iter().map(Vec::as_slice).collect(), + rustgis_data::Geometry::Polygon(polys) => polys.iter().flatten().map(Vec::as_slice).collect(), + rustgis_data::Geometry::Point(_) | rustgis_data::Geometry::MultiPoint(_) => Vec::new(), + } + } + let (to_lonlat, into, back) = (original.lonlat_conversion()?, Crs::LonLat.to(work)?, work.to(Crs::LonLat)?); + let (mut n, mut far) = (0usize, 0.0f64); + for (i, (f, c)) in original.features.iter().zip(converted.features.iter()).enumerate() { + if i.is_multiple_of(256) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + let (Some(g), Some(h)) = (&f.geometry, &c.geometry) else { continue }; + for (part, held) in parts(g).into_iter().zip(parts(h)) { + for (ab, cd) in part.windows(2).zip(held.windows(2)) { + let ([a, b], [c0, c1]) = (ab, cd) else { continue }; + let (Some(a), Some(b)) = (to_lonlat.point(*a), to_lonlat.point(*b)) else { continue }; + let (pa, pb) = (lonlat_to_plane(a), lonlat_to_plane(b)); + // (Also passed over: a length that is no number, a coordinate being missing.) + let length = (pb.x - pa.x).hypot(pb.y - pa.y); + if length.is_nan() || length < 1000.0 { + continue; + } + // The middle of the edge as a run in longitude/latitude takes it, in `work`, and how + // far it is from the chord there, across it (not along: where an edge's middle is + // along it differs between the planes, a meridian's by some 280 m over a degree). + let middle = plane_to_lonlat(Coord::new((pa.x + pb.x) / 2.0, (pa.y + pb.y) / 2.0)); + let Some(m) = into.point(middle) else { continue }; + let (dx, dy) = (c1.x - c0.x, c1.y - c0.y); + let chord = dx.hypot(dy); + let across = ((m.x - c0.x) * dy - (m.y - c0.y) * dx).abs() / chord; + // In metres: the chord's ground length over its length in `work`'s units. + let (Some(e0), Some(e1)) = (back.point(*c0), back.point(*c1)) else { continue }; + let d = across * rustgis_geom::wgs84_inverse(e0, e1).0 / chord; + if d > BENT_M { + n += 1; + far = far.max(d); + } + } + } + } + Ok((n, far)) } /// The executor's source-read choice, shared with pure permission planning. diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 8e0c02b497..6d237325df 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1601,6 +1601,11 @@ fn overlays_work_in_their_held_inputs_own_system() { let mut a = area.clone(); a.hold_in(crs).unwrap(); s.map_mut().add_dataset(a); + // The same box left in longitude/latitude in both sessions: converted into UTM for a run + // there, as another layer is. + let mut plain = area.clone(); + plain.name = "Plain_Area".into(); + s.map_mut().add_dataset(plain); } let ids = |s: &Session| s.map().layers.iter().map(|l| l.id).collect::>(); let attrs = |ds: &Dataset| { @@ -1621,9 +1626,17 @@ fn overlays_work_in_their_held_inputs_own_system() { json!({"tool": "featureToPoint", "params": {"input": "Parcels"}}), json!({"tool": "countPoints", "params": {"polygons": "Area", "points": "Wells"}}), json!({"tool": "spatialJoin", "params": {"target": "Parcels", "join": "Area", "match": "Intersects"}}), + json!({"tool": "spatialJoin", "params": {"target": "Parcels", "join": "Area", "match": "Largest overlap", "output": "Largest"}}), + json!({"tool": "spatialJoin", "params": {"target": "Wells", "join": "Area", "match": "Have their center in", "output": "Centres"}}), + json!({"tool": "clip", "params": {"input": "Parcels", "clip": "Plain_Area", "output": "Plain_Clip"}}), + json!({"tool": "union", "params": {"input": "Parcels", "overlay": "Plain_Area", "output": "Plain_Union"}}), ] { let before = ids(&ss[0]); + let marks = [ss[0].notice_mark(), ss[1].notice_mark()]; run_both(&mut ss, "gp.run", &p); + // Nothing said in one that isn't in the other: no pole or degree notice for UTM's metres. + let [said_a, said_b] = [0, 1].map(|i| ss[i].notices_since(marks[i]).iter().map(|n| n.text.clone()).collect::>()); + assert_eq!(said_a, said_b, "{p}"); let made: Vec = ids(&ss[0]).into_iter().filter(|id| !before.contains(id)).collect(); assert!(!made.is_empty(), "{p}: no layer"); for id in made { @@ -1653,3 +1666,65 @@ fn overlays_work_in_their_held_inputs_own_system() { assert!(!selected(&ss[1], "Wells").is_empty(), "{p}: nothing selected"); } } + +/// Spatial Join's Largest overlap picks the zone covering most of each parcel in UTM as in +/// longitude/latitude: the middle column of parcels (11.510° to 11.515°) lies 0.0035° in the +/// western zone and 0.0015° in the eastern one, so it joins the western one, and the outer columns +/// their own side's. Measured in UTM's plane, not by reading its metres as degrees. +#[test] +fn largest_overlap_ranks_overlaps_in_the_held_system() { + let mut ss = both(); + let fields = vec![Field::new("zone", FieldType::Text)]; + let mut zones = Dataset::new("Zones", GeometryType::Polygon, fields); + for (name, west, east) in [("west", 11.49, 11.5135), ("east", 11.5135, 11.53)] { + let ring = [(west, 48.69), (east, 48.69), (east, 48.74), (west, 48.74), (west, 48.69)]; + zones.push( + Some(Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]])), + vec![Cell::Text(name.into())], + ); + } + for (s, crs) in ss.iter_mut().zip([Crs::LonLat, UTM]) { + let mut z = zones.clone(); + z.hold_in(crs).unwrap(); + s.map_mut().add_dataset(z); + } + let p = json!({"tool": "spatialJoin", "params": {"target": "Parcels", "join": "Zones", "match": "Largest overlap", "output": "Zoned"}}); + run_both(&mut ss, "gp.run", &p); + let zone = |s: &Session| { + let ds = &s.map().layer_by_name("Zoned").unwrap().dataset; + let f = ds.field_index("join_zone").unwrap(); + (0..ds.features.len()).map(|r| ds.value(r, f).to_string()).collect::>() + }; + let want: Vec = ["west", "west", "west", "west", "west", "west", "east", "east", "east"].map(String::from).to_vec(); + assert_eq!(zone(&ss[0]), want); + assert_eq!(zone(&ss[1]), want); +} + +/// A run in UTM says when another input's long edges, converted into UTM vertex by vertex, run +/// far from where a run in longitude/latitude takes them: a degree-wide box's east-west edges +/// (74 km at 48.7°N) follow their parallels in longitude/latitude, straight in Web Mercator, and +/// are chords in UTM, which part from them by about L² tan φ / 8R, some 120 m at the middle. Its +/// north-south edges are meridians, straight in Web Mercator; 2° and 3° east of UTM zone 32N's +/// central meridian they curve in UTM, by some 8 m over the degree, so they count too. The clip +/// itself isn't changed by it here: the parcels lie far inside the box. +#[test] +fn a_converted_inputs_long_edges_are_said() { + let mut s = session(UTM); + let mut boxed = Dataset::new("Degree", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + let ring = [(11.0, 48.2), (12.0, 48.2), (12.0, 49.2), (11.0, 49.2), (11.0, 48.2)]; + boxed.push(Some(Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]])), vec![Cell::Text("d".into())]); + s.map_mut().add_dataset(boxed); + let mark = s.notice_mark(); + s.run("gp.run", &json!({"tool": "clip", "params": {"input": "Parcels", "clip": "Degree", "output": "Clipped"}})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let note = said.iter().find(|t| t.contains("edge(s) of 'Degree', converted into EPSG:32632")).unwrap_or_else(|| panic!("{said:?}")); + assert!(note.starts_with("Clip: 4 edge(s)"), "{note}"); + let far: f64 = note.split("up to ").nth(1).and_then(|t| t.split(' ').next()).and_then(|t| t.parse().ok()).unwrap(); + // 74.3 km along 48.2°N: 74_300² × tan 48.2° / (8 × 6_371_000) = 121 m. + assert!((110.0..130.0).contains(&far), "{note}"); + assert_eq!(held_coords(&s, "Clipped").len(), 9); + // Merge copies the box's vertices and crosses no edges: nothing to say. + let mark = s.notice_mark(); + s.run("gp.run", &json!({"tool": "merge", "params": {"inputs": ["Parcels", "Degree"], "attributes": false, "output": "Both"}})).unwrap(); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("taken straight there"))); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2191787c2c..01b76b563c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -186,9 +186,15 @@ Spatial Join when they measure no distance (no search distance, a match other th Within a distance). Their other inputs are converted into that system for the run, and their new layers are kept in it, so the coordinates of what they copy stay exactly as they were. An overlay there takes each edge as straight in that system, not in Web Mercator as it does in -longitude/latitude: where a long edge crosses another, the place it makes can lie a few -decimetres from where the same tool puts it in longitude/latitude (about 20 cm for a 3 km edge at -48°N), nearer the shortest way on the ground. If another input has a place that system can't hold, the tool works in +longitude/latitude, so where an edge crosses another can differ from the same tool's result in +longitude/latitude. For a layer's own edges, a few decimetres at most (about 20 cm for a 3 km +edge at 48°N). An input in another system is converted vertex by vertex, as the map draws it in +that system, and its long edges can run much farther from where they run in longitude/latitude: a +degree-wide box's east-west edges, which follow their parallels there, are chords in UTM up to +120 m away. The tool then says how many edges of which layer run more than a metre away, and how +far the farthest does. A world projection (World Mercator, Plate Carrée, Robinson, Equal Earth and +the like), whose plane has the antimeridian as a seam and the poles as lines, is worked on in +longitude/latitude, as Web Mercator is. If another input has a place that system can't hold, the tool works in longitude/latitude instead, and its message says so. A layer in longitude/latitude, Web Mercator or another geographic system is worked on in longitude/latitude, as before. From 04658a7dfedcb6ae1f10d79185fac57c24f945a2 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 07:27:12 +0100 Subject: [PATCH 3/9] Review: input preparation stops on Cancel; the environment's extent admits alike in a projected system; bent edges sampled at their quarters and on closing edges, said once; webmerc a world projection; docs --- crates/analysis/src/tools.rs | 9 +-- crates/data/src/raster/crs.rs | 3 + crates/engine/src/cmd/gp.rs | 105 ++++++++++++++++--------- crates/engine/src/tests/held_layers.rs | 57 +++++++++++++- docs/user-guide/analysis.md | 6 +- 5 files changed, 132 insertions(+), 48 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 66823c425d..f8e9ab197f 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -65,7 +65,7 @@ pub static TOOLS: &[ToolSpec] = &[ id: "featureEnvelopeToPolygon", name: "Feature Envelope To Polygon", toolbox: "Data Management › Features", - summary: "Writes one axis-aligned bounding rectangle per feature in the layer's own coordinates when it is held in a projected system other than Web Mercator, else in longitude/latitude. Zero-area envelopes are skipped.", + summary: "Writes one axis-aligned bounding rectangle per feature in the layer's own coordinates when it is held in a projected system other than Web Mercator and the other world projections (Robinson, Plate Carrée and the like), else in longitude/latitude. Zero-area envelopes are skipped.", params: &[ P { name: "input", label: "Input Features", kind: K::Layer, required: true, default: "", help: "" }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, @@ -1785,10 +1785,9 @@ fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { /// `None` when nothing is left, or only a shared edge or corner. /// /// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `union_all` -/// leaves them. The -/// feature's may wind either way (the reference corpus has a clockwise parcel), but must not -/// overlap each other: pass a feature of several polygons through [`dissolved`] first, once for all -/// its masks. +/// leaves them. The feature's may wind either way (the reference corpus has a clockwise parcel), +/// but must not overlap each other: pass a feature of several polygons through [`dissolved`] first, +/// once for all its masks. fn part(g: &Geometry, mask: &MultiPolygon, inside: bool) -> Option { match g { Geometry::Polygon(_) => { diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 026e9b0e33..329f34db68 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -612,6 +612,7 @@ impl Crs { pub fn is_world_projection(self) -> bool { const WORLD: &[&str] = &[ "merc", + "webmerc", "eqc", "cea", "mill", @@ -2561,6 +2562,8 @@ mod tests { assert!(!Crs::from_epsg(c).unwrap().is_world_projection(), "{c}"); } assert!(Crs::WebMercator.is_world_projection() && !Crs::LonLat.is_world_projection()); + // PROJ's own spelling of Web Mercator, as a file may give it. + assert!(Crs::parse("+proj=webmerc +datum=WGS84 +units=m +no_defs").unwrap().is_world_projection()); } /// A saved code another variant stands for reads as that variant, so Web Mercator saved as diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index b5fd06ab3a..709867e1ac 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -700,6 +700,10 @@ impl ToolRun { full_ids: FullIds::new(), }; } + // Reading and converting the inputs stops on Cancel too, as the tool does: the + // conversions look at the run's control (`rustgis_data::progress`), and a conversion's + // refusal isn't taken for a place that can't be held when it is a Cancel. + let _probe = rustgis_analysis::control::install_progress(Some(control.clone())); let current = continuation.clone(); let still = std::sync::Arc::new(move || current.check().is_ok()) as crate::render::rustgis_tiles::cache::Still; // A bug in reading the inputs, like one in a tool, must not take the app down. @@ -1568,18 +1572,14 @@ fn inputs_in( ) -> Result<(std::collections::HashMap, Vec), String> { let mut converted = std::collections::HashMap::new(); // What a run that crosses edges is told of an input's converted edges ([`bent_edges`]). - let mut said = Vec::new(); + // The converted inputs with edges that bend ([`bent_edges`]): name, how many, how far. + let mut bent: Vec<(String, usize, f64)> = Vec::new(); let reads_edges = work != Crs::LonLat && spec.is_some_and(rustgis_analysis::ToolSpec::reads_edges); let mut say = |original: &Dataset, c: &Dataset| -> Result<(), String> { if reads_edges { let (n, far) = bent_edges(original, c, work)?; if n > 0 { - let name = spec.map_or("The tool", |t| t.name); - said.push(format!( - "{name}: {n} edge(s) of '{}', converted into {}, are taken straight there, up to {far:.0} m from where a run in longitude/latitude takes them (straight on a Web Mercator map); their vertices are where they were", - original.name, - work.label() - )); + bent.push((original.name.clone(), n, far)); } } Ok(()) @@ -1588,7 +1588,7 @@ fn inputs_in( // input, if it is named there too, is in that system already.) let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; for (key, ds) in full { - if unread.contains(key) { + if unread.contains(&key.to_ascii_lowercase()) { continue; } if let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { @@ -1628,6 +1628,18 @@ fn inputs_in( converted.insert(key, c); } } + // One notice for them all, naming each layer. + let mut said = Vec::new(); + if !bent.is_empty() { + let name = spec.map_or("The tool", |t| t.name); + let n: usize = bent.iter().map(|(_, n, _)| n).sum(); + let far = bent.iter().map(|(.., far)| *far).fold(0.0, f64::max); + let layers = bent.iter().map(|(layer, n, _)| format!("'{layer}' ({n})")).collect::>().join(", "); + said.push(format!( + "{name}: {n} edge(s) of {layers}, converted into {}, are taken straight there, up to {far:.0} m from where a run in longitude/latitude takes them (straight on a Web Mercator map); their vertices are where they were", + work.label() + )); + } Ok((converted, said)) } @@ -1638,47 +1650,57 @@ const BENT_M: f64 = 1.0; /// The edges of `original` that `converted`, its geometry converted vertex by vertex into `work`, /// takes more than [`BENT_M`] from where a run in longitude/latitude takes them: straight in the /// analysis plane there (Web Mercator, along a parallel for an edge running east), straight in -/// `work` here. Their count, and how far the farthest moved, in metres: measured at each edge's -/// middle, where the two part most, across the chord. An edge under -/// a kilometre in the analysis plane is passed over: its two readings part by under a metre short -/// of 88.9° from the equator (about L² tan φ / 8R). -fn bent_edges(original: &Dataset, converted: &Dataset, work: Crs) -> Result<(usize, f64), String> { +/// `work` here. A polygon ring's closing edge counts too, when the ring doesn't repeat its first +/// vertex. Their count, and how far the farthest moved, in metres: measured across the chord at a +/// quarter, half and three quarters of the edge (an edge across a transverse Mercator's central +/// meridian bends both ways, its middle staying on the chord), in ground metres whatever `work`'s +/// units. An edge under a kilometre in the analysis plane is skipped: its two readings part by +/// under a metre short of 88.9° from the equator (about L² tan φ / 8R). +pub(crate) fn bent_edges(original: &Dataset, converted: &Dataset, work: Crs) -> Result<(usize, f64), String> { use rustgis_geom::{Coord, lonlat_to_plane, plane_to_lonlat}; - fn parts(g: &rustgis_data::Geometry) -> Vec<&[Coord]> { + /// Its parts' vertices, each with whether it is a polygon's ring, whose closing edge counts. + fn parts(g: &rustgis_data::Geometry) -> Vec<(&[Coord], bool)> { match g { - rustgis_data::Geometry::Line(parts) => parts.iter().map(Vec::as_slice).collect(), - rustgis_data::Geometry::Polygon(polys) => polys.iter().flatten().map(Vec::as_slice).collect(), + rustgis_data::Geometry::Line(parts) => parts.iter().map(|p| (p.as_slice(), false)).collect(), + rustgis_data::Geometry::Polygon(polys) => polys.iter().flatten().map(|r| (r.as_slice(), true)).collect(), rustgis_data::Geometry::Point(_) | rustgis_data::Geometry::MultiPoint(_) => Vec::new(), } } + /// The edges of a part: each pair of neighbours, and a ring's closing pair when it isn't + /// closed already. + fn edges(part: &[Coord], ring: bool) -> impl Iterator + '_ { + let closing = ring.then(|| part.first().zip(part.last())).flatten().filter(|(a, b)| a != b).map(|(a, b)| (*b, *a)); + part.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).chain(closing) + } let (to_lonlat, into, back) = (original.lonlat_conversion()?, Crs::LonLat.to(work)?, work.to(Crs::LonLat)?); let (mut n, mut far) = (0usize, 0.0f64); - for (i, (f, c)) in original.features.iter().zip(converted.features.iter()).enumerate() { + for (i, (f, c)) in original.features.rows().zip(converted.features.rows()).enumerate() { if i.is_multiple_of(256) { rustgis_data::progress::check().map_err(|e| e.to_string())?; } - let (Some(g), Some(h)) = (&f.geometry, &c.geometry) else { continue }; - for (part, held) in parts(g).into_iter().zip(parts(h)) { - for (ab, cd) in part.windows(2).zip(held.windows(2)) { - let ([a, b], [c0, c1]) = (ab, cd) else { continue }; - let (Some(a), Some(b)) = (to_lonlat.point(*a), to_lonlat.point(*b)) else { continue }; + let (Some(g), Some(h)) = (f.geometry(), c.geometry()) else { continue }; + for ((part, ring), (held, _)) in parts(g).into_iter().zip(parts(h)) { + for ((a, b), (c0, c1)) in edges(part, ring).zip(edges(held, ring)) { + let (Some(a), Some(b)) = (to_lonlat.point(a), to_lonlat.point(b)) else { continue }; let (pa, pb) = (lonlat_to_plane(a), lonlat_to_plane(b)); - // (Also passed over: a length that is no number, a coordinate being missing.) + // (Also skipped: a length that is no number, a coordinate being missing.) let length = (pb.x - pa.x).hypot(pb.y - pa.y); if length.is_nan() || length < 1000.0 { continue; } - // The middle of the edge as a run in longitude/latitude takes it, in `work`, and how - // far it is from the chord there, across it (not along: where an edge's middle is - // along it differs between the planes, a meridian's by some 280 m over a degree). - let middle = plane_to_lonlat(Coord::new((pa.x + pb.x) / 2.0, (pa.y + pb.y) / 2.0)); - let Some(m) = into.point(middle) else { continue }; let (dx, dy) = (c1.x - c0.x, c1.y - c0.y); let chord = dx.hypot(dy); - let across = ((m.x - c0.x) * dy - (m.y - c0.y) * dx).abs() / chord; // In metres: the chord's ground length over its length in `work`'s units. - let (Some(e0), Some(e1)) = (back.point(*c0), back.point(*c1)) else { continue }; - let d = across * rustgis_geom::wgs84_inverse(e0, e1).0 / chord; + let (Some(e0), Some(e1)) = (back.point(c0), back.point(c1)) else { continue }; + let per_unit = rustgis_geom::wgs84_inverse(e0, e1).0 / chord; + // How far the edge as a run in longitude/latitude takes it lies across the chord + // (not along it: where a point is along an edge differs between the planes, a + // meridian's middle by some 280 m over a degree). + let across = |t: f64| { + let on = plane_to_lonlat(Coord::new(pa.x + t * (pb.x - pa.x), pa.y + t * (pb.y - pa.y))); + into.point(on).map(|m| ((m.x - c0.x) * dy - (m.y - c0.y) * dx).abs() / chord * per_unit) + }; + let d = [0.25, 0.5, 0.75].into_iter().filter_map(across).fold(0.0, f64::max); if d > BENT_M { n += 1; far = far.max(d); @@ -1762,15 +1784,20 @@ fn env_rows( .filter(|l| !l.is_raster() && l.selection.is_empty()) .map(|l| { let ds = full.get(&l.name.to_ascii_lowercase()).unwrap_or(&l.dataset); - // The extent in the layer's own coordinates, as its features' boxes are. + // The extent in the layer's own coordinates, as its features' boxes are: a box there + // around the longitude/latitude one, which can reach past its edges, so a feature it + // reaches is admitted only when its box in longitude/latitude meets the extent, as in a + // run in longitude/latitude. let own = ds.extent_from_lonlat(&e); - let rows: Vec = ds - .features - .iter() - .enumerate() - .filter(|(_, f)| f.geometry.as_ref().is_some_and(|g| g.extent().intersects(&own))) - .map(|(i, _)| i) - .collect(); + let to_lonlat = ds.lonlat_conversion().ok(); + let meets = |g: &rustgis_data::Geometry| { + g.extent().intersects(&own) + && to_lonlat.as_ref().is_some_and(|to| { + to.is_identity() || Dataset::geometry_to_lonlat_by(to, g).is_ok_and(|g| g.extent().intersects(&e)) + }) + }; + let rows: Vec = + ds.features.rows().enumerate().filter(|(_, r)| r.geometry().is_some_and(meets)).map(|(i, _)| i).collect(); (l.name.to_ascii_lowercase(), rows) }) .collect() diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 6d237325df..a8e4305790 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1717,7 +1717,7 @@ fn a_converted_inputs_long_edges_are_said() { let mark = s.notice_mark(); s.run("gp.run", &json!({"tool": "clip", "params": {"input": "Parcels", "clip": "Degree", "output": "Clipped"}})).unwrap(); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - let note = said.iter().find(|t| t.contains("edge(s) of 'Degree', converted into EPSG:32632")).unwrap_or_else(|| panic!("{said:?}")); + let note = said.iter().find(|t| t.contains("edge(s) of 'Degree' (4), converted into EPSG:32632")).unwrap_or_else(|| panic!("{said:?}")); assert!(note.starts_with("Clip: 4 edge(s)"), "{note}"); let far: f64 = note.split("up to ").nth(1).and_then(|t| t.split(' ').next()).and_then(|t| t.parse().ok()).unwrap(); // 74.3 km along 48.2°N: 74_300² × tan 48.2° / (8 × 6_371_000) = 121 m. @@ -1728,3 +1728,58 @@ fn a_converted_inputs_long_edges_are_said() { s.run("gp.run", &json!({"tool": "merge", "params": {"inputs": ["Parcels", "Degree"], "attributes": false, "output": "Both"}})).unwrap(); assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("taken straight there"))); } + +/// The environment's extent admits the features of a layer held in UTM that it admits of the same +/// layer in longitude/latitude: the extent's box in UTM, turned some 1.9° with UTM's grid, reaches +/// past the middle of each of its edges by some 25 m, where a point 5 m out isn't admitted. +#[test] +fn the_environments_extent_admits_alike_in_the_held_system() { + let mut ss = both(); + let mut near = Dataset::new("Near", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + let (west, south, east, north) = (11.505, 48.705, 11.525, 48.725); + // 5 m out: 0.000_045° of latitude, 0.000_068° of longitude at 48.7°. + let (mid_x, mid_y, out_y, out_x) = (11.515, 48.715, 0.000_045, 0.000_068); + let outside = [(mid_x, north + out_y), (mid_x, south - out_y), (east + out_x, mid_y), (west - out_x, mid_y)]; + for (x, y) in outside.into_iter().chain([(mid_x, mid_y)]) { + near.push(Some(Geometry::Point(Coord::new(x, y))), vec![Cell::Text(format!("{x},{y}"))]); + } + for (s, crs) in ss.iter_mut().zip([Crs::LonLat, UTM]) { + let mut d = near.clone(); + d.hold_in(crs).unwrap(); + s.map_mut().add_dataset(d); + s.project.gp_env.extent = Some(rustgis_geom::Extent { min_x: west, min_y: south, max_x: east, max_y: north }); + } + run_both(&mut ss, "gp.run", &json!({"tool": "featureToPoint", "params": {"input": "Near", "output": "Inside"}})); + let names = |s: &Session| { + let ds = &s.map().layer_by_name("Inside").unwrap().dataset; + (0..ds.features.len()).map(|r| ds.value(r, 0).to_string()).collect::>() + }; + assert_eq!(names(&ss[0]), vec!["11.515,48.715".to_string()]); + assert_eq!(names(&ss[1]), names(&ss[0])); +} + +/// How far a converted edge runs from where a run in longitude/latitude takes it is looked for +/// beyond its middle, and on a ring's closing edge when the ring doesn't repeat its first vertex. +#[test] +fn bent_edges_are_found_beyond_their_middle_and_on_closing_edges() { + let bent = |g: Geometry| { + let mut ds = Dataset::new("Edges", g.kind(), Vec::new()); + ds.push(Some(g), Vec::new()); + let c = ds.in_crs(UTM).unwrap().into_owned(); + crate::cmd::gp::bent_edges(&ds, &c, UTM).unwrap() + }; + // Across UTM zone 32N's central meridian (9°E) at the equator, point-symmetric about where they + // cross: its middle, (9°E, 0°), is on the chord and on the edge in Web Mercator alike, and it + // bends away to either side, by metres at its quarters (CodeRabbit's example, on #2659). + let (n, far) = bent(Geometry::Line(vec![vec![Coord::new(8.0, -1.0), Coord::new(10.0, 1.0)]])); + assert_eq!(n, 1); + assert!(far > 1.0, "{far}"); + // The degree-wide box of `a_converted_inputs_long_edges_are_said`, closed and open: its four edges + // either way. + let ring = [(11.0, 48.2), (12.0, 48.2), (12.0, 49.2), (11.0, 49.2)].map(|(x, y)| Coord::new(x, y)).to_vec(); + let mut closed = ring.clone(); + closed.push(ring[0]); + let open = bent(Geometry::Polygon(vec![vec![ring]])); + assert_eq!(open.0, 4); + assert_eq!(bent(Geometry::Polygon(vec![vec![closed]])).0, 4); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 01b76b563c..a08e727a11 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -187,8 +187,8 @@ Within a distance). Their other inputs are converted into that system for the ru layers are kept in it, so the coordinates of what they copy stay exactly as they were. An overlay there takes each edge as straight in that system, not in Web Mercator as it does in longitude/latitude, so where an edge crosses another can differ from the same tool's result in -longitude/latitude. For a layer's own edges, a few decimetres at most (about 20 cm for a 3 km -edge at 48°N). An input in another system is converted vertex by vertex, as the map draws it in +longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: some 20 cm for +a 3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another system is converted vertex by vertex, as the map draws it in that system, and its long edges can run much farther from where they run in longitude/latitude: a degree-wide box's east-west edges, which follow their parallels there, are chords in UTM up to 120 m away. The tool then says how many edges of which layer run more than a metre away, and how @@ -1241,7 +1241,7 @@ CRS metadata. Coordinates are used directly, without projection or snapping. memory returns an error. - **Feature Envelope To Polygon** (`featureEnvelopeToPolygon`) writes one axis-aligned rectangle around all coordinates of each feature, along the axes of the layer's own system when it is a - projected one, and of longitude/latitude otherwise. Point features and + projected one other than a world projection (see above), and of longitude/latitude otherwise. Point features and horizontal or vertical lines have zero-area envelopes and are skipped with a count. Longitude bounds are literal, including for features spanning the antimeridian. - **Unsplit Line** (`unsplitLine`) joins line parts at exactly equal endpoints where precisely From 15bea9bc914a2a71cc3041c8b20a7199822dd2c7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 07:40:23 +0100 Subject: [PATCH 4/9] Review: a Cancel while the inputs are read names the tool; a feature the environment's extent can't read in lon/lat is admitted by its box, as before; ends that meet give no bend --- crates/engine/src/cmd/gp.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 709867e1ac..fca75c4ad1 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -711,6 +711,11 @@ impl ToolRun { crate::render::rustgis_tiles::cache::with_still(still, || { let inputs = match inputs_of(snap, Some(spec), ¶ms) { Ok(inputs) => inputs, + // A Cancel while the inputs are read names the tool, as one while it runs does. + Err(_) if control.is_cancelled() => { + let result = Err(format!("{name} was cancelled while it read its inputs")); + return ToolDone { inputs: Vec::new(), result, full_ids: FullIds::new() }; + } Err(e) => return ToolDone { inputs: Vec::new(), result: Err(e), full_ids: FullIds::new() }, }; let mut result = pin.run(&inputs, ¶ms, control, &|| continuation.check()); @@ -1693,6 +1698,10 @@ pub(crate) fn bent_edges(original: &Dataset, converted: &Dataset, work: Crs) -> // In metres: the chord's ground length over its length in `work`'s units. let (Some(e0), Some(e1)) = (back.point(c0), back.point(c1)) else { continue }; let per_unit = rustgis_geom::wgs84_inverse(e0, e1).0 / chord; + // (Ends that meet in `work` give no chord to measure across.) + if !per_unit.is_finite() { + continue; + } // How far the edge as a run in longitude/latitude takes it lies across the chord // (not along it: where a point is along an edge differs between the planes, a // meridian's middle by some 280 m over a degree). @@ -1793,7 +1802,9 @@ fn env_rows( let meets = |g: &rustgis_data::Geometry| { g.extent().intersects(&own) && to_lonlat.as_ref().is_some_and(|to| { - to.is_identity() || Dataset::geometry_to_lonlat_by(to, g).is_ok_and(|g| g.extent().intersects(&e)) + // (A feature with a place that can't be read in longitude/latitude is + // admitted by its box alone, as before.) + to.is_identity() || Dataset::geometry_to_lonlat_by(to, g).map_or(true, |g| g.extent().intersects(&e)) }) }; let rows: Vec = From 37041f9c188cf120b208d3502ab85ba5333e67e8 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 08:11:01 +0100 Subject: [PATCH 5/9] Review: a numbered table is converted into the run's system as a named one is; the environment's extent admits by the lon/lat box alone; envelope doc --- crates/analysis/src/tools.rs | 5 +- crates/engine/src/cmd/gp.rs | 67 ++++++++++++++++++++------ crates/engine/src/tests/held_layers.rs | 57 ++++++++++++++++++++++ 3 files changed, 112 insertions(+), 17 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index f8e9ab197f..8619c60f37 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -8204,8 +8204,9 @@ fn split_line_at_vertices(inp: &dyn Inputs, p: &Json) -> Result Result { geometry::convert(inp, p, geometry::Conversion::FeatureEnvelopeToPolygon) } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index fca75c4ad1..f55dc11192 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -509,7 +509,8 @@ pub(crate) struct StartedRun { type FullIds = std::collections::HashMap>; fn full_ids(full: &std::collections::HashMap) -> FullIds { - full.iter().map(|(k, d)| (k.clone(), d.features.iter().map(|f| f.id).collect())).collect() + // (Not the standalone tables converted for a run, [`table_key`]: no layer is updated from them.) + full.iter().filter(|(k, _)| !k.starts_with('\0')).map(|(k, d)| (k.clone(), d.features.iter().map(|f| f.id).collect())).collect() } /// Checks and carries the admitted owner through every synchronous input/preparation request. @@ -1534,7 +1535,8 @@ fn attributes_only(spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> /// The layers a tool reads, in the system it works in ([`work_system`], [`Inputs::dataset`]): /// its first input's own for a tool that works in it, every other input converted into it; else /// longitude/latitude. An input with a place that system can't hold has the run work in -/// longitude/latitude instead, and a message says so. Returns the system. +/// longitude/latitude instead, and a message says so (the conversions made for the first attempt +/// are dropped then, and the inputs read again in longitude/latitude). Returns the system. fn work_inputs( map: &rustgis_map::Map, tables: &[crate::project::Table], @@ -1633,6 +1635,29 @@ fn inputs_in( converted.insert(key, c); } } + // A standalone table given by its number ([`Inputs::table`]), as one given by name. + fn numbers(v: &Value, out: &mut Vec) { + match v { + Value::Number(n) => out.extend(n.as_u64()), + Value::Array(a) => a.iter().for_each(|x| numbers(x, out)), + Value::Object(o) => o.values().for_each(|x| numbers(x, out)), + _ => {} + } + } + let mut ids = Vec::new(); + match params { + Value::Object(o) => o.iter().filter(|(k, _)| k.as_str() != "output").for_each(|(_, v)| numbers(v, &mut ids)), + other => numbers(other, &mut ids), + } + for t in tables.iter().filter(|t| ids.contains(&u64::from(t.id))) { + if t.dataset.geometry_type == rustgis_data::GeometryType::None { + continue; + } + if let std::borrow::Cow::Owned(c) = t.dataset.in_crs(work)? { + say(&t.dataset, &c)?; + converted.insert(table_key(t.id), c); + } + } // One notice for them all, naming each layer. let mut said = Vec::new(); if !bent.is_empty() { @@ -1648,6 +1673,12 @@ fn inputs_in( Ok((converted, said)) } +/// The key a standalone table given by its number is converted under among a run's inputs +/// ([`inputs_in`]): one no layer's name can be. +fn table_key(id: u32) -> String { + format!("\u{0}table {id}") +} + /// How far, on the ground, an edge converted into another system may move from where a run in /// longitude/latitude takes it before a run says so: a metre. const BENT_M: f64 = 1.0; @@ -1793,19 +1824,19 @@ fn env_rows( .filter(|l| !l.is_raster() && l.selection.is_empty()) .map(|l| { let ds = full.get(&l.name.to_ascii_lowercase()).unwrap_or(&l.dataset); - // The extent in the layer's own coordinates, as its features' boxes are: a box there - // around the longitude/latitude one, which can reach past its edges, so a feature it - // reaches is admitted only when its box in longitude/latitude meets the extent, as in a - // run in longitude/latitude. - let own = ds.extent_from_lonlat(&e); + // A feature is admitted when its box in longitude/latitude meets the extent, as in a + // run in longitude/latitude (which reads the whole layer converted too): no box in the + // layer's own system tests that, a box there around the extent missing a feature whose + // box in longitude/latitude meets it. One with a place that can't be read in + // longitude/latitude, or a layer that can't be, is admitted by its own box meeting the + // extent's there, as before. + let own = std::cell::OnceCell::new(); + let by_own = |g: &rustgis_data::Geometry| g.extent().intersects(own.get_or_init(|| ds.extent_from_lonlat(&e))); let to_lonlat = ds.lonlat_conversion().ok(); - let meets = |g: &rustgis_data::Geometry| { - g.extent().intersects(&own) - && to_lonlat.as_ref().is_some_and(|to| { - // (A feature with a place that can't be read in longitude/latitude is - // admitted by its box alone, as before.) - to.is_identity() || Dataset::geometry_to_lonlat_by(to, g).map_or(true, |g| g.extent().intersects(&e)) - }) + let meets = |g: &rustgis_data::Geometry| match &to_lonlat { + Some(to) if to.is_identity() => g.extent().intersects(&e), + Some(to) => Dataset::geometry_to_lonlat_by(to, g).map_or_else(|_| by_own(g), |g| g.extent().intersects(&e)), + None => by_own(g), }; let rows: Vec = ds.features.rows().enumerate().filter(|(_, r)| r.geometry().is_some_and(meets)).map(|(i, _)| i).collect(); @@ -1853,7 +1884,13 @@ impl Inputs for MapInputs<'_> { }) } fn table(&self, id: u32) -> Option<&Dataset> { - self.snap.tables.iter().find(|t| t.id == id).map(|t| &t.dataset) + // Converted before the run when the tool's parameters give its number ([`inputs_in`]); + // else read as it is only in the system the tool works in, as a layer is. + self.loaded.get(&table_key(id)).or_else(|| { + self.snap.tables.iter().find(|t| t.id == id).map(|t| &t.dataset).filter(|d| { + d.geometry_type == rustgis_data::GeometryType::None || d.coord_crs().to(self.work).is_ok_and(|to| to.is_identity()) + }) + }) } fn work_crs(&self) -> Crs { self.work diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index a8e4305790..3d66823f08 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1783,3 +1783,60 @@ fn bent_edges_are_found_beyond_their_middle_and_on_closing_edges() { assert_eq!(open.0, 4); assert_eq!(bent(Geometry::Polygon(vec![vec![closed]])).0, 4); } + +/// A line held in UTM along a northing is tilted in longitude/latitude: an environment's extent +/// near a corner of its box there, away from the line, admits it, in a run in longitude/latitude +/// and in the held system alike (CodeRabbit, on #2659). +#[test] +fn the_environments_extent_admits_a_tilted_line_by_its_box_in_longitude_latitude() { + let mut ss = both(); + let back = UTM.to(Crs::LonLat).unwrap(); + // From the central meridian 200 km east at northing 5,400 km (48.7°N): its east end some + // 3.6 km south of its west end's latitude. + let (w, e) = (back.point(Coord::new(500_000.0, 5_400_000.0)).unwrap(), back.point(Coord::new(700_000.0, 5_400_000.0)).unwrap()); + assert!((w.y - e.y).abs() > 0.02, "{w:?} {e:?}"); + let mut line = Dataset::new("Tilted", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + line.push(Some(Geometry::Line(vec![vec![w, e]])), vec![Cell::Text("tilted".into())]); + // A small box at the corner of the line's box at its west end's longitude and east end's + // latitude, inside it: kilometres from the line. + let (x, y) = (w.x + 0.002, e.y + 0.002 * (w.y - e.y).signum()); + for (s, crs) in ss.iter_mut().zip([Crs::LonLat, UTM]) { + let mut d = line.clone(); + d.hold_in(crs).unwrap(); + s.map_mut().add_dataset(d); + s.project.gp_env.extent = Some(rustgis_geom::Extent { min_x: x - 0.001, min_y: y - 0.001, max_x: x + 0.001, max_y: y + 0.001 }); + } + run_both(&mut ss, "gp.run", &json!({"tool": "featureToPoint", "params": {"input": "Tilted", "output": "Admitted"}})); + for s in &ss { + assert_eq!(s.map().layer_by_name("Admitted").unwrap().dataset.features.len(), 1); + } +} + +/// A standalone table with geometry given by its number is converted into the system the run +/// works in, as one given by name is (claude-review, on #2659). +#[test] +fn a_numbered_table_is_converted_into_the_held_system() { + let mut ss = both(); + let mut wells = Dataset::new("Wells", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for (x, y) in [(11.51, 48.71), (11.6, 48.8)] { + wells.push(Some(Geometry::Point(Coord::new(x, y))), vec![Cell::Text(format!("{x},{y}"))]); + } + let mut area = Dataset::new("Area", GeometryType::Polygon, Vec::new()); + let ring = [(11.5, 48.7), (11.52, 48.7), (11.52, 48.72), (11.5, 48.72), (11.5, 48.7)]; + area.push(Some(Geometry::Polygon(vec![vec![ring.iter().map(|&(x, y)| Coord::new(x, y)).collect()]])), Vec::new()); + let mut ids = Vec::new(); + for (s, crs) in ss.iter_mut().zip([Crs::LonLat, UTM]) { + let mut d = wells.clone(); + d.hold_in(crs).unwrap(); + s.map_mut().add_dataset(d); + // In longitude/latitude in both sessions. + ids.push(s.project.add_table(area.clone())); + } + assert_eq!(ids[0], ids[1]); + run_both(&mut ss, "gp.run", &json!({"tool": "clip", "params": {"input": "Wells", "clip": ids[0], "output": "Inside"}})); + for s in &ss { + let ds = &s.map().layer_by_name("Inside").unwrap().dataset; + assert_eq!(ds.coord_crs(), if std::ptr::eq(s, &ss[0]) { Crs::LonLat } else { UTM }); + assert_eq!((0..ds.features.len()).map(|r| ds.value(r, 0).to_string()).collect::>(), vec!["11.51,48.71"]); + } +} From f27801b0f4dcc67f6e8626879170bd67d7c4b41d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 08:16:55 +0100 Subject: [PATCH 6/9] Review: table numbers are read only under layer parameters whose geometry the tool reads; a name can't reach a converted table; a layer the extent can't read in lon/lat admits none, as before --- crates/engine/src/cmd/gp.rs | 40 +++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index f55dc11192..b647730277 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1635,19 +1635,24 @@ fn inputs_in( converted.insert(key, c); } } - // A standalone table given by its number ([`Inputs::table`]), as one given by name. - fn numbers(v: &Value, out: &mut Vec) { - match v { - Value::Number(n) => out.extend(n.as_u64()), - Value::Array(a) => a.iter().for_each(|x| numbers(x, out)), - Value::Object(o) => o.values().for_each(|x| numbers(x, out)), - _ => {} - } - } + // A standalone table given by its number ([`Inputs::table`]), as one given by name: under a + // layer parameter (or a name it also accepts), the only place a number is a table's; not one + // the tool reads only the attributes of, in a run in its first input's system. let mut ids = Vec::new(); - match params { - Value::Object(o) => o.iter().filter(|(k, _)| k.as_str() != "output").for_each(|(_, v)| numbers(v, &mut ids)), - other => numbers(other, &mut ids), + if let Some(spec) = spec { + use rustgis_analysis::ParamKind as K; + let layers = spec.params.iter().filter(|p| { + matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers) + && (work == Crs::LonLat || spec.reads_geometry_of(p.name)) + }); + for p in layers { + let aliases = rustgis_analysis::param_aliases(spec, p.name); + let keys: &[&str] = if aliases.is_empty() { std::slice::from_ref(&p.name) } else { aliases }; + for v in keys.iter().filter_map(|k| params.get(*k)) { + let one = std::slice::from_ref(v); + ids.extend(v.as_array().map_or(one, Vec::as_slice).iter().filter_map(Value::as_u64)); + } + } } for t in tables.iter().filter(|t| ids.contains(&u64::from(t.id))) { if t.dataset.geometry_type == rustgis_data::GeometryType::None { @@ -1828,15 +1833,16 @@ fn env_rows( // run in longitude/latitude (which reads the whole layer converted too): no box in the // layer's own system tests that, a box there around the extent missing a feature whose // box in longitude/latitude meets it. One with a place that can't be read in - // longitude/latitude, or a layer that can't be, is admitted by its own box meeting the - // extent's there, as before. + // longitude/latitude is admitted by its own box meeting the extent's there, as before; + // a layer that can't be read in longitude/latitude at all admits none, as before (and + // the run says none is inside). let own = std::cell::OnceCell::new(); let by_own = |g: &rustgis_data::Geometry| g.extent().intersects(own.get_or_init(|| ds.extent_from_lonlat(&e))); let to_lonlat = ds.lonlat_conversion().ok(); let meets = |g: &rustgis_data::Geometry| match &to_lonlat { Some(to) if to.is_identity() => g.extent().intersects(&e), Some(to) => Dataset::geometry_to_lonlat_by(to, g).map_or_else(|_| by_own(g), |g| g.extent().intersects(&e)), - None => by_own(g), + None => false, }; let rows: Vec = ds.features.rows().enumerate().filter(|(_, r)| r.geometry().is_some_and(meets)).map(|(i, _)| i).collect(); @@ -1865,6 +1871,10 @@ impl Inputs for MapInputs<'_> { crate::render::raster_export::export(raster, min_zoom, max_zoom, opacity) } fn dataset(&self, layer: &str) -> Option<&Dataset> { + // (A standalone table converted for the run is had by its number, [`table_key`].) + if layer.starts_with('\0') { + return None; + } self.loaded .get(layer) .or_else(|| self.loaded.get(&layer.to_ascii_lowercase())) From ce6f220f1d8a327ec4f122b9882c830b5b610e23 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 08:42:47 +0100 Subject: [PATCH 7/9] Review: a numbered table read only for its attributes is read as it is; the environment's extent looks for Cancel; a quoted world projection's method is read; test comments --- crates/data/src/raster/crs.rs | 6 ++++- crates/engine/src/cmd/gp.rs | 34 +++++++++++++++++--------- crates/engine/src/tests/held_layers.rs | 18 +++++++++++--- 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 329f34db68..86759fa334 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -687,7 +687,10 @@ impl Crs { Crs::Epsg(c) => epsg_proj4(c).map(|d| d.to_string()), Crs::Custom(_) => self.custom_def().map(|d| d.proj4.clone()), }; - proj4.is_some_and(|d| d.split_whitespace().filter_map(|t| t.strip_prefix("+proj=")).any(|m| WORLD.contains(&m))) + // (A method may be written quoted, as PROJ reads it.) + proj4.is_some_and(|d| { + d.split_whitespace().filter_map(|t| t.strip_prefix("+proj=")).map(|m| m.trim_matches('"')).any(|m| WORLD.contains(&m)) + }) } /// Whether its coordinates are geocentric (X, Y and Z from the Earth's centre), not a map's. @@ -2564,6 +2567,7 @@ mod tests { assert!(Crs::WebMercator.is_world_projection() && !Crs::LonLat.is_world_projection()); // PROJ's own spelling of Web Mercator, as a file may give it. assert!(Crs::parse("+proj=webmerc +datum=WGS84 +units=m +no_defs").unwrap().is_world_projection()); + assert!(Crs::parse("+proj=\"eqc\" +datum=WGS84 +units=m").unwrap().is_world_projection()); } /// A saved code another variant stands for reads as that variant, so Web Mercator saved as diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index b647730277..041a1dcba4 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1527,8 +1527,9 @@ fn attributes_only(spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> let aliases = rustgis_analysis::param_aliases(spec, p.name); if aliases.is_empty() { vec![p.name] } else { aliases.to_vec() } }) - .filter_map(|k| params.get(k).and_then(Value::as_str)) - .map(str::to_ascii_lowercase) + .filter_map(|k| params.get(k)) + // A standalone table given by its number, by the key it would be converted under. + .filter_map(|v| v.as_str().map(str::to_ascii_lowercase).or_else(|| v.as_u64().and_then(|n| u32::try_from(n).ok()).map(table_key))) .collect() } @@ -1802,7 +1803,7 @@ fn env_inputs( env: &crate::project::GpEnvironment, params: &Value, ) -> Result>, String> { - let rows = env_rows(map, full, env, params); + let rows = env_rows(map, full, env, params)?; if let Some((name, v)) = rows.iter().next() && v.is_empty() { @@ -1818,10 +1819,10 @@ fn env_rows( full: &std::collections::HashMap, env: &crate::project::GpEnvironment, params: &Value, -) -> std::collections::HashMap> { - let Some(e) = env.extent else { return std::collections::HashMap::new() }; +) -> Result>, String> { + let Some(e) = env.extent else { return Ok(std::collections::HashMap::new()) }; let Some(input) = params.get("target").or_else(|| params.get("input")).and_then(Value::as_str) else { - return std::collections::HashMap::new(); + return Ok(std::collections::HashMap::new()); }; // The layer the name finds (the first of that name), as the tool will. map.layer_by_name(input) @@ -1844,9 +1845,17 @@ fn env_rows( Some(to) => Dataset::geometry_to_lonlat_by(to, g).map_or_else(|_| by_own(g), |g| g.extent().intersects(&e)), None => false, }; - let rows: Vec = - ds.features.rows().enumerate().filter(|(_, r)| r.geometry().is_some_and(meets)).map(|(i, _)| i).collect(); - (l.name.to_ascii_lowercase(), rows) + // (Each feature converted: a Cancel is looked for every 256 of them.) + let mut rows = Vec::new(); + for (i, r) in ds.features.rows().enumerate() { + if i % 256 == 0 { + rustgis_data::progress::check().map_err(|e| format!("{}: {e}", l.name))?; + } + if r.geometry().is_some_and(meets) { + rows.push(i); + } + } + Ok((l.name.to_ascii_lowercase(), rows)) }) .collect() } @@ -1895,10 +1904,13 @@ impl Inputs for MapInputs<'_> { } fn table(&self, id: u32) -> Option<&Dataset> { // Converted before the run when the tool's parameters give its number ([`inputs_in`]); - // else read as it is only in the system the tool works in, as a layer is. + // else read as it is only in the system the tool works in, as a layer is, or when the + // tool reads only its attributes (Join Field's join table). self.loaded.get(&table_key(id)).or_else(|| { self.snap.tables.iter().find(|t| t.id == id).map(|t| &t.dataset).filter(|d| { - d.geometry_type == rustgis_data::GeometryType::None || d.coord_crs().to(self.work).is_ok_and(|to| to.is_identity()) + d.geometry_type == rustgis_data::GeometryType::None + || self.unread.contains(&table_key(id)) + || d.coord_crs().to(self.work).is_ok_and(|to| to.is_identity()) }) }) } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 3d66823f08..d6b8c35552 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1533,6 +1533,18 @@ fn a_join_tables_places_dont_decide_the_system() { assert_eq!(bits(&held_coords(&s, "Owned")), bits(&held_coords(&s, "Parcels"))); let ds = &s.map().layer_by_name("Owned").unwrap().dataset; assert_eq!(ds.value(0, ds.field_index("owner").unwrap()).to_string(), "far owner"); + // The same as a standalone table given by its number: read as it is too. + let mut table = s.map().layer_by_name("Far").unwrap().dataset.clone(); + table.name = "Far table".into(); + let id = s.project.add_table(table); + let mark = s.notice_mark(); + let p = json!({"tool": "joinField", "params": {"target": "Parcels", "targetField": "n", "joinTable": id, "joinField": "n", "output": "Owned_2"}}); + s.run("gp.run", &p).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(!said.iter().any(|t| t.contains("worked in longitude/latitude")), "{said:?}"); + let ds = &s.map().layer_by_name("Owned_2").unwrap().dataset; + assert_eq!(ds.coord_crs(), UTM); + assert_eq!(ds.value(0, ds.field_index("owner").unwrap()).to_string(), "far owner"); } /// A project giving Web Mercator and longitude/latitude as their EPSG codes (`{"Epsg": 3857}`, @@ -1770,7 +1782,7 @@ fn bent_edges_are_found_beyond_their_middle_and_on_closing_edges() { }; // Across UTM zone 32N's central meridian (9°E) at the equator, point-symmetric about where they // cross: its middle, (9°E, 0°), is on the chord and on the edge in Web Mercator alike, and it - // bends away to either side, by metres at its quarters (CodeRabbit's example, on #2659). + // bends away to either side, by metres at its quarters. let (n, far) = bent(Geometry::Line(vec![vec![Coord::new(8.0, -1.0), Coord::new(10.0, 1.0)]])); assert_eq!(n, 1); assert!(far > 1.0, "{far}"); @@ -1786,7 +1798,7 @@ fn bent_edges_are_found_beyond_their_middle_and_on_closing_edges() { /// A line held in UTM along a northing is tilted in longitude/latitude: an environment's extent /// near a corner of its box there, away from the line, admits it, in a run in longitude/latitude -/// and in the held system alike (CodeRabbit, on #2659). +/// and in the held system alike. #[test] fn the_environments_extent_admits_a_tilted_line_by_its_box_in_longitude_latitude() { let mut ss = both(); @@ -1813,7 +1825,7 @@ fn the_environments_extent_admits_a_tilted_line_by_its_box_in_longitude_latitude } /// A standalone table with geometry given by its number is converted into the system the run -/// works in, as one given by name is (claude-review, on #2659). +/// works in, as one given by name is. #[test] fn a_numbered_table_is_converted_into_the_held_system() { let mut ss = both(); From ff1109491c9f26750d3e669d0e4f8573b12c9b3a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 08:54:35 +0100 Subject: [PATCH 8/9] Review: doc comments name the run's plane; docs rewrapped --- crates/analysis/src/tools.rs | 8 +++--- crates/engine/src/cmd/gp.rs | 3 +-- docs/user-guide/analysis.md | 51 ++++++++++++++++++------------------ 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 8619c60f37..d5f9d6efbb 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5365,8 +5365,9 @@ fn merc_extent(g: &impl geo::CoordsIter) -> Extent { /// Summarize Within: each polygon's count of the (selected) point features that meet it, inside it /// or on its edge; a feature of several points counts once in each polygon it meets. Each point is /// tested only against the polygons whose extents hold it, through an [`ExtentIndex`], and, at a -/// pole, those reaching it, which it touches at any longitude. The extents are in the analysis -/// plane, where the test runs, which goes on past 85.05° to the poles (#1033). The statistics +/// pole, those reaching it, which it touches at any longitude. The extents are in the run's plane +/// ([`crate::convert::plane`]), where the test runs: the analysis plane, which goes on past 85.05° to +/// the poles (#1033), or a projected layer's own coordinates. The statistics /// asked for, of the point layer's fields, are over the same points, as `_` after /// `point_count`. fn count_points(inp: &dyn Inputs, p: &Json) -> Result { @@ -6873,7 +6874,8 @@ impl AtPoles { } } -/// The poles polygons in the analysis plane reach, from their box there: north, then south. +/// The poles polygons in the run's plane reach, from their box there: north, then south (none in +/// a projected layer's own coordinates, [`crate::convert::plane`]). fn plane_poles(mp: &MultiPolygon) -> (bool, bool) { use geo::BoundingRect; let lat = |y: f64| rustgis_geom::plane_to_lonlat(Coord::new(0.0, y)).y; diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 041a1dcba4..781cc92e68 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1579,7 +1579,6 @@ fn inputs_in( work: Crs, ) -> Result<(std::collections::HashMap, Vec), String> { let mut converted = std::collections::HashMap::new(); - // What a run that crosses edges is told of an input's converted edges ([`bent_edges`]). // The converted inputs with edges that bend ([`bent_edges`]): name, how many, how far. let mut bent: Vec<(String, usize, f64)> = Vec::new(); let reads_edges = work != Crs::LonLat && spec.is_some_and(rustgis_analysis::ToolSpec::reads_edges); @@ -1848,7 +1847,7 @@ fn env_rows( // (Each feature converted: a Cancel is looked for every 256 of them.) let mut rows = Vec::new(); for (i, r) in ds.features.rows().enumerate() { - if i % 256 == 0 { + if i.is_multiple_of(256) { rustgis_data::progress::check().map_err(|e| format!("{}: {e}", l.name))?; } if r.geometry().is_some_and(meets) { diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a08e727a11..9750c9aa4c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -174,29 +174,30 @@ which searches every tool) or Command Search. Fill in its parameters and click * layers or tables are added to the project; selection tools select existing rows and Calculate Geometry Attributes updates the input layer. Each run is listed under **Analyze › History**. -**Which coordinate system a tool works in.** Most tools work in longitude/latitude, with -geodesic distances and areas, whatever system their layers are in. Some work in their first -input's own coordinate system when it is a projected one, such as a UTM zone or a national grid: -Summary Statistics, Pivot Table, Join Field, Select Layer By Attribute, Export Features, Merge, -Polygon To Line, Split Line At Vertices, Feature Envelope To Polygon, Unsplit Line, Feature -Vertices To Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, -Identity, Union, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry -(convex hull), Feature To Point and Summarize Within; and Select Layer By Location and -Spatial Join when they measure no distance (no search distance, a match other than Closest or -Within a distance). Their other inputs are converted into that system for the run, and their new -layers are kept in it, so the coordinates of what they copy stay exactly as they were. An overlay -there takes each edge as straight in that system, not in Web Mercator as it does in -longitude/latitude, so where an edge crosses another can differ from the same tool's result in -longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: some 20 cm for -a 3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another system is converted vertex by vertex, as the map draws it in -that system, and its long edges can run much farther from where they run in longitude/latitude: a -degree-wide box's east-west edges, which follow their parallels there, are chords in UTM up to -120 m away. The tool then says how many edges of which layer run more than a metre away, and how -far the farthest does. A world projection (World Mercator, Plate Carrée, Robinson, Equal Earth and -the like), whose plane has the antimeridian as a seam and the poles as lines, is worked on in -longitude/latitude, as Web Mercator is. If another input has a place that system can't hold, the tool works in -longitude/latitude instead, and its message says so. A layer in longitude/latitude, Web Mercator or -another geographic system is worked on in longitude/latitude, as before. +**Which coordinate system a tool works in.** Most tools work in longitude/latitude, with geodesic +distances and areas, whatever system their layers are in. Some work in their first input's own +coordinate system when it is a projected one, such as a UTM zone or a national grid: Summary +Statistics, Pivot Table, Join Field, Select Layer By Attribute, Export Features, Merge, Polygon To +Line, Split Line At Vertices, Feature Envelope To Polygon, Unsplit Line, Feature Vertices To +Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, Identity, Union, +Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry (convex hull), +Feature To Point and Summarize Within; and Select Layer By Location and Spatial Join when they +measure no distance (no search distance, a match other than Closest or Within a distance). Their +other inputs are converted into that system for the run, and their new layers are kept in it, so +the coordinates of what they copy stay exactly as they were. An overlay there takes each edge as +straight in that system, not in Web Mercator as it does in longitude/latitude, so where an edge +crosses another can differ from the same tool's result in longitude/latitude, by up to about L² tan +φ / 8R for an edge L long at latitude φ: some 20 cm for a 3 km edge at 48°N, 2 m for a 10 km one, +220 m for a 100 km one. An input in another system is converted vertex by vertex, as the map draws +it in that system, and its long edges can run much farther from where they run in +longitude/latitude: a degree-wide box's east-west edges, which follow their parallels there, are +chords in UTM up to 120 m away. The tool then says how many edges of which layer run more than a +metre away, and how far the farthest does. A world projection (World Mercator, Plate Carrée, +Robinson, Equal Earth and the like), whose plane has the antimeridian as a seam and the poles as +lines, is worked on in longitude/latitude, as Web Mercator is. If another input has a place that +system can't hold, the tool works in longitude/latitude instead, and its message says so. A layer +in longitude/latitude, Web Mercator or another geographic system is worked on in +longitude/latitude, as before. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that @@ -1241,8 +1242,8 @@ CRS metadata. Coordinates are used directly, without projection or snapping. memory returns an error. - **Feature Envelope To Polygon** (`featureEnvelopeToPolygon`) writes one axis-aligned rectangle around all coordinates of each feature, along the axes of the layer's own system when it is a - projected one other than a world projection (see above), and of longitude/latitude otherwise. Point features and - horizontal or vertical lines have zero-area envelopes and are skipped with a count. Longitude + projected one other than a world projection (see above), and of longitude/latitude otherwise. + Point features and horizontal or vertical lines have zero-area envelopes and are skipped with a count. Longitude bounds are literal, including for features spanning the antimeridian. - **Unsplit Line** (`unsplitLine`) joins line parts at exactly equal endpoints where precisely two part ends meet and all attribute values agree. Reversed parts and closed cycles are From 9935c01aab4e8434e8f05ec845327a9d89f25f1d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 09:01:18 +0100 Subject: [PATCH 9/9] Row uses: 784 --- xtask/row-uses.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 3ae2a90555..95b6158a4e 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 794 +count = 784