From 93ed1032e2d4b5dc7a8f95475cfc0cebdc29fea1 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 20:05:14 +0100 Subject: [PATCH 1/4] Tools that don't depend on the coordinate system work in their first input's own projected system (#2032 C2e-1) --- crates/analysis/src/lib.rs | 35 +++- crates/analysis/src/repair.rs | 4 +- crates/analysis/src/tools.rs | 8 +- crates/analysis/src/tools/repair_geometry.rs | 17 +- crates/data/src/lib.rs | 22 ++- crates/engine/src/cmd/gp.rs | 174 ++++++++++++++++--- crates/engine/src/tests/held_layers.rs | 149 ++++++++++++++++ docs/user-guide/analysis.md | 29 +++- 8 files changed, 394 insertions(+), 44 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 68aad49e0c..a1bd36f722 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -173,8 +173,9 @@ pub struct ToolResult { /// Access to the map's layers by name. pub trait Inputs { - /// A vector layer or table by name, in longitude/latitude: the space every tool reads its - /// inputs in and writes its outputs in. + /// A vector layer or table by name, in the system the tool works in: longitude/latitude, or + /// 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>; /// 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> { @@ -229,6 +230,36 @@ pub struct ToolSpec { pub run: fn(&dyn Inputs, &Value) -> Result, } +/// 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). +const OWN_SYSTEM_TOOLS: &[&str] = &[ + "summaryStatistics", + "pivotTable", + "joinField", + "selectByAttributes", + "exportFeatures", + "polygonToLine", + "splitLineAtVertices", + "featureEnvelopeToPolygon", + "unsplitLine", + "featureVerticesToPoints", + "merge", + "checkGeometry", + "repairGeometry", +]; + +impl ToolSpec { + /// Whether the tool works in its first input's own coordinate system when that is a projected + /// 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)) + } +} + /// Runs an external tool (the spec says which). pub type ExternalRunner = fn(&ToolSpec, &dyn Inputs, &Value) -> Result; diff --git a/crates/analysis/src/repair.rs b/crates/analysis/src/repair.rs index 17301fc1a8..3bd90addc1 100644 --- a/crates/analysis/src/repair.rs +++ b/crates/analysis/src/repair.rs @@ -107,8 +107,8 @@ pub(crate) struct Repaired { /// direction, where they would have no area ([`narrower_than`]); written as `no_area` after /// the codes. pub narrow: usize, - /// When the overlay rebuilt it, how far its coordinates may have moved, in their units (degrees, - /// as coordinates are stored). + /// When the overlay rebuilt it, how far its coordinates may have moved, in their units (degrees + /// for a layer in longitude/latitude, a projected system's own units for one held in it). pub moved: Option, /// Under [`Rule::EvenOdd`], rings dropped as duplicates before the rings were combined, since a /// pair would cancel out: a hole repeated in its part, and every ring of a part repeated whole diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 357c227ea7..44d8a50751 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 stored longitude/latitude coordinates. 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, 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: "" }, @@ -6715,6 +6715,9 @@ fn export_features(inp: &dyn Inputs, p: &Json) -> Result { rs.retain(|r| rustgis_data::query::eval(&e, ds, *r)); } let mut out = copy_schema(ds, out_name(p, format!("{}_Export", ds.name)), ds.geometry_type); + // Its features as they are: in the input's system, which exports use by default, with what it + // lost on reading. + (out.crs, out.crs_incomplete, out.zm_dropped) = (ds.crs, ds.crs_incomplete, ds.zm_dropped); for r in rs { if let Some(f) = ds.features.get(r) { out.push(f.geometry.clone(), f.attrs.clone()); @@ -8165,7 +8168,8 @@ fn split_line_at_vertices(inp: &dyn Inputs, p: &Json) -> Result Result { geometry::convert(inp, p, geometry::Conversion::FeatureEnvelopeToPolygon) } diff --git a/crates/analysis/src/tools/repair_geometry.rs b/crates/analysis/src/tools/repair_geometry.rs index 1b694662de..2fb48c414f 100644 --- a/crates/analysis/src/tools/repair_geometry.rs +++ b/crates/analysis/src/tools/repair_geometry.rs @@ -232,7 +232,10 @@ fn run_with_room( } out.features = list.into(); - let mut messages = notices(&tally, &field, rule); + // The units its coordinates are in, which the overlay's rounding moves them by. + let crs = ds.coord_crs(); + let units = if crs.is_geographic() { "degrees of longitude or latitude".to_string() } else { format!("the units of {}", crs.label()) }; + let mut messages = notices(&tally, &field, rule, &units); messages.extend(notes); let losses = (tally.extra > 0) .then(|| rustgis_data::loss::LossMessage { @@ -251,7 +254,7 @@ fn run_with_room( /// and per kind of change beyond the codes: pieces dropped (with too few points or no area, or /// narrower than a step of the overlay's grid in any direction), holes taken out, parts merged or /// split, coordinates moved. `field` is the output's repairs field. -fn notices(t: &Tally, field: &str, rule: Rule) -> Vec { +fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec { let mut messages = vec![summary(t)]; let is = |n: usize| if n == 1 { "is" } else { "are" }; let was = |n: usize| if n == 1 { "was" } else { "were" }; @@ -343,7 +346,7 @@ fn notices(t: &Tally, field: &str, rule: Rule) -> Vec { } if t.overlaid > 0 { messages.push(format!( - "{TOOL}: {} {} rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} degrees of longitude or latitude, and vertices in the middle of straight edges were left out", + "{TOOL}: {} {} rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} {units}, and vertices in the middle of straight edges were left out", features(t.overlaid), was(t.overlaid), rounded_up(t.moved) @@ -399,6 +402,8 @@ fn summary(t: &Tally) -> String { #[cfg(test)] mod tests { use super::*; + /// The units a layer in longitude/latitude has its coordinates in. + const DEGREES: &str = "degrees of longitude or latitude"; /// The inputs: one layer, with nothing selected. struct One(Dataset); @@ -456,7 +461,7 @@ mod tests { fn features_left_as_they_were_are_counted_by_reason() { let t = Tally { processed: 9, failed: 1, ..Tally::default() }; assert_eq!( - notices(&t, "repairs", Rule::default()), + notices(&t, "repairs", Rule::default(), DEGREES), [ "Repair Geometry: repaired 0 of 9 features", "Repair Geometry: 1 feature couldn't be repaired, because geo's geometry operations failed on it, and is written unchanged, with repair_failed in repairs", @@ -464,14 +469,14 @@ mod tests { ); let t = Tally { processed: 9, work: 2, memory: 3, failed: 2, ..Tally::default() }; assert_eq!( - notices(&t, "repairs_2", Rule::default())[1..], + notices(&t, "repairs_2", Rule::default(), DEGREES)[1..], [ "Repair Geometry: 2 features were too complex to repair within the work limit and are written unchanged, with too_complex in repairs_2", "Repair Geometry: 3 features couldn't be repaired, because there wasn't enough memory to repair them, and are written unchanged, with too_complex in repairs_2", "Repair Geometry: 2 features couldn't be repaired, because geo's geometry operations failed on them, and are written unchanged, with repair_failed in repairs_2", ] ); - assert_eq!(notices(&Tally::default(), "repairs", Rule::default()), ["Repair Geometry: no features to repair"]); + assert_eq!(notices(&Tally::default(), "repairs", Rule::default(), DEGREES), ["Repair Geometry: no features to repair"]); } /// A cancel stops the repairs at the next feature, and the copies at the next row. diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 385a177b56..75820ca391 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1075,7 +1075,7 @@ impl Dataset { } } - /// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its + /// The dataset in longitude/latitude, the space most analysis tools work in: borrowed while its /// coordinates are longitude/latitude ([`Dataset::coord_crs`]); otherwise a copy with every /// geometry converted, missing coordinates kept. Refused, naming the first feature that can't /// be, when one of its places can't be converted. The copy is held in longitude/latitude @@ -1104,6 +1104,26 @@ impl Dataset { Ok(Cow::Owned(out)) } + /// The dataset in `crs`, the system a tool works in when it works in its first input's own + /// ([`Dataset::in_lonlat`] for longitude/latitude): borrowed while its coordinates are already + /// there; otherwise a copy held there ([`Dataset::hold_in`]), missing coordinates kept. + /// Refused as [`Dataset::hold_in`] refuses, naming the first feature with a place `crs` can't + /// hold. + pub fn in_crs(&self, crs: raster::Crs) -> std::result::Result, String> { + if crs == raster::Crs::LonLat { + return self.in_lonlat(); + } + if self.coord_crs().to(crs)?.is_identity() { + return Ok(Cow::Borrowed(self)); + } + let mut out = self.clone(); + // A copy for one run, not the layer: a window's rows are converted as they are. + let windowed = std::mem::take(&mut out.windowed); + out.hold_in(crs)?; + out.windowed = windowed; + Ok(Cow::Owned(out)) + } + /// A longitude/latitude box in its own coordinates ([`Dataset::coord_crs`]), as /// [`raster::Reprojection::extent`] converts it: for asking which features a box reaches, once /// for the box rather than once a feature. The box itself while they are diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index e4a93128a6..71ab1d6351 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -3,6 +3,7 @@ use rustgis_analysis::{Inputs, Output, OutputLayer, RasterInput}; use rustgis_data::Dataset; use rustgis_data::loss::{LossCode, LossMessage}; +use rustgis_data::raster::Crs; use serde_json::{Value, json}; use super::{need_layers, ps}; @@ -710,6 +711,7 @@ impl ToolRun { }; let mut result = pin.run(&inputs, ¶ms, control, &|| continuation.check()); if let Ok(r) = &mut result { + inputs.hold_results(r); r.messages.extend(inputs.messages.iter().cloned()); r.losses.extend(inputs.losses.iter().cloned()); } @@ -1228,8 +1230,11 @@ struct MapInputs<'a> { /// environment's extent. rows: std::collections::HashMap>, /// Streamed layers the tool reads, loaded whole, and copies of layers in another system than - /// longitude/latitude, converted ([`lonlat_inputs`]), by lowercase name. + /// the one it works in, converted ([`work_inputs`]), by lowercase name. loaded: std::collections::HashMap, + /// The system the tool works in ([`work_system`]): the one its inputs are given in and its + /// outputs are made in. + work: Crs, /// Import warnings from local file inputs, kept in the tool result and history. messages: Vec, losses: Vec, @@ -1243,6 +1248,32 @@ struct MapInputs<'a> { } impl MapInputs<'_> { + /// Marks the layers a tool made as held in the system it worked in ([`MapInputs::work`]), + /// where their coordinates are, so they aren't taken for longitude/latitude: a layer it made + /// from scratch starts in longitude/latitude ([`Dataset::held_in`]). Nothing for a tool that + /// worked in longitude/latitude, or for a table. + fn hold_results(&self, result: &mut rustgis_analysis::ToolResult) { + if self.work == Crs::LonLat { + return; + } + let hold = |ds: &mut Dataset| { + if ds.geometry_type != rustgis_data::GeometryType::None { + ds.held_in = self.work; + } + }; + match &mut result.output { + Output::Layer(ds) | Output::Update { dataset: ds, .. } => hold(ds), + Output::Layers(outputs) => { + for o in outputs { + if let rustgis_analysis::OutputLayer::Vector(ds) = o { + hold(ds); + } + } + } + Output::Selection { .. } | Output::Table(_) | Output::File { .. } => {} + } + } + /// The flat map's projection, built on first use. fn flat(&self) -> Option<&(String, rustgis_map::projection::Flat, f64)> { let map = &self.snap.map; @@ -1290,10 +1321,10 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, } #[cfg(target_arch = "wasm32")] let mut full = full; - lonlat_inputs(&snap.map, spec, params, &mut full)?; + let work = work_inputs(&snap.map, &snap.tables, spec, params, &mut full, &mut messages)?; let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; - Ok(MapInputs { snap, rows, loaded: full, messages, losses, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new() }) + Ok(MapInputs { snap, rows, loaded: full, work, messages, losses, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new() }) } /// Narrows the rows a tool reads of each layer to the features its definition query keeps, as the @@ -1408,23 +1439,101 @@ fn streamed_inputs( Ok((full, said)) } -/// The layers a tool reads, in longitude/latitude, the space analysis tools work in -/// ([`Inputs::dataset`]): those read whole (streamed layers, files) converted where they are, and -/// a converted copy of each other layer it names whose coordinates are in another system. Nothing -/// is copied for a layer held in longitude/latitude. -fn lonlat_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. +/// +/// [`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() +} + +/// The system a run works in: its first input's own ([`Dataset::coord_crs`]) when the tool works +/// in it and it is one tools work in ([`works_in`]), else longitude/latitude. +fn work_system( + map: &rustgis_map::Map, + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, + 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 }; + // The tool's first layer parameter, as it names it: a table given by its number (read + // unconverted, [`Inputs::table`]) or a layer named under another key (Join Field's `input`) + // leaves the run in longitude/latitude, as before. + let Some(kind) = + spec.params.iter().find(|p| matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers)) + else { + return Crs::LonLat; + }; + let value = params.get(kind.name).unwrap_or(&Value::Null); + let first = if kind.kind == K::VectorLayers { + rustgis_analysis::layer_list(value).ok().and_then(|v| v.first().copied()) + } else { + value.as_str() + }; + let Some(first) = first else { return Crs::LonLat }; + // Files read whole are kept by the name they were given, streamed layers by lowercase name. + full.get(first) + .or_else(|| full.get(&first.to_ascii_lowercase())) + .or_else(|| map.layer_by_name(first).filter(|l| !l.is_raster()).map(|l| &l.dataset)) + .map(Dataset::coord_crs) + .filter(|c| works_in(*c)) + .unwrap_or(Crs::LonLat) +} + +/// 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. +fn work_inputs( map: &rustgis_map::Map, + tables: &[crate::project::Table], spec: Option<&rustgis_analysis::ToolSpec>, params: &Value, full: &mut std::collections::HashMap, -) -> Result<(), String> { - for ds in full.values_mut() { - if let std::borrow::Cow::Owned(converted) = ds.in_lonlat()? { - *ds = converted; + messages: &mut Vec, +) -> Result { + let work = work_system(map, spec, params, full); + if work != Crs::LonLat { + match inputs_in(map, tables, spec, params, full, work) { + Ok(converted) => { + full.extend(converted); + return Ok(work); + } + Err(e) => { + // A Cancel isn't a place that can't be held. + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let name = spec.map_or("The tool", |t| t.name); + messages.push(format!("{name} worked in longitude/latitude, not {}: {e}", work.label())); + } + } + } + let converted = inputs_in(map, tables, spec, params, full, Crs::LonLat)?; + full.extend(converted); + Ok(Crs::LonLat) +} + +/// Copies of the layers a tool reads converted into `work`, by lowercase name: those read whole +/// (streamed layers, files) and each other layer or standalone table with geometry it names whose +/// coordinates are in another system. Nothing is copied for a layer already in `work`. +fn inputs_in( + map: &rustgis_map::Map, + tables: &[crate::project::Table], + spec: Option<&rustgis_analysis::ToolSpec>, + params: &Value, + full: &std::collections::HashMap, + work: Crs, +) -> Result, String> { + let mut converted = std::collections::HashMap::new(); + for (key, ds) in full { + if let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { + converted.insert(key.clone(), c); } } // Every text the parameters hold that names a layer, not only layer parameters: a tool may - // name one elsewhere, and a layer it reads must be in longitude/latitude. + // name one elsewhere, and a layer it reads must be in the system it works in. fn texts<'v>(v: &'v Value, out: &mut Vec<&'v str>) { match v { Value::String(s) => out.push(s), @@ -1437,16 +1546,20 @@ fn lonlat_inputs( texts(params, &mut names); for n in names { let key = n.to_ascii_lowercase(); - if full.contains_key(&key) { + if full.contains_key(&key) || converted.contains_key(&key) { continue; } - if let Some(l) = map.layer_by_name(n).filter(|l| !l.is_raster()) - && let std::borrow::Cow::Owned(converted) = l.dataset.in_lonlat()? + // A layer, or a standalone table with geometry; one without reads alike in any system. + if let Some(ds) = project_input(map, tables, n, false) + .filter(|i| !matches!(i, ProjectInput::Layer(l) if l.is_raster())) + .map(|i| i.dataset()) + .filter(|d| d.geometry_type != rustgis_data::GeometryType::None) + && let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { - full.insert(key, converted); + converted.insert(key, c); } } - Ok(()) + Ok(converted) } /// The executor's source-read choice, shared with pure permission planning. @@ -1559,10 +1672,17 @@ impl Inputs for MapInputs<'_> { self.loaded .get(layer) .or_else(|| self.loaded.get(&layer.to_ascii_lowercase())) - // A layer read as it is only in longitude/latitude: one in another system is - // converted before the run ([`lonlat_inputs`]) when the tool names it, and isn't read + // A layer read as it is only in the system the tool works in: one in another system is + // converted before the run ([`work_inputs`]) when the tool names it, and isn't read // in its own coordinates otherwise. - .or_else(|| project_input(&self.snap.map, &self.snap.tables, layer, false).map(|i| i.dataset()).filter(|d| d.edits_in_lonlat())) + .or_else(|| { + project_input(&self.snap.map, &self.snap.tables, layer, false) + .map(|i| i.dataset()) + // A table without geometry reads alike in any system. + .filter(|d| { + d.geometry_type == rustgis_data::GeometryType::None || d.coord_crs().to(self.work).is_ok_and(|to| to.is_identity()) + }) + }) } fn table(&self, id: u32) -> Option<&Dataset> { self.snap.tables.iter().find(|t| t.id == id).map(|t| &t.dataset) @@ -2716,6 +2836,7 @@ pub(crate) fn execute( pin.run(&inputs, params, control, &|| continuation.check()) }; if let Ok(result) = &mut res { + inputs.hold_results(result); result.messages.extend(inputs.messages.iter().cloned()); result.losses.extend(inputs.losses.iter().cloned()); } @@ -3127,8 +3248,15 @@ fn apply_with( } Output::Update { layer, dataset } => { let l = s.map_mut().layers.iter_mut().find(|l| l.name.eq_ignore_ascii_case(&layer)).ok_or("the input layer disappeared")?; - // Made in longitude/latitude, written back in the layer's own coordinates. - l.dataset = l.dataset.results_from_lonlat(dataset)?; + // Made in the system the tool worked in ([`MapInputs::hold_results`]): taken as made + // when that is the layer's own, else written back in its own coordinates from + // longitude/latitude. + l.dataset = if dataset.coord_crs() == l.dataset.coord_crs() { + dataset + } else { + let lonlat = if dataset.coord_crs() == Crs::LonLat { dataset } else { dataset.in_lonlat()?.into_owned() }; + l.dataset.results_from_lonlat(lonlat)? + }; // Under the layer's name now: a background run's layer may have been renamed meanwhile. l.dataset.name.clone_from(&l.name); // A streamed layer updated by a tool holds the whole result in memory from now on. diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 04c8ca8223..1b8d41d8c1 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1340,3 +1340,152 @@ fn the_held_layer_fixture_opens_held() { assert!((c.x - x).abs() < 1e-6 && (c.y - y).abs() < 1e-6, "{c:?}"); } } + +/// Every coordinate of a layer as it holds it ([`Dataset::coord_crs`]), feature by feature. +fn held_coords(s: &Session, layer: &str) -> Vec> { + let l = s.map().layer_by_name(layer).unwrap_or_else(|| panic!("no layer {layer}")); + l.dataset + .features + .iter() + .map(|f| { + let mut v = Vec::new(); + if let Some(g) = &f.geometry { + g.for_each_coord(|c| v.push(c)); + } + v + }) + .collect() +} + +/// The coordinates as bits, for comparing them exactly. +fn bits(v: &[Vec]) -> Vec<(u64, u64)> { + v.iter().flatten().map(|c| (c.x.to_bits(), c.y.to_bits())).collect() +} + +/// A tool that works in its first input's own system (#2032 C2e) is given a layer held in UTM in +/// UTM, not a longitude/latitude copy, and its new layer is held in UTM too: what it copies keeps +/// its stored coordinates bit for bit, and what it makes from them (an envelope) is made along +/// UTM's axes. +#[test] +fn a_tool_works_in_its_held_inputs_own_system() { + let mut s = session(UTM); + s.map_mut().layers.iter_mut().for_each(|l| l.dataset.crs = Some(UTM)); + let run = |s: &mut Session, tool: &str, input: &str, out: &str| { + s.run("gp.run", &json!({"tool": tool, "params": {"input": input, "output": out}})).unwrap_or_else(|e| panic!("{tool}: {e}")); + let l = s.map().layer_by_name(out).unwrap_or_else(|| panic!("{tool}: no output")); + assert_eq!(l.dataset.coord_crs(), UTM, "{tool}: held in"); + }; + for (tool, input, out) in [ + ("exportFeatures", "Wells", "Exported"), + ("polygonToLine", "Parcels", "Outlines"), + ("repairGeometry", "Parcels", "Repaired"), + ("featureVerticesToPoints", "Roads", "Vertices"), + ("splitLineAtVertices", "Roads", "Segments"), + ("unsplitLine", "Roads", "Unsplit"), + ] { + run(&mut s, tool, input, out); + let (copied, from) = (bits(&held_coords(&s, out)), bits(&held_coords(&s, input))); + let kept = |c: &(u64, u64)| from.contains(c); + assert!(!copied.is_empty() && copied.iter().all(kept), "{tool}: its coordinates are the input's, as held"); + } + // Export Features keeps the input's system as the one exports use (#2032 C2e). + assert_eq!(s.map().layer_by_name("Exported").unwrap().dataset.crs, Some(UTM)); + // Each envelope is the box of the parcel's stored UTM coordinates, which in longitude/latitude + // is a turned rectangle, not the box of the parcel's longitudes and latitudes. + run(&mut s, "featureEnvelopeToPolygon", "Parcels", "Envelopes"); + let parcels = held_coords(&s, "Parcels"); + for (i, envelope) in held_coords(&s, "Envelopes").iter().enumerate() { + let parcel = parcels.get(i).unwrap(); + let (min_x, max_x) = parcel.iter().fold((f64::MAX, f64::MIN), |(a, b), c| (a.min(c.x), b.max(c.x))); + let (min_y, max_y) = parcel.iter().fold((f64::MAX, f64::MIN), |(a, b), c| (a.min(c.y), b.max(c.y))); + for c in envelope { + assert!(c.x == min_x || c.x == max_x, "envelope {i}: x {} of {min_x}..{max_x}", c.x); + assert!(c.y == min_y || c.y == max_y, "envelope {i}: y {} of {min_y}..{max_y}", c.y); + } + } + // Check Geometry finds nothing wrong with valid squares, in any system. + s.run("gp.run", &json!({"tool": "checkGeometry", "params": {"input": "Parcels", "output": "Problems"}})).unwrap(); + assert!(held_coords(&s, "Problems").is_empty()); + // A tool working on attributes alone answers as it does for the layer in longitude/latitude. + let mut ss = both(); + let p = json!({"tool": "selectByAttributes", "params": {"input": "Wells", "where": "n >= 4"}}); + run_both(&mut ss, "gp.run", &p); + assert_eq!(selected(&ss[0], "Wells"), selected(&ss[1], "Wells")); + assert_eq!(selected(&ss[1], "Wells"), vec![4, 5, 6, 7, 8]); +} + +/// Merge's other inputs are converted into its first input's own system, where its result is +/// held: the first's coordinates kept bit for bit, the others' where PROJ puts them; with a +/// first input in longitude/latitude, everything stays there as before. +#[test] +fn merge_converts_its_other_inputs_into_the_firsts_system() { + let mut s = session(UTM); + let mut plain = Dataset::new("Plain", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + plain.push(Some(Geometry::Point(Coord::new(11.6, 48.75))), vec![Cell::Text("p".into())]); + s.map_mut().add_dataset(plain); + let merge = |s: &mut Session, inputs: [&str; 2], out: &str| { + let p = json!({"tool": "merge", "params": {"inputs": inputs, "attributes": true, "output": out}}); + s.run("gp.run", &p).unwrap_or_else(|e| panic!("merge: {e}")) + }; + merge(&mut s, ["Wells", "Plain"], "Merged"); + let merged = s.map().layer_by_name("Merged").unwrap(); + assert_eq!(merged.dataset.coord_crs(), UTM); + let (out, wells) = (held_coords(&s, "Merged"), held_coords(&s, "Wells")); + assert_eq!(bits(out.get(..9).unwrap()), bits(&wells), "the wells as held"); + // echo 48.75 11.6 | cs2cs -f %.6f EPSG:4326 EPSG:32632 (PROJ 9.9.0): 691112.022414 5402926.247736 + let c = out.get(9).and_then(|v| v.first()).copied().unwrap(); + assert!((c.x - 691_112.022_414).abs() < 1e-3 && (c.y - 5_402_926.247_736).abs() < 1e-3, "{c:?}"); + // The other way round, the run works in longitude/latitude, as every run did before. + merge(&mut s, ["Plain", "Wells"], "Merged_LonLat"); + let lonlat_merge = s.map().layer_by_name("Merged_LonLat").unwrap(); + assert_eq!(lonlat_merge.dataset.coord_crs(), Crs::LonLat); + let first = held_coords(&s, "Merged_LonLat").first().and_then(|v| v.first()).copied().unwrap(); + assert_eq!((first.x, first.y), (11.6, 48.75)); +} + +/// An input with a place the first input's system can't hold (a point a quarter of the way round +/// the Earth from UTM zone 32N's meridian, which PROJ can't convert either) has the run work in +/// longitude/latitude, as every run did before, and its message says why. +#[test] +fn an_input_the_first_ones_system_cant_hold_is_worked_on_in_lonlat() { + let mut s = session(UTM); + let mut far = Dataset::new("Far", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + // echo 0 99 | cs2cs EPSG:4326 EPSG:32632 (PROJ 9.9.0): * * inf + far.push(Some(Geometry::Point(Coord::new(99.0, 0.0))), vec![Cell::Text("far".into())]); + s.map_mut().add_dataset(far); + let p = json!({"tool": "merge", "params": {"inputs": ["Wells", "Far"], "attributes": true, "output": "Merged"}}); + let mark = s.notice_mark(); + s.run("gp.run", &p).unwrap(); + let merged = s.map().layer_by_name("Merged").unwrap(); + assert_eq!(merged.dataset.coord_crs(), Crs::LonLat); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("Merge worked in longitude/latitude, not EPSG:32632: Far: feature")), "{said:?}"); + let last = held_coords(&s, "Merged").last().and_then(|v| v.first()).copied().unwrap(); + assert_eq!((last.x, last.y), (99.0, 0.0)); +} + +/// A standalone table without geometry (a spreadsheet's rows) joins onto a layer held in UTM as it +/// does onto one in longitude/latitude, and the joined layer keeps the parcels' places as held. +#[test] +fn a_table_joins_onto_a_held_layer() { + let mut owners = + Dataset::new("Owners", GeometryType::None, vec![Field::new("n", FieldType::Integer), Field::new("owner", FieldType::Text)]); + for n in 0..9 { + owners.push(None, vec![Cell::Int(n), Cell::Text(format!("owner {n}"))]); + } + let mut ss = both(); + for s in &mut ss { + s.project.add_table(owners.clone()); + } + let p = json!({"tool": "joinField", "params": {"target": "Parcels", "targetField": "n", "joinTable": "Owners", "joinField": "n", "output": "Owned"}}); + run_both(&mut ss, "gp.run", &p); + let owner = |s: &Session| { + let ds = &s.map().layer_by_name("Owned").unwrap().dataset; + let f = ds.field_index("owner").unwrap(); + (0..ds.features.len()).map(|r| ds.value(r, f).to_string()).collect::>() + }; + assert_eq!(owner(&ss[0]), owner(&ss[1])); + assert_eq!(owner(&ss[1]).first().map(String::as_str), Some("owner 0")); + assert_eq!(ss[1].map().layer_by_name("Owned").unwrap().dataset.coord_crs(), UTM); + assert_eq!(bits(&held_coords(&ss[1], "Owned")), bits(&held_coords(&ss[1], "Parcels"))); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1920cb81f4..34c24d00c7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -174,6 +174,17 @@ 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. 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 +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 count their work (Viewshed, IDW Interpolation, Kriging, Kernel Density, Buffer, Select Layer By @@ -595,8 +606,9 @@ Matching field names (case-insensitive) and types share a column. Other fields a missing values are empty. Incompatible types remain separate columns with unique suffixes, such as `count_2`, preserving their original values and types. Turn off **Preserve Attributes** for geometry only. Multipart geometry and holes are kept unchanged, new feature ids are assigned, -and export defaults to the first input's coordinate system; internal coordinates stay longitude -and latitude. The inputs stay unchanged, and the new layer can be undone. +and export defaults to the first input's coordinate system. The new layer is kept in the first +input's system when it is a projected one, the other inputs' features converted into it, and in +longitude/latitude otherwise. The inputs stay unchanged, and the new layer can be undone. **Feature Vertices To Points** (`featureVerticesToPoints`) writes a point at each vertex of the `input` layer's features (a point layer's points are their own vertices, and a multipoint's points @@ -1212,8 +1224,8 @@ CRS metadata. Coordinates are used directly, without projection or snapping. output memory, including repeated text attributes, before building the segments; unavailable memory returns an error. - **Feature Envelope To Polygon** (`featureEnvelopeToPolygon`) writes one axis-aligned rectangle - around all coordinates of each feature in longitude/latitude axes (converted from the layer's - own system). Point features and + 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 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 @@ -1346,12 +1358,13 @@ finds a hole outside, merges holes or merges parts. The rebuild uses the [geo](https://github.com/georust/geo) library's boolean overlay, which works on an integer grid: half the larger side of the feature's extent spans about 229 steps. -Coordinates are stored in degrees of longitude and latitude, so a step is about -0.000 000 000 12° (0.013 mm) for a feature 10 km across, and about 0.000 000 24° (2.6 cm at the -equator) for one spanning the world. Rebuilt coordinates may move by up to five steps from the +For a layer in longitude/latitude, a step is about 0.000 000 000 12° (0.013 mm) for a feature +10 km across, and about 0.000 000 24° (2.6 cm at the equator) for one spanning the world. For a +layer held in a projected system, the grid is laid over its own coordinates: a step is about +0.01 mm for a feature 10 km across. Rebuilt coordinates may move by up to five steps from the input's rings; in the tests they moved at most two thirds of a step. The overlay also leaves out vertices in the middle of straight edges. The tool says how many features were rebuilt and the -farthest, in degrees, their coordinates may have moved. Every rebuilt geometry is checked again and +farthest their coordinates may have moved, in the layer's units (degrees for longitude/latitude). Every rebuilt geometry is checked again and written only when it is valid. A hole or part narrower than one step of that grid in any direction can be rounded onto a single From e8568c774ff58abeff325d5ce85b47d243684ca8 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 20:42:36 +0100 Subject: [PATCH 2/4] Review: Repair Geometry's projected units read as a sentence; the output's name isn't read as an input; Summary Statistics and Pivot Table tested on a held layer --- crates/analysis/src/tools/repair_geometry.rs | 6 +++++- crates/engine/src/cmd/gp.rs | 8 ++++++-- crates/engine/src/tests/held_layers.rs | 20 ++++++++++++++++++++ docs/user-guide/analysis.md | 4 ++-- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/tools/repair_geometry.rs b/crates/analysis/src/tools/repair_geometry.rs index 2fb48c414f..bb240c43bf 100644 --- a/crates/analysis/src/tools/repair_geometry.rs +++ b/crates/analysis/src/tools/repair_geometry.rs @@ -234,7 +234,7 @@ fn run_with_room( // The units its coordinates are in, which the overlay's rounding moves them by. let crs = ds.coord_crs(); - let units = if crs.is_geographic() { "degrees of longitude or latitude".to_string() } else { format!("the units of {}", crs.label()) }; + let units = if crs.is_geographic() { "degrees of longitude or latitude".to_string() } else { format!("units of {}", crs.label()) }; let mut messages = notices(&tally, &field, rule, &units); messages.extend(notes); let losses = (tally.extra > 0) @@ -477,6 +477,10 @@ mod tests { ] ); assert_eq!(notices(&Tally::default(), "repairs", Rule::default(), DEGREES), ["Repair Geometry: no features to repair"]); + // A layer held in a projected system is told its bound in that system's units. + let rebuilt = Tally { overlaid: 1, moved: 0.01, ..Tally::default() }; + let said = notices(&rebuilt, "repairs", Rule::default(), "units of EPSG:32632").join("\n"); + assert!(said.contains("may have moved by up to 1.0e-2 units of EPSG:32632, and vertices"), "{said}"); } /// A cancel stops the repairs at the next feature, and the copies at the next row. diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 71ab1d6351..722e935830 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1533,7 +1533,8 @@ fn inputs_in( } } // Every text the parameters hold that names a layer, not only layer parameters: a tool may - // name one elsewhere, and a layer it reads must be in the system it works in. + // name one elsewhere, and a layer it reads must be in the system it works in. Not the name + // its output is given, which it doesn't read. fn texts<'v>(v: &'v Value, out: &mut Vec<&'v str>) { match v { Value::String(s) => out.push(s), @@ -1543,7 +1544,10 @@ fn inputs_in( } } let mut names = layer_names(spec, params); - texts(params, &mut names); + match params { + Value::Object(o) => o.iter().filter(|(k, _)| k.as_str() != "output").for_each(|(_, v)| texts(v, &mut names)), + other => texts(other, &mut names), + } for n in names { let key = n.to_ascii_lowercase(); if full.contains_key(&key) || converted.contains_key(&key) { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 1b8d41d8c1..190df8f9a3 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1412,6 +1412,21 @@ fn a_tool_works_in_its_held_inputs_own_system() { run_both(&mut ss, "gp.run", &p); assert_eq!(selected(&ss[0], "Wells"), selected(&ss[1], "Wells")); assert_eq!(selected(&ss[1], "Wells"), vec![4, 5, 6, 7, 8]); + // Summary Statistics and Pivot Table make the same table as for the layer in longitude/latitude. + let table = |s: &Session| { + let t = &s.project.tables.last().expect("a table").dataset; + let cells = (0..t.features.len()).flat_map(|r| (0..t.fields.len()).map(move |f| (r, f))).map(|(r, f)| t.value(r, f).to_string()); + (t.fields.iter().map(|f| f.name.clone()).collect::>(), cells.collect::>()) + }; + for p in [ + json!({"tool": "summaryStatistics", "params": {"input": "Wells", "field": "n"}}), + json!({"tool": "pivotTable", "params": {"input": "Wells", "fields": "n", "pivot": "name", "value": "n"}}), + ] { + run_both(&mut ss, "gp.run", &p); + let (a, b) = (table(&ss[0]), table(&ss[1])); + assert!(!a.1.is_empty(), "{p}: an empty table"); + assert_eq!(a, b, "{p}"); + } } /// Merge's other inputs are converted into its first input's own system, where its result is @@ -1462,6 +1477,11 @@ fn an_input_the_first_ones_system_cant_hold_is_worked_on_in_lonlat() { assert!(said.iter().any(|t| t.starts_with("Merge worked in longitude/latitude, not EPSG:32632: Far: feature")), "{said:?}"); let last = held_coords(&s, "Merged").last().and_then(|v| v.first()).copied().unwrap(); assert_eq!((last.x, last.y), (99.0, 0.0)); + // A layer the run only names its output after isn't read, so it doesn't decide the system. + let p = json!({"tool": "exportFeatures", "params": {"input": "Wells", "output": "Far"}}); + let answer = s.run("gp.run", &p).unwrap(); + let id = answer.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()).unwrap(); + assert_eq!(s.map().layer(id).unwrap().dataset.coord_crs(), UTM); } /// A standalone table without geometry (a spreadsheet's rows) joins onto a layer held in UTM as it diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 34c24d00c7..7d3a42bc66 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1364,8 +1364,8 @@ layer held in a projected system, the grid is laid over its own coordinates: a s 0.01 mm for a feature 10 km across. Rebuilt coordinates may move by up to five steps from the input's rings; in the tests they moved at most two thirds of a step. The overlay also leaves out vertices in the middle of straight edges. The tool says how many features were rebuilt and the -farthest their coordinates may have moved, in the layer's units (degrees for longitude/latitude). Every rebuilt geometry is checked again and -written only when it is valid. +farthest their coordinates may have moved, in the layer's units (degrees for longitude/latitude). +Every rebuilt geometry is checked again and written only when it is valid. A hole or part narrower than one step of that grid in any direction can be rounded onto a single line of it and lose its area, depending on where it lies between the grid's lines. Rounding moves a From d730bc95b5a9f4e9bf42924fbe0139debbf84248 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 21:20:05 +0100 Subject: [PATCH 3/4] Review: Join Field's accepted names for its target decide the system; a saved EPSG:3857 or 4326 reads as Web Mercator or longitude/latitude --- crates/data/src/raster/crs.rs | 13 ++++++++++++- crates/engine/src/cmd/gp.rs | 12 ++++++++---- crates/engine/src/tests/held_layers.rs | 5 +++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index ba55f07693..46d6b6df56 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -330,7 +330,9 @@ impl TryFrom for Crs { Ok(match s { SavedCrs::LonLat => Crs::LonLat, SavedCrs::WebMercator => Crs::WebMercator, - SavedCrs::Epsg(e) => Crs::Epsg(e), + // A code another variant stands for (4326, 3857 and its aliases), as a file written + // by hand or by another program may give it, is that variant, as `from_epsg` gives it. + SavedCrs::Epsg(e) => Crs::from_epsg(u32::from(e)).unwrap_or(Crs::Epsg(e)), SavedCrs::Proj { proj4, label, wkt } => Crs::custom(CustomCrs { proj4, label, wkt, ..CustomCrs::default() })?, }) } @@ -2464,6 +2466,15 @@ mod tests { /// An ESRI code reads as the system the picker offers for it (`ESRI:102033`, as a `.prj` and /// the coordinate system boxes name it); one the catalog lacks is refused with its name. + /// 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] + fn a_saved_code_another_variant_stands_for_reads_as_it() { + for (code, crs) in [(3857, Crs::WebMercator), (3785, Crs::WebMercator), (4326, Crs::LonLat), (32632, Crs::Epsg(32632))] { + assert_eq!(Crs::try_from(SavedCrs::Epsg(code)), Ok(crs), "EPSG:{code}"); + } + } + #[test] fn an_esri_code_is_read() { for text in ["ESRI:102033", "esri:102033", " ESRI : 102033 "] { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 722e935830..8be7010017 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1459,15 +1459,19 @@ fn work_system( ) -> Crs { use rustgis_analysis::ParamKind as K; let Some(spec) = spec.filter(|t| t.works_in_own_system()) else { return Crs::LonLat }; - // The tool's first layer parameter, as it names it: a table given by its number (read - // unconverted, [`Inputs::table`]) or a layer named under another key (Join Field's `input`) - // leaves the run in longitude/latitude, as before. + // 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`]) leaves the run in + // longitude/latitude, as before. let Some(kind) = spec.params.iter().find(|p| matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers)) else { return Crs::LonLat; }; - let value = params.get(kind.name).unwrap_or(&Value::Null); + let aliases = rustgis_analysis::param_aliases(spec, kind.name); + let keys: &[&str] = if aliases.is_empty() { std::slice::from_ref(&kind.name) } else { aliases }; + let blank = |v: &&Value| v.is_null() || v.as_str().is_some_and(|s| s.trim().is_empty()); + let value = keys.iter().filter_map(|k| params.get(*k)).find(|v| !blank(v)).unwrap_or(&Value::Null); let first = if kind.kind == K::VectorLayers { rustgis_analysis::layer_list(value).ok().and_then(|v| v.first().copied()) } else { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 190df8f9a3..371eb36f65 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1508,4 +1508,9 @@ fn a_table_joins_onto_a_held_layer() { assert_eq!(owner(&ss[1]).first().map(String::as_str), Some("owner 0")); assert_eq!(ss[1].map().layer_by_name("Owned").unwrap().dataset.coord_crs(), UTM); assert_eq!(bits(&held_coords(&ss[1], "Owned")), bits(&held_coords(&ss[1], "Parcels"))); + // Named under a name Join Field also accepts for its target, the layer decides the system too. + let p = json!({"tool": "joinField", "params": {"input": "Parcels", "targetField": "n", "join": "Owners", "joinField": "n", "output": "Owned_2"}}); + ss[1].run("gp.run", &p).unwrap(); + assert_eq!(ss[1].map().layer_by_name("Owned_2").unwrap().dataset.coord_crs(), UTM); + assert_eq!(bits(&held_coords(&ss[1], "Owned_2")), bits(&held_coords(&ss[1], "Parcels"))); } From 94d422d3cb55311b078ce24c493ebc681748dab5 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sat, 21 Nov 2026 21:51:21 +0100 Subject: [PATCH 4/4] Review: a layer read only for its attributes (Join Field's join table) is read as it is and doesn't decide the system; fixture for EPSG-coded Web Mercator and lon/lat; doc fixes --- crates/analysis/src/lib.rs | 7 + crates/data/src/raster/crs.rs | 4 +- crates/engine/src/cmd/gp.rs | 55 ++++- crates/engine/src/tests/held_layers.rs | 38 +++ schema/fixtures/held_epsg_variants.rgis | 293 ++++++++++++++++++++++++ 5 files changed, 389 insertions(+), 8 deletions(-) create mode 100644 schema/fixtures/held_epsg_variants.rgis diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index a1bd36f722..9843f47933 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -258,6 +258,13 @@ impl ToolSpec { pub fn works_in_own_system(&self) -> bool { OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) } + + /// 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. + pub fn reads_geometry_of(&self, param: &str) -> bool { + !(self.id == "joinField" && param == "joinTable") + } } /// Runs an external tool (the spec says which). diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 46d6b6df56..772b6e408c 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -2464,8 +2464,6 @@ impl Transformer { mod tests { use super::*; - /// An ESRI code reads as the system the picker offers for it (`ESRI:102033`, as a `.prj` and - /// the coordinate system boxes name it); one the catalog lacks is refused with its name. /// 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] @@ -2475,6 +2473,8 @@ mod tests { } } + /// An ESRI code reads as the system the picker offers for it (`ESRI:102033`, as a `.prj` and + /// the coordinate system boxes name it); one the catalog lacks is refused with its name. #[test] fn an_esri_code_is_read() { for text in ["ESRI:102033", "esri:102033", " ESRI : 102033 "] { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 8be7010017..77e89f7f5a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1235,6 +1235,9 @@ struct MapInputs<'a> { /// The system the tool works in ([`work_system`]): the one its inputs are given in and its /// outputs are made in. work: Crs, + /// The layers (by lowercase name) it reads only the attributes of, read as they are + /// ([`attributes_only`]); none when it works in longitude/latitude. + unread: std::collections::HashSet, /// Import warnings from local file inputs, kept in the tool result and history. messages: Vec, losses: Vec, @@ -1324,7 +1327,18 @@ fn inputs_of<'a>(snap: Snapshot<'a>, spec: Option<&rustgis_analysis::ToolSpec>, let work = work_inputs(&snap.map, &snap.tables, spec, params, &mut full, &mut messages)?; let mut rows = env_inputs(&snap.map, &full, &snap.env, params)?; narrow_to_queries(&snap.map, spec, params, &full, &mut rows, &mut messages)?; - Ok(MapInputs { snap, rows, loaded: full, work, messages, losses, flat: std::cell::OnceCell::new(), view: std::cell::OnceCell::new() }) + let unread = if work == Crs::LonLat { std::collections::HashSet::new() } else { attributes_only(spec, params) }; + Ok(MapInputs { + snap, + rows, + loaded: full, + work, + unread, + messages, + losses, + flat: std::cell::OnceCell::new(), + view: std::cell::OnceCell::new(), + }) } /// Narrows the rows a tool reads of each layer to the features its definition query keeps, as the @@ -1461,8 +1475,8 @@ fn work_system( let Some(spec) = spec.filter(|t| t.works_in_own_system()) 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`]) leaves the run in - // longitude/latitude, as before. + // given by its number (read unconverted, [`Inputs::table`]) or by name leaves the run in + // longitude/latitude, as before: only a map layer decides the system. let Some(kind) = spec.params.iter().find(|p| matches!(p.kind, K::Layer | K::PolygonLayer | K::PointLayer | K::VectorLayer | K::VectorLayers)) else { @@ -1487,6 +1501,26 @@ fn work_system( .unwrap_or(Crs::LonLat) } +/// The layers (by lowercase name) whose attributes alone a tool reads, given under a parameter +/// whose geometry it doesn't read ([`ToolSpec::reads_geometry_of`]) or one of the names it also +/// accepts for it: they are read as they are, in whatever system, so a place of theirs the system +/// it works in can't hold doesn't send it to longitude/latitude. +/// +/// [`ToolSpec::reads_geometry_of`]: rustgis_analysis::ToolSpec::reads_geometry_of +fn attributes_only(spec: Option<&rustgis_analysis::ToolSpec>, params: &Value) -> std::collections::HashSet { + let Some(spec) = spec else { return std::collections::HashSet::new() }; + spec.params + .iter() + .filter(|p| !spec.reads_geometry_of(p.name)) + .flat_map(|p| { + 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) + .collect() +} + /// 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 @@ -1531,7 +1565,13 @@ fn inputs_in( work: Crs, ) -> Result, String> { let mut converted = std::collections::HashMap::new(); + // 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) }; for (key, ds) in full { + if unread.contains(key) { + continue; + } if let std::borrow::Cow::Owned(c) = ds.in_crs(work)? { converted.insert(key.clone(), c); } @@ -1554,7 +1594,7 @@ fn inputs_in( } for n in names { let key = n.to_ascii_lowercase(); - if full.contains_key(&key) || converted.contains_key(&key) { + if full.contains_key(&key) || converted.contains_key(&key) || unread.contains(&key) { continue; } // A layer, or a standalone table with geometry; one without reads alike in any system. @@ -1686,9 +1726,12 @@ impl Inputs for MapInputs<'_> { .or_else(|| { project_input(&self.snap.map, &self.snap.tables, layer, false) .map(|i| i.dataset()) - // A table without geometry reads alike in any system. + // A table without geometry reads alike in any system, and so does a layer + // the tool reads only the attributes of. .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(&layer.to_ascii_lowercase()) + || 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 371eb36f65..45e7be106f 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1514,3 +1514,41 @@ fn a_table_joins_onto_a_held_layer() { assert_eq!(ss[1].map().layer_by_name("Owned_2").unwrap().dataset.coord_crs(), UTM); assert_eq!(bits(&held_coords(&ss[1], "Owned_2")), bits(&held_coords(&ss[1], "Parcels"))); } + +/// Join Field reads only the attributes of its join table, so a place there that UTM can't hold +/// (99°E on the equator, see [`an_input_the_first_ones_system_cant_hold_is_worked_on_in_lonlat`]) +/// doesn't send the run to longitude/latitude: the parcels keep their stored coordinates. +#[test] +fn a_join_tables_places_dont_decide_the_system() { + let mut s = session(UTM); + let mut far = Dataset::new("Far", GeometryType::Point, vec![Field::new("n", FieldType::Integer), Field::new("owner", FieldType::Text)]); + far.push(Some(Geometry::Point(Coord::new(99.0, 0.0))), vec![Cell::Int(0), Cell::Text("far owner".into())]); + s.map_mut().add_dataset(far); + let mark = s.notice_mark(); + let p = json!({"tool": "joinField", "params": {"target": "Parcels", "targetField": "n", "joinTable": "Far", "joinField": "n", "output": "Owned"}}); + 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:?}"); + assert_eq!(s.map().layer_by_name("Owned").unwrap().dataset.coord_crs(), UTM); + 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"); +} + +/// A project giving Web Mercator and longitude/latitude as their EPSG codes (`{"Epsg": 3857}`, +/// `{"Epsg": 4326}`), as one written by hand or by another program may, opens with them as +/// RustGIS's own Web Mercator and longitude/latitude: the layer held in Web Mercator stays off the +/// projected path tools take, and the other is in longitude/latitude. +#[test] +fn the_epsg_variants_fixture_opens_as_rustgis_own_systems() { + let p = Project::from_json(include_str!("../../../../schema/fixtures/held_epsg_variants.rgis")).unwrap(); + let (mercator, plain) = (&p.maps[0].layers[0].dataset, &p.maps[0].layers[1].dataset); + assert_eq!((mercator.coord_crs(), mercator.crs), (Crs::WebMercator, Some(Crs::LonLat))); + assert_eq!((plain.coord_crs(), plain.crs), (Crs::LonLat, Some(Crs::WebMercator))); + // echo 48.7 11.5 | cs2cs -f %.6f EPSG:4326 EPSG:3857 (PROJ 9.9.0): 1280174.144123 6224110.131660 + let Some(Geometry::Point(c)) = mercator.features.first().and_then(|f| f.geometry.clone()) else { panic!("a point") }; + assert!((c.x - 1_280_174.144_123).abs() < 1e-6 && (c.y - 6_224_110.131_660).abs() < 1e-6, "{c:?}"); + let back = mercator.in_lonlat().unwrap(); + 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:?}"); +} diff --git a/schema/fixtures/held_epsg_variants.rgis b/schema/fixtures/held_epsg_variants.rgis new file mode 100644 index 0000000000..5113b6729a --- /dev/null +++ b/schema/fixtures/held_epsg_variants.rgis @@ -0,0 +1,293 @@ +{ + "requires": [ + "native-coordinates" + ], + "format": 2, + "name": "Systems saved as the EPSG codes of Web Mercator and longitude/latitude", + "maps": [ + { + "name": "Map", + "layers": [ + { + "id": 1, + "name": "Wells", + "visible": true, + "dataset": { + "name": "Wells", + "geometry_type": "Point", + "fields": [ + { + "name": "name", + "ty": "Text", + "alias": null + }, + { + "name": "n", + "ty": "Integer", + "alias": null + } + ], + "features": [ + { + "id": 1, + "geometry": { + "Point": { + "x": 1280174.1441226462, + "y": 6224110.131660086 + } + }, + "attrs": [ + { + "Text": "w0" + }, + { + "Int": 0 + } + ] + } + ], + "source": null, + "crs": { + "Epsg": 4326 + }, + "held_in": { + "Epsg": 3857 + } + }, + "renderer": { + "Single": { + "fill": [ + 224, + 123, + 57, + 255 + ], + "stroke": [ + 255, + 255, + 255, + 255 + ], + "stroke_width": 1.0, + "size": 7.0, + "marker": "Circle" + } + }, + "labels": { + "enabled": false, + "field": "name", + "size": 10.0, + "color": [ + 43, + 43, + 43, + 255 + ], + "halo": true, + "bold": false, + "min_scale": null, + "max_scale": null, + "closest": null, + "farthest": null, + "placement": "Auto" + }, + "transparency": 0.0, + "min_scale": null, + "max_scale": null, + "definition_query": null, + "selection": [], + "expanded": true, + "selectable": true, + "graphics": false, + "blend": "Normal", + "mask": null, + "display_filters": [], + "aggregation": null, + "extrusion": null, + "priority": 0, + "geometry_rev": 0 + }, + { + "id": 101, + "name": "Plain", + "visible": true, + "dataset": { + "name": "Plain", + "geometry_type": "Point", + "fields": [ + { + "name": "name", + "ty": "Text", + "alias": null + }, + { + "name": "n", + "ty": "Integer", + "alias": null + } + ], + "features": [ + { + "id": 1, + "geometry": { + "Point": { + "x": 11.5, + "y": 48.7 + } + }, + "attrs": [ + { + "Text": "w0" + }, + { + "Int": 0 + } + ] + } + ], + "source": null, + "crs": { + "Epsg": 3857 + }, + "held_in": { + "Epsg": 4326 + } + }, + "renderer": { + "Single": { + "fill": [ + 224, + 123, + 57, + 255 + ], + "stroke": [ + 255, + 255, + 255, + 255 + ], + "stroke_width": 1.0, + "size": 7.0, + "marker": "Circle" + } + }, + "labels": { + "enabled": false, + "field": "name", + "size": 10.0, + "color": [ + 43, + 43, + 43, + 255 + ], + "halo": true, + "bold": false, + "min_scale": null, + "max_scale": null, + "closest": null, + "farthest": null, + "placement": "Auto" + }, + "transparency": 0.0, + "min_scale": null, + "max_scale": null, + "definition_query": null, + "selection": [], + "expanded": true, + "selectable": true, + "graphics": false, + "blend": "Normal", + "mask": null, + "display_filters": [], + "aggregation": null, + "extrusion": null, + "priority": 0, + "geometry_rev": 0 + } + ], + "basemap": "Paper", + "camera": { + "center": { + "x": 0.0, + "y": 2000000.0 + }, + "res": 30000.0, + "bearing": 0.0, + "pitch": 0.0 + }, + "bookmarks": [], + "graticule": true, + "projection": "WebMercator", + "popup_mode": "Topmost", + "label_display": { + "paused": false, + "locked": false, + "show_unplaced": false + }, + "editing": { + "relationships": [], + "snapping": { + "enabled": false, + "tolerance_px": 10.0, + "vertex": true, + "edge": true, + "end": true + }, + "topology": [], + "settings": { + "enabled": true, + "show_vertices": true, + "elevation": "None", + "ground_to_grid": null + } + }, + "swipe": null, + "view": { + "effects": { + "stars": true, + "sun_time": null, + "weather": "None", + "vignette": false, + "edges": false, + "tilt_shift": false, + "grain": false, + "brightness": 0.0, + "contrast": 0.0, + "saturation": 0.0, + "sepia": 0.0 + }, + "wireframe": false, + "clip_distance": null, + "terrain": null + }, + "animation": [], + "next_layer_id": 2 + } + ], + "active_map": 0, + "tables": [], + "next_table_id": 1, + "gp_history": [], + "layouts": [], + "folders": [], + "styles": [], + "ramps": [], + "tasks": [], + "gp_env": { + "extent": null, + "cell_size": null + }, + "models": [], + "workspaces": [], + "link_views": false, + "jobs": [], + "offline_areas": [], + "reports": [], + "presentations": [], + "notebooks": [], + "dl_models": [], + "shared": [], + "data_stores": [] +}