From 2cdb6960ac6ded68fb328158595d179188773ca7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 12:20:01 +0100 Subject: [PATCH 1/4] feat(crs): a dataset holds its coordinates in a system of its own; commands work from it (#2032 C2a) Dataset::held_in (longitude/latitude for every dataset read or made today) replaces the test-only override of coord_crs; Dataset::hold_in converts a dataset into another system. A project still saves features in longitude/latitude, so older releases read it unchanged. Engine tests run commands on layers held in UTM 32N against the same layers in longitude/latitude. They found, and this fixes, places that read stored coordinates as longitude/latitude: the globe, the layer mask on it and perpendicular labels, rasterize and raster clip, STL/OBJ meshes, the glTF scene, the mobile package's simplification, the layout locator sketch, block diagram contacts, terrain water, a layer made from the selection, labels converted to annotation, the STAC search area, profiles, spectral zones, supervised classification and deep-learning training samples, interpolation, routes, simulated points, photos added to a layer and plugin tool inputs. --- crates/data/src/io.rs | 9 +- crates/data/src/lib.rs | 144 ++++--- crates/data/src/publish.rs | 2 +- crates/engine/src/cmd/imagery.rs | 27 +- crates/engine/src/cmd/items.rs | 22 +- crates/engine/src/cmd/labels.rs | 13 +- crates/engine/src/cmd/layer.rs | 8 +- crates/engine/src/cmd/layout.rs | 11 +- crates/engine/src/cmd/plugins.rs | 1 + crates/engine/src/cmd/select.rs | 2 + crates/engine/src/cmd/sharing.rs | 3 + crates/engine/src/cmd/stac_area.rs | 10 +- crates/engine/src/cmd/whole.rs | 14 +- crates/engine/src/cmd/workflows.rs | 17 +- crates/engine/src/cmd/workspace.rs | 19 +- crates/engine/src/project.rs | 3 + crates/engine/src/tests.rs | 3 + crates/engine/src/tests/held_layers.rs | 516 +++++++++++++++++++++++++ crates/map/src/lib.rs | 56 ++- crates/plugins/src/tools.rs | 6 +- crates/render/src/block.rs | 5 +- crates/render/src/lib.rs | 24 +- crates/render/src/terrain/water.rs | 5 +- xtask/row-uses.txt | 2 +- 24 files changed, 804 insertions(+), 118 deletions(-) create mode 100644 crates/engine/src/tests/held_layers.rs diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c501e20b87..259f2470a4 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -629,6 +629,7 @@ pub fn project(ds: &Dataset, crs: Crs) -> Result { let mut out = ds.clone(); let to = from.to(crs).map_err(DataError::Format)?; project_features(&mut out.features, &to)?; + out.held_in = crs; Ok(out) } @@ -685,6 +686,9 @@ pub fn define_projection(ds: &Dataset, crs: Crs) -> Result { f.geometry = Some(g); } } + // Its coordinates read in `crs` and are held in longitude/latitude, as every dataset's are + // until #2032 C2 lets a layer hold its own system (defining one then only relabels it). + out.held_in = Crs::LonLat; out.crs = Some(crs); Ok(out) } @@ -7894,7 +7898,7 @@ mod tests { let at = utm.transformer().unwrap().from_lonlat(lonlat).unwrap(); let mut ds = Dataset::new("held", GeometryType::Point, vec![]); ds.push(Some(Geometry::Point(at)), vec![]); - let _held = crate::tests::HeldIn::new(utm); + ds.held_in = utm; assert_eq!(ds.coord_crs(), utm); // GeoJSON: longitude/latitude. let (bytes, _) = write_bytes_in(&ds, "geojson", Crs::LonLat).unwrap(); @@ -7937,7 +7941,7 @@ mod tests { } let want = export_losses_notes(&lonlat, "csv", None, "out.csv").unwrap(); let held = project(&lonlat, utm).unwrap(); - let _held = crate::tests::HeldIn::new(utm); + assert_eq!(held.coord_crs(), utm); assert_eq!(export_losses_notes(&held, "csv", None, "out.csv").unwrap(), want); // A line with a missing coordinate: its vertex is left out of a Shapefile written as // held, and noted; in any other system the export's conversion refuses the line instead @@ -7945,6 +7949,7 @@ mod tests { let mut line = Dataset::new("line", GeometryType::Polyline, vec![]); let parts = vec![vec![Coord::new(500_000.0, 5_400_000.0), Coord::new(f64::NAN, 5_400_100.0), Coord::new(500_100.0, 5_400_200.0)]]; line.push(Some(Geometry::Line(parts)), vec![]); + line.held_in = utm; let own = shapefile_geometry_notes(&line, "out.shp", utm); assert!(own.iter().any(|n| n.contains("1 vertex with a missing or infinite coordinate")), "{own:?}"); assert!(shapefile_geometry_notes(&line, "out.shp", Crs::Epsg(25832)).is_empty()); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 30f48ded2a..16658617ca 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -402,8 +402,9 @@ impl<'de> Deserialize<'de> for Features { } /// A feature class: a named table of features sharing a schema and geometry type. -/// Geometry coordinates are always WGS 84 longitude/latitude, including datasets created by -/// tools and plugins. Projected source coordinates must be normalized before insertion. +/// Its geometry is in the system it holds its coordinates in ([`Dataset::held_in`]): WGS 84 +/// longitude/latitude for every dataset read or made today, including those of tools and +/// plugins (#2032 C2 lets readers hold a file's own system). #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Dataset { pub name: String, @@ -413,8 +414,8 @@ pub struct Dataset { /// Where it was read from, if anywhere. #[serde(default)] pub source: Option, - /// The coordinate system it was read in, when that isn't longitude/latitude. Its geometry is - /// always longitude/latitude; this is what an export writes by default. + /// The coordinate system it was read in, when that isn't longitude/latitude: what an export + /// writes by default. Its geometry is in [`Dataset::held_in`], longitude/latitude today. #[serde(default, skip_serializing_if = "Option::is_none")] pub crs: Option, /// Import lost geometry while interpreting source coordinates. Defining a projection cannot @@ -429,21 +430,60 @@ pub struct Dataset { /// so they aren't saved: the source is read again instead. #[serde(skip)] pub windowed: bool, + /// The system its geometry is in ([`Dataset::coord_crs`]): longitude/latitude unless it was + /// put in another with [`Dataset::hold_in`]. A project saves its features in + /// longitude/latitude, as older releases read them, so a saved dataset reads back held there. + #[serde(skip, default = "held_in_lonlat")] + pub held_in: raster::Crs, +} + +/// What a dataset read from a project holds its coordinates in ([`Dataset::held_in`]). +fn held_in_lonlat() -> raster::Crs { + raster::Crs::LonLat } impl Dataset { - /// The coordinate system its geometry is in: longitude/latitude (WGS 84), as every dataset's - /// is today, whatever system it was read in ([`Dataset::crs`]). Drawing converts geometry from - /// it ([`raster::Crs::to`]), so a dataset that keeps the coordinates it was read in can say so - /// here without the map changing. Longitude/latitude never fails to convert. The map draws none of - /// a layer whose conversion fails (`Layer::projected_in`) and doesn't say so yet: before this - /// returns another system, that needs a notice, as AGENTS.md's "Never silent" asks. + /// The coordinate system its geometry is in ([`Dataset::held_in`]): longitude/latitude (WGS 84) + /// for every dataset read or made today, whatever system it was read in ([`Dataset::crs`]). + /// Drawing converts geometry from it ([`raster::Crs::to`]), so a dataset that keeps the + /// coordinates it was read in can say so here without the map changing. Longitude/latitude + /// never fails to convert, and [`Dataset::hold_in`] only holds a dataset where every place + /// converts. The map draws none of a layer whose conversion fails (`Layer::projected_in`) and + /// doesn't say so yet: before a reader holds a file's own system (#2032 C2b), that needs a + /// notice, as AGENTS.md's "Never silent" asks. pub fn coord_crs(&self) -> raster::Crs { - #[cfg(test)] - if let Some(held) = tests::held_in() { - return held; + self.held_in + } + + /// Converts its geometry into `crs` and holds it there ([`Dataset::held_in`]); a missing + /// coordinate (NaN, infinite) stays as it is. Refused, naming the first feature, when its + /// system can't be converted to `crs` or one of its places can't be held there (in Web + /// Mercator, one past 85.05°, which it would hold at 85.05°); and for a window onto a source + /// read in place, whose rows are read again in longitude/latitude. Nothing changes then. + pub fn hold_in(&mut self, crs: raster::Crs) -> std::result::Result<(), String> { + if self.windowed && crs != self.held_in { + return Err(format!("{}: a layer read in place is held as its source is read", self.name)); } - raster::Crs::LonLat + let to = self.held_in.to(crs)?; + if !to.is_identity() { + let lonlat = self.lonlat_conversion()?; + let mut features = self.features.clone(); + for f in &mut features { + if let Some(g) = &f.geometry { + let mut past = false; + if crs == raster::Crs::WebMercator { + g.for_each_coord(|c| past |= c.is_finite() && lonlat.point(c).is_some_and(|l| l.y.abs() > rustgis_geom::MAX_LAT)); + } + let held = (!past).then(|| convert_keeping_missing(&to, g, &HeldPlaces::default())).flatten(); + f.geometry = Some( + held.ok_or_else(|| format!("{}: feature {} has a place that can't be held in {}", self.name, f.id, crs.label()))?, + ); + } + } + self.features = features; + } + self.held_in = crs; + Ok(()) } /// One of its geometries in longitude/latitude, the space edits work in (a vertex dragged to a @@ -537,7 +577,11 @@ impl Serialize for Dataset { st.serialize_field("geometry_type", &self.geometry_type)?; st.serialize_field("fields", &self.fields)?; let none: &[Feature] = &[]; - st.serialize_field("features", if self.windowed { none } else { self.features.as_slice() })?; + // In longitude/latitude, as every release reads a saved dataset's features. A place that + // can't be given there fails the save, naming its feature, rather than being saved + // wrong; `hold_in` only holds a dataset whose places all convert. + let lonlat = if self.windowed { None } else { Some(self.in_lonlat().map_err(serde::ser::Error::custom)?) }; + st.serialize_field("features", lonlat.as_ref().map_or(none, |d| d.features.as_slice()))?; st.serialize_field("source", &self.source)?; if let Some(crs) = &self.crs { st.serialize_field("crs", crs)?; @@ -848,6 +892,7 @@ impl Dataset { crs_incomplete: false, zm_dropped: false, windowed: false, + held_in: raster::Crs::LonLat, } } @@ -924,15 +969,15 @@ impl Dataset { /// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its /// coordinates are longitude/latitude ([`Dataset::coord_crs`]), as every dataset's are today; /// 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. Once a dataset - /// records its own system (C2 of #2032), the copy is to be recorded as longitude/latitude, so - /// that it isn't converted again. + /// the first feature that can't be, when one of its places can't be converted. The copy is + /// held in longitude/latitude ([`Dataset::held_in`]), so it isn't converted again. pub fn in_lonlat(&self) -> std::result::Result, String> { let to = self.lonlat_conversion()?; if to.is_identity() { return Ok(Cow::Borrowed(self)); } let mut out = self.clone(); + out.held_in = raster::Crs::LonLat; for f in &mut out.features { if let Some(g) = &mut f.geometry { *g = convert_keeping_missing(&to, g, &HeldPlaces::default()).ok_or_else(|| { @@ -980,6 +1025,7 @@ impl Dataset { f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); } } + results.held_in = self.held_in; Ok(results) } @@ -1149,32 +1195,36 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP mod tests { use super::*; - thread_local! { - /// The system this thread's tests hold every dataset's coordinates in ([`HeldIn`]). - static HELD_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; - } - - /// What [`Dataset::coord_crs`] says on this thread while a [`HeldIn`] is alive: what a dataset - /// that keeps the coordinates it was read in (#2032 C2) will say, for the paths that convert - /// from it to be tried before it does. - pub(crate) fn held_in() -> Option { - HELD_IN.try_with(std::cell::Cell::get).ok().flatten() - } - - /// Every dataset on this thread is taken to hold its coordinates in a system until dropped, - /// on the thread that made it (it can't be sent to another). - pub(crate) struct HeldIn(Option, std::marker::PhantomData<*const ()>); - - impl HeldIn { - pub(crate) fn new(crs: raster::Crs) -> HeldIn { - HeldIn(HELD_IN.with(|h| h.replace(Some(crs))), std::marker::PhantomData) - } - } - - impl Drop for HeldIn { - fn drop(&mut self) { - let _ = HELD_IN.try_with(|h| h.set(self.0)); - } + /// A dataset held in another system converts into it, and back, at the same places; one + /// reaching past where Web Mercator ends, or a window onto a source read in place, is refused + /// and left as it was. + #[test] + fn a_dataset_is_held_where_its_places_convert() { + let utm = raster::Crs::Epsg(32632); + let mut ds = Dataset::new("held", GeometryType::Point, vec![]); + ds.push(Some(Geometry::Point(Coord::new(11.5, 48.7))), vec![]); + ds.push(Some(Geometry::Point(Coord::new(f64::NAN, 48.7))), vec![]); + let plain = ds.clone(); + ds.hold_in(utm).unwrap(); + assert_eq!(ds.coord_crs(), utm); + let Some(Geometry::Point(p)) = ds.features[0].geometry else { panic!("a point") }; + assert_eq!(Some(p), utm.transformer().unwrap().from_lonlat(Coord::new(11.5, 48.7))); + assert!(matches!(ds.features[1].geometry, Some(Geometry::Point(c)) if c.x.is_nan())); + ds.hold_in(raster::Crs::LonLat).unwrap(); + let Some(Geometry::Point(back)) = ds.features[0].geometry else { panic!("a point") }; + assert!((back.x - 11.5).abs() < 1e-9 && (back.y - 48.7).abs() < 1e-9, "{back:?}"); + // Past 85.05°: refused, nothing changed. + let mut polar = plain.clone(); + polar.push(Some(Geometry::Point(Coord::new(0.0, 89.0))), vec![]); + let before = polar.clone(); + let err = polar.hold_in(raster::Crs::WebMercator).unwrap_err(); + assert!(err.contains("feature 3"), "{err}"); + assert_eq!(polar, before); + // A window onto a source is read again in longitude/latitude. + let mut window = plain; + window.windowed = true; + assert!(window.hold_in(utm).is_err()); + assert_eq!(window.coord_crs(), raster::Crs::LonLat); } /// An export in Web Mercator counts the places past where it ends by their latitude, from the @@ -1182,12 +1232,12 @@ mod tests { #[test] fn web_mercators_end_is_counted_by_latitude() { let utm = raster::Crs::Epsg(32632); - let t = utm.transformer().unwrap(); let mut ds = Dataset::new("held", GeometryType::Point, vec![]); for lat in [48.7, 86.0] { - ds.push(Some(Geometry::Point(t.from_lonlat(Coord::new(9.0, lat)).unwrap())), vec![]); + ds.push(Some(Geometry::Point(Coord::new(9.0, lat))), vec![]); } - let _held = HeldIn::new(utm); + ds.hold_in(utm).unwrap(); + assert_eq!(ds.coord_crs(), utm); let note = web_mercator_note(&[(&ds, ds.extent())], "out.gpkg").unwrap_or_default(); assert_eq!(note, web_mercator_said(&[("held", Some(1))], "out.gpkg").unwrap_or_default()); assert!(!note.is_empty()); diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index db0da53a85..3f1d901b8c 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -793,7 +793,7 @@ mod tests { let at = Coord::new(500_000.0, 5_400_000.0); let mut ds = Dataset::new("held", GeometryType::Point, vec![]); ds.push(Some(Geometry::Point(at)), vec![]); - let _held = crate::tests::HeldIn::new(utm); + ds.held_in = utm; let same = in_file(&ds, Some(utm), None).unwrap(); assert!(matches!(same, std::borrow::Cow::Borrowed(_))); let other = in_file(&ds, Some(etrs), Some((&ds, &ds))).unwrap(); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 552520c2d2..d1d036916f 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -453,6 +453,19 @@ fn report_resampled_classes(s: &mut Session, source: &Raster, out: &Raster, meth /// The largest whole number a raster's 32-bit float pixels hold exactly. const EXACT_WHOLE: f64 = 16_777_216.0; +/// The conversion of a layer's own coordinates to longitude/latitude, for polygons read one by +/// one ([`rasterops::transform_feature_polygons_to_lonlat`]): none while they are +/// longitude/latitude, as they are unless the layer holds another system. The same operation +/// as [`rustgis_data::Dataset::lonlat_conversion`]'s: a conversion to longitude/latitude is the +/// system's own, never a direct one between two others. +fn held_transformer(ds: &rustgis_data::Dataset) -> Result, String> { + let crs = ds.coord_crs(); + if crs == Crs::LonLat { + return Ok(None); + } + crs.transformer().map(Some).map_err(|e| format!("{}: {e}", ds.name)) +} + /// `raster.rasterize`: a polygon layer's selected (or all) features burned onto a grid given as /// `raster.project`'s is, each cell whose centre falls in a polygon taking its field's value, a /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and @@ -491,10 +504,12 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { rows.dedup(); let (mut no_value, mut no_polygon) = (0, 0); let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + // Burned from longitude/latitude, whatever system the layer holds its coordinates in. + let own = held_transformer(ds)?; for row in rows { let Some(feature) = ds.features.get(row) else { continue }; let parts = match &feature.geometry { - Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, None).ok(), + Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()).ok(), _ => None, }; let Some(parts) = parts else { @@ -1035,7 +1050,11 @@ fn zone_rings(s: &Session, z: &str) -> Result>, String> { let l = s.map().layer_by_name(z).filter(|l| l.geometry_type() == GeometryType::Polygon).ok_or_else(|| format!("no polygon layer '{z}'"))?; let row = l.selection.first().copied().unwrap_or(0); - let Some(Geometry::Polygon(polys)) = l.dataset.features.get(row).and_then(|f| f.geometry.as_ref()) else { + let Some(g) = l.dataset.features.get(row).and_then(|f| f.geometry.as_ref()) else { + return Err("the zone has no polygon".into()); + }; + // In longitude/latitude, whatever system the layer holds its coordinates in. + let Geometry::Polygon(polys) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{z}: {e}"))? else { return Err("the zone has no polygon".into()); }; polys.first().cloned().ok_or_else(|| "the zone has no polygon".into()) @@ -1230,10 +1249,12 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result>> = Vec::new(); let mut failed_features = Vec::new(); + // In longitude/latitude, whatever system the layer holds its coordinates in. + let own = held_transformer(&l.dataset)?; for &row in &rows { let Some(f) = l.dataset.features.get(row) else { continue }; match &f.geometry { - Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, None) { + Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()) { Ok(transformed) => { polygons.extend(transformed); } diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 98efbe6f43..a26de26267 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -835,6 +835,11 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64) -> Result, Strin if l.is_raster() || tol <= 0.0 { continue; } + // Simplified in longitude/latitude, as the package saves it, whatever system the + // layer holds its coordinates in. + if let std::borrow::Cow::Owned(ds) = l.dataset.in_lonlat()? { + l.dataset = ds; + } for f in &mut l.dataset.features { if let Some(g) = &f.geometry { let (simple, said) = rustgis_analysis::simplify_geometry(g, tol * 111_320.0); @@ -1253,9 +1258,9 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result rustgis_data::progress::check().map_err(|e| e.to_string())?; } // A feature with no geometry draws nothing, so its height is neither used nor reported. - if rows.get(row) != Some(&true) || ft.geometry.is_none() { - continue; - } + let Some(g) = ft.geometry.as_ref().filter(|_| rows.get(row) == Some(&true)) else { continue }; + // Placed from longitude/latitude, whatever system the layer holds its coordinates in. + let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?; // A height that isn't a finite number takes the default, and is counted. let height = match hf { Some(fi) => match l.dataset.value(row, fi).as_f64().filter(|h| h.is_finite()) { @@ -1273,13 +1278,13 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result let below = h < 0.0; let orient = |o: Orient| if below { o.reversed() } else { o }; // A solid of zero height would be two coincident caps facing apart: STL leaves it out. - if !mesh.keep_lines && h == 0.0 && !matches!(ft.geometry, Some(Geometry::Line(_))) { + if !mesh.keep_lines && h == 0.0 && !matches!(&*g, Geometry::Line(_)) { mesh.flat += 1; continue; } let before = mesh.vertices; - match &ft.geometry { - Some(Geometry::Polygon(polys)) => { + match &*g { + Geometry::Polygon(polys) => { for rings in polys { // Each ring open (no closing vertex), outer first then holes. let mut open: Vec> = rings @@ -1344,7 +1349,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result } } } - Some(Geometry::Line(parts)) => { + Geometry::Line(parts) => { for part in parts { let n = part.len(); if n < 2 { @@ -1363,7 +1368,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result mesh.face(Item::Polyline((0..n).map(|i| v + i).collect()))?; } } - Some(g @ (Geometry::Point(_) | Geometry::MultiPoint(_))) => { + g @ (Geometry::Point(_) | Geometry::MultiPoint(_)) => { let pts: Vec = match g { Geometry::Point(c) => vec![*c], Geometry::MultiPoint(c) => c.clone(), @@ -1386,7 +1391,6 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result } } } - None => {} } if mesh.vertices > before { s.constructions.count_feature(s.map().instance_id(), l, ft, &mut mesh.constructions); diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 0c19b73e95..707551d8b6 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -867,11 +867,14 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { out_fields, ); let mut moved = Vec::new(); - for (row, ft) in l.dataset.features.iter().enumerate() { + for (row, ft) in l.dataset.features.rows().enumerate() { if rows.get(row) != Some(&true) { continue; } - let Some(at) = ft.geometry.as_ref().and_then(Geometry::label_point) else { continue }; + // In longitude/latitude, as the annotation layer holds its points and moved labels are. + let Some(g) = ft.geometry() else { continue }; + let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; + let Some(at) = g.label_point() else { continue }; for (i, class) in matcher.classes_of(&l.dataset, row).filter(|(_, c)| c.visible) { let text = match by_text(i).and_then(|e| e.text_cut(&l.dataset, row)) { Some(Some((t, was_cut))) => { @@ -894,7 +897,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { } // A label moved by hand becomes an annotation where it was put, and stays moved there // (its class's offset leaves it). - let put = class.moved_to(ft.id); + let put = class.moved_to(ft.id()); let at = put.map_or(at, |[x, y]| Coord::new(x, y)); let e = exprs.get(i).and_then(Option::as_ref); let number = |v: Option| v.map_or(Attr::Null, |v| Attr::Float(f64::from(v))); @@ -906,11 +909,11 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { attrs.push(c.map_or(Attr::Null, |c| Attr::Text(format!("{},{},{},{}", c.r(), c.g(), c.b(), c.a())))); } if by_angle { - let turns = class.by.angle.is_some() && !along(class, ft.geometry.as_ref()); + let turns = class.by.angle.is_some() && !along(class, ft.geometry()); attrs.push(number(e.filter(|_| turns).and_then(|e| e.angle(&l.dataset, row)))); } ds.push(Some(Geometry::Point(at)), attrs); - let flat = put.is_none() && along(class, ft.geometry.as_ref()); + let flat = put.is_none() && along(class, ft.geometry()); flattened += usize::from(flat); repeated += usize::from(flat && class.repeat.is_some()); if let (Some(put), Some(new)) = (put, ds.features.last()) { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f7aa01f2f4..eb8d501acc 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1831,8 +1831,14 @@ pub(crate) fn add_photos_to(s: &mut Session, name: &str, zoom: Option, fee let id = match existing { Some(id) => { let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; + // Read in longitude/latitude, held in the layer's system. + let mut photos = Vec::new(); for f in ds.features.into_iter().take(added) { - l.dataset.push(f.geometry, f.attrs); + let g = f.geometry.map(|g| l.dataset.geometry_from_lonlat(g)).transpose().map_err(|e| format!("{}: {e}", l.name))?; + photos.push((g, f.attrs)); + } + for (g, attrs) in photos { + l.dataset.push(g, attrs); } l.touch_geometry(); s.active_layer = Some(id); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 1a400d2d99..67c53efe15 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2032,8 +2032,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { layer.gpkg = None; layer.postgis = None; layer.synced = None; - layer.dataset.features = l - .dataset + // Sketched in longitude/latitude, whatever system the layer holds its + // coordinates in. + let lonlat = l.dataset.in_lonlat()?; + layer.dataset.held_in = rustgis_data::raster::Crs::LonLat; + layer.dataset.features = lonlat .features .iter() .map(|f| { @@ -2045,9 +2048,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { layer.touch_geometry(); layer.selection.clear(); layer.labels.enabled = false; - layer + Ok(layer) }) - .collect(); + .collect::>()?; // All but reaching beyond 85.05°, which any world map does (`without_polar`). warnings.extend(notes.get().without_polar().messages("the globe locator, simplifying its polygons")); let name = m.name.clone(); diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 7cde3a425b..94742a503a 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -612,6 +612,7 @@ impl Bridge<'_> { crs_incomplete: false, zm_dropped: false, windowed: false, + held_in: rustgis_data::raster::Crs::LonLat, }; let mut ds = ds; let mut member = None; diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 44c8d95114..4df9aae2f0 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -75,6 +75,8 @@ pub fn commands() -> Vec { return Err("nothing is selected in this layer".into()); } let mut ds = rustgis_data::Dataset::new(format!("{} selection", l.name), l.geometry_type(), l.dataset.fields.clone()); + // Its coordinates as they are, held in the layer's system. + ds.held_in = l.dataset.held_in; for r in &l.selection { if let Some(f) = l.dataset.features.get(*r) { ds.push(f.geometry.clone(), f.attrs.clone()); diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 9818083de6..7850c944cb 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -1091,6 +1091,9 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { scene.limited += 1; continue; } + // Placed from longitude/latitude, whatever system the layer holds its coordinates in. + let lonlat = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?; + let g = &*lonlat; // A position too far for 32 bits would make the scene invalid: the feature is left out, // and said. Only what would be drawn counts (not a degenerate ring or a one-vertex line). let far = |c: &Coord| { diff --git a/crates/engine/src/cmd/stac_area.rs b/crates/engine/src/cmd/stac_area.rs index 88e5fba654..9c98b092da 100644 --- a/crates/engine/src/cmd/stac_area.rs +++ b/crates/engine/src/cmd/stac_area.rs @@ -157,8 +157,14 @@ fn selected(s: &Session, p: &Value) -> Result<(Vec, Vec), Stri if layer.selection.len() > area::MAX_FEATURES { return Err(format!("more than {} features are selected: select fewer or use a bounding box", area::MAX_FEATURES)); } - let geometries: Vec = - layer.selection.iter().filter_map(|row| layer.dataset.features.get(*row)).filter_map(|f| f.geometry.clone()).collect(); + // In longitude/latitude, as a search area is, whatever system the layer holds them in. + let mut geometries: Vec = Vec::new(); + for f in layer.selection.iter().filter_map(|row| layer.dataset.features.row(*row)) { + if let Some(g) = f.geometry() { + let g = layer.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", layer.name, f.id()))?; + geometries.push(g.into_owned()); + } + } let mut notes = Vec::new(); if geometries.len() < layer.selection.len() { notes.push(format!( diff --git a/crates/engine/src/cmd/whole.rs b/crates/engine/src/cmd/whole.rs index 526fb5f7ba..6001946cf5 100644 --- a/crates/engine/src/cmd/whole.rs +++ b/crates/engine/src/cmd/whole.rs @@ -56,16 +56,20 @@ impl Whole { Whole { name: l.name.clone(), rows } } - /// Every feature, with the fields the layer lists (so a field's index in the layer is its - /// index here), and the rows of its source that couldn't be read. A source read a chunk at a - /// time looks at Cancel between chunks; one read at once (a GeoJSON file, a database table) - /// is a single step that doesn't, as for Load All Features. + /// Every feature in longitude/latitude, whatever system the layer holds its coordinates in + /// (its work reads places there), with the fields the layer lists (so a field's index in the + /// layer is its index here), and the rows of its source that couldn't be read. A source read + /// a chunk at a time looks at Cancel between chunks; one read at once (a GeoJSON file, a + /// database table) is a single step that doesn't, as for Load All Features. pub(crate) fn read(self) -> Result<(Dataset, Unread), String> { let Whole { name, rows } = self; - let (ds, unread) = match rows { + let (mut ds, unread) = match rows { Rows::Held(ds) => (ds, Unreadable::default()), Rows::Source(l) => l.load_all_counted().map_err(|e| format!("{name}: {e}"))?, }; + if ds.coord_crs() != rustgis_data::raster::Crs::LonLat { + ds = ds.in_lonlat()?.into_owned(); + } Ok((ds, Unread::of(name, unread))) } } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 39f9847732..481f232cd5 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1567,8 +1567,11 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { // Features without a place or a number are left out, and said (by kind, with a count). let (mut no_point, mut no_value) = (0usize, 0usize); let mut pts: Vec<(Coord, f64)> = Vec::with_capacity(ds.features.len()); + // Each place in longitude/latitude, whatever system the layer holds its coordinates in; one + // that can't be given there has no place. + let to = ds.lonlat_conversion()?; for (r, ft) in ds.features.iter().enumerate() { - let Some(c) = ft.geometry.as_ref().and_then(|g| g.label_point()).filter(|c| c.is_finite()) else { + let Some(c) = ft.geometry.as_ref().and_then(|g| g.label_point()).and_then(|c| to.point(c)).filter(|c| c.is_finite()) else { no_point += 1; continue; }; @@ -1704,8 +1707,11 @@ fn route(s: &mut Session, p: &Value) -> CmdResult { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), rustgis_map::rows::Rows::Subset(rows) => rows, }; + // The network in longitude/latitude, as `from` and `to` are, whatever system the layer holds + // its coordinates in. + let lines = l.dataset.in_lonlat()?; let r = network::shortest_route( - &l.dataset, + &lines, &rows, point(p, "from")?, point(p, "to")?, @@ -1830,6 +1836,9 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), rustgis_map::rows::Rows::Subset(rows) => rows, }; + // Placed in longitude/latitude, as the points' layer holds them, whatever system the polygons' + // layer holds its coordinates in. + let polygons = l.dataset.in_lonlat()?; let seed = f(p, "seed").map_or(42, |v| v.max(0.0) as u64); let pts: Vec<(usize, Coord)> = match ps(p, "field") { Some(fname) => { @@ -1839,7 +1848,7 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { let mut out = Vec::new(); for r in &rows { let n = (l.dataset.value(*r, fi).as_f64().unwrap_or(0.0) * rate).round().clamp(0.0, 100_000.0) as usize; - out.extend(network::random_points(&l.dataset, &[*r], n, seed.wrapping_add(*r as u64))); + out.extend(network::random_points(&polygons, &[*r], n, seed.wrapping_add(*r as u64))); if out.len() > 1_000_000 { return Err("that would make more than a million points; lower the rate".into()); } @@ -1851,7 +1860,7 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { if rows.len().saturating_mul(per) > 1_000_000 { return Err("that would make more than a million points; lower the count".into()); } - network::random_points(&l.dataset, &rows, per, seed) + network::random_points(&polygons, &rows, per, seed) } }; let mut ds = Dataset::new(name, GeometryType::Point, vec![Field::new("polygon", FieldType::Integer)]); diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 2eb91f78b4..7117875216 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -476,14 +476,17 @@ fn selected_lines(s: &Session, p: &Value, all: bool) -> Result>, _ if all => l.selection.clone(), _ => l.selection.iter().take(1).copied().collect(), }; - let out: Vec> = rows - .iter() - .filter_map(|r| match l.dataset.features.get(*r)?.geometry.as_ref()? { - Geometry::Line(parts) => Some(parts.iter().flatten().copied().collect()), - _ => None, - }) - .filter(|v: &Vec| v.len() >= 2) - .collect(); + // Sampled in longitude/latitude, whatever system the layer holds its coordinates in. + let mut out: Vec> = Vec::new(); + for f in rows.iter().filter_map(|r| l.dataset.features.row(*r)) { + let Some(g) = f.geometry().filter(|g| matches!(g, Geometry::Line(_))) else { continue }; + if let Geometry::Line(parts) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{n}: feature {}: {e}", f.id()))? { + let v: Vec = parts.iter().flatten().copied().collect(); + if v.len() >= 2 { + out.push(v); + } + } + } if out.is_empty() { Err("no usable lines".into()) } else { Ok(out) } } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 0b139f025b..7076b21a3c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -528,6 +528,8 @@ impl From for Table { crs_incomplete, zm_dropped, windowed: false, + // Saved in longitude/latitude, as `Dataset`'s own saving writes them. + held_in: rustgis_data::raster::Crs::LonLat, }, } } @@ -2458,6 +2460,7 @@ impl Durable for Table { crs_incomplete: _, zm_dropped: _, windowed: _, + held_in: _, } = dataset; if let Some(v) = provenance { p.string(Leaf::Table, v, true, rustgis_map::paths::is_local(v)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3e518bcf1f..8d847e8190 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -27,6 +27,9 @@ mod block_model; #[path = "tests/write_notices.rs"] mod write_notices; +#[path = "tests/held_layers.rs"] +mod held_layers; + #[path = "tests/task_reentry.rs"] mod task_reentry; diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs new file mode 100644 index 0000000000..d84ac5e746 --- /dev/null +++ b/crates/engine/src/tests/held_layers.rs @@ -0,0 +1,516 @@ +//! Commands on a layer held in its own system (#2032 C2): every one gives what it gives for the +//! same layer held in longitude/latitude. Each test runs a command on both and compares. + +use rustgis_data::raster::Crs; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}; +use serde_json::{Value, json}; + +use crate::{Project, Session}; + +/// A directory of its own for a test's files, removed when dropped. +struct Dir(std::path::PathBuf); + +impl Dir { + fn new(name: &str) -> Dir { + let path = std::env::temp_dir().join(format!("rustgis-held-layers-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Dir(path) + } + + fn path(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// UTM zone 32N, the system the held layers are in. +const UTM: Crs = Crs::Epsg(32632); + +/// How far apart, in degrees, a place may read through UTM and back (well under a millimetre). +const CLOSE: f64 = 1e-8; + +/// Wells (points), Roads (a line) and Parcels (squares) near Ingolstadt, 2.5° east of UTM zone +/// 32N's central meridian (its grid turned some 1.9° from north there), with a name and a number. +fn layers() -> Vec { + let fields = || vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut wells = Dataset::new("Wells", GeometryType::Point, fields()); + let mut parcels = Dataset::new("Parcels", GeometryType::Polygon, fields()); + for i in 0..3 { + for j in 0..3 { + let (x, y) = (11.5 + 0.01 * f64::from(i), 48.7 + 0.01 * f64::from(j)); + let n = i64::from(i * 3 + j); + wells.push(Some(Geometry::Point(Coord::new(x, y))), vec![Cell::Text(format!("w{n}")), Cell::Int(n)]); + let ring = vec![ + Coord::new(x, y), + Coord::new(x + 0.005, y), + Coord::new(x + 0.005, y + 0.005), + Coord::new(x, y + 0.005), + Coord::new(x, y), + ]; + parcels.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![Cell::Text(format!("p{n}")), Cell::Int(n)]); + } + } + let mut roads = Dataset::new("Roads", GeometryType::Polyline, fields()); + let line = vec![Coord::new(11.49, 48.69), Coord::new(11.515, 48.705), Coord::new(11.53, 48.73)]; + roads.push(Some(Geometry::Line(vec![line])), vec![Cell::Text("r0".into()), Cell::Int(0)]); + vec![wells, roads, parcels] +} + +/// A session with [`layers`] held in `crs`. +fn session(crs: Crs) -> Session { + let mut s = Session::new(Project::default()); + for mut ds in layers() { + ds.hold_in(crs).unwrap(); + s.map_mut().add_dataset(ds); + } + s.map_mut().editing.settings.enabled = true; + s +} + +/// The sessions with the layers held in longitude/latitude and in UTM 32N. +fn both() -> [Session; 2] { + [session(Crs::LonLat), session(UTM)] +} + +/// A layer's geometry, read in longitude/latitude. +fn lonlat(s: &Session, layer: &str) -> Vec> { + let l = s.map().layer_by_name(layer).unwrap(); + l.dataset.in_lonlat().unwrap().features.iter().map(|f| f.geometry.clone()).collect() +} + +/// Every coordinate of `a` within [`CLOSE`] of `b`'s, in the same shapes. +fn assert_close(a: &[Option], b: &[Option], what: &str) { + assert_eq!(a.len(), b.len(), "{what}: feature count"); + for (i, (a, b)) in a.iter().zip(b).enumerate() { + let (mut ca, mut cb) = (Vec::new(), Vec::new()); + if let Some(g) = a { + g.for_each_coord(|c| ca.push(c)); + } + if let Some(g) = b { + g.for_each_coord(|c| cb.push(c)); + } + assert_eq!(ca.len(), cb.len(), "{what}: feature {i}'s coordinates"); + for (p, q) in ca.iter().zip(&cb) { + assert!((p.x - q.x).abs() < CLOSE && (p.y - q.y).abs() < CLOSE, "{what}: feature {i}: {p:?} vs {q:?}"); + } + } +} + +/// Runs `cmd` in each session and gives both results. +fn run_both(ss: &mut [Session; 2], cmd: &str, p: &Value) -> [Value; 2] { + let a = ss[0].run(cmd, p).unwrap_or_else(|e| panic!("{cmd} (longitude/latitude): {e}")); + let b = ss[1].run(cmd, p).unwrap_or_else(|e| panic!("{cmd} (UTM): {e}")); + [a, b] +} + +/// The rows of `layer` selected. +fn selected(s: &Session, layer: &str) -> Vec { + let mut v = s.map().layer_by_name(layer).unwrap().selection.clone(); + v.sort_unstable(); + v +} + +/// A held layer reads back in longitude/latitude where it was put, and its extent, a zoom to it +/// and the map's full extent are those of the same layer held in longitude/latitude. +#[test] +fn a_held_layer_has_the_same_extent_and_zoom() { + let mut ss = both(); + assert_eq!(ss[1].map().layer_by_name("Wells").unwrap().dataset.coord_crs(), UTM); + for layer in ["Wells", "Roads", "Parcels"] { + assert_close(&lonlat(&ss[0], layer), &lonlat(&ss[1], layer), layer); + let [a, b] = [&ss[0], &ss[1]].map(|s| s.map().layer_by_name(layer).unwrap().extent()); + // The held layer's is the longitude/latitude box of its UTM box: it holds the other, and + // is a few percent larger, as UTM's grid is turned some 1.9° from north there. + let slack = 0.1 * a.width().max(a.height()); + let ulp = 1e-9; + assert!( + b.min_x <= a.min_x + ulp && b.min_y <= a.min_y + ulp && b.max_x >= a.max_x - ulp && b.max_y >= a.max_y - ulp, + "{layer}: {a:?} vs {b:?}" + ); + assert!(a.min_x - b.min_x < slack && a.min_y - b.min_y < slack, "{layer}: {a:?} vs {b:?}"); + assert!(b.max_x - a.max_x < slack && b.max_y - a.max_y < slack, "{layer}: {a:?} vs {b:?}"); + } + run_both(&mut ss, "layer.zoomTo", &json!({"layer": "Parcels"})); + let [a, b] = [&ss[0], &ss[1]].map(|s| s.map().camera.center); + // Web Mercator metres, on a layer some 2.8 km across: within the extents' difference. + assert!((a.x - b.x).abs() < 5.0 && (a.y - b.y).abs() < 5.0, "{a:?} vs {b:?}"); +} + +/// Selecting by a box, a point, a radius and a polygon picks the same features. +#[test] +fn a_held_layer_is_selected_alike() { + let mut ss = both(); + let picks = [ + ("select.byRect", json!({"minLon": 11.495, "minLat": 48.695, "maxLon": 11.512, "maxLat": 48.712})), + ("select.atPoint", json!({"lon": 11.5125, "lat": 48.7125, "tolerancePx": 0})), + ("select.byRadius", json!({"lon": 11.51, "lat": 48.71, "radius": 900})), + ("select.byPolygon", json!({"points": [[11.495, 48.695], [11.525, 48.695], [11.5, 48.725], [11.495, 48.695]]})), + ]; + for (cmd, p) in picks { + for s in &mut ss { + // Refused when nothing is selected. + let _ = s.run("select.clear", &Value::Null); + } + let [a, b] = run_both(&mut ss, cmd, &p); + assert_eq!(a, b, "{cmd}"); + for layer in ["Wells", "Roads", "Parcels"] { + assert_eq!(selected(&ss[0], layer), selected(&ss[1], layer), "{cmd}: {layer}"); + } + assert!(["Wells", "Parcels"].iter().any(|l| !selected(&ss[0], l).is_empty()), "{cmd} picked nothing"); + } +} + +/// Exports in longitude/latitude and in another system, and a conversion to GeoJSON, write the +/// same places. +#[test] +fn a_held_layer_is_exported_alike() { + let mut ss = both(); + let dir = Dir::new("exports"); + for (ext, crs) in [("geojson", None), ("gpkg", Some("EPSG:25832")), ("shp", Some("EPSG:32632")), ("csv", None)] { + let mut read = Vec::new(); + for (k, s) in ss.iter_mut().enumerate() { + let path = dir.path().join(format!("parcels{k}.{ext}")); + let mut p = json!({"layer": "Parcels", "path": path.display().to_string()}); + if let Some(c) = crs { + p["crs"] = json!(c); + } + s.run("share.exportLayer", &p).unwrap_or_else(|e| panic!("{ext} ({k}): {e}")); + let ds = rustgis_data::io::read_path(&path).unwrap().0; + read.push(ds.features.iter().map(|f| f.geometry.clone()).collect::>()); + } + assert_close(&read[0], &read[1], ext); + } + let p = json!({"layer": "Wells", "format": "geojson"}); + let [a, b] = run_both(&mut ss, "data.convert", &p); + let read = [a, b].map(|v| { + let text = v["text"].as_str().map(str::to_owned).unwrap_or_else(|| v.to_string()); + rustgis_data::io::read_bytes("w.geojson", text.as_bytes()) + .unwrap() + .0 + .features + .iter() + .map(|f| f.geometry.clone()) + .collect::>() + }); + assert_close(&read[0], &read[1], "data.convert"); +} + +/// Geometry calculations and a buffer give the same measures and places. +#[test] +fn a_held_layer_is_analysed_alike() { + let mut ss = both(); + run_both(&mut ss, "gp.run", &json!({"tool": "calculateGeometry", "params": {"input": "Parcels"}})); + run_both(&mut ss, "gp.run", &json!({"tool": "calculateGeometry", "params": {"input": "Roads"}})); + for layer in ["Parcels", "Roads"] { + let [a, b] = [&ss[0], &ss[1]].map(|s| { + let ds = &s.map().layer_by_name(layer).unwrap().dataset; + (0..ds.features.len()) + .flat_map(|r| (2..ds.fields.len()).map(move |f| (r, f))) + .map(|(r, f)| ds.value(r, f).as_f64().unwrap_or(f64::NAN)) + .collect::>() + }); + assert!(!a.is_empty(), "{layer}: no measures"); + for (p, q) in a.iter().zip(&b) { + assert!((p - q).abs() <= 1e-6 * p.abs().max(1.0), "{layer}: {a:?} vs {b:?}"); + } + } + run_both(&mut ss, "gp.run", &json!({"tool": "buffer", "params": {"input": "Wells", "distance": 100}})); + assert_close(&lonlat(&ss[0], "Wells_Buffer"), &lonlat(&ss[1], "Wells_Buffer"), "buffer"); +} + +/// A geometry set, a move in metres and an undo leave the same places, and a held layer keeps +/// its system through them. +#[test] +fn a_held_layer_is_edited_alike() { + let mut ss = both(); + let g = json!({"type": "Point", "coordinates": [11.505, 48.705]}); + run_both(&mut ss, "edit.setGeometry", &json!({"layer": "Wells", "row": 0, "geometry": g})); + assert_close(&lonlat(&ss[0], "Wells"), &lonlat(&ss[1], "Wells"), "setGeometry"); + run_both(&mut ss, "select.rows", &json!({"layer": "Parcels", "rows": [4]})); + run_both(&mut ss, "edit.move", &json!({"dx": 250.0, "dy": -100.0})); + let [a, b] = [lonlat(&ss[0], "Parcels"), lonlat(&ss[1], "Parcels")]; + // A move in metres on the map: the two agree to well within a centimetre. + for (p, q) in a.iter().zip(&b) { + let (mut ca, mut cb) = (Vec::new(), Vec::new()); + p.as_ref().unwrap().for_each_coord(|c| ca.push(c)); + q.as_ref().unwrap().for_each_coord(|c| cb.push(c)); + for (p, q) in ca.iter().zip(&cb) { + assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "move: {p:?} vs {q:?}"); + } + } + run_both(&mut ss, "edit.undo", &Value::Null); + assert_close(&lonlat(&ss[0], "Parcels"), &lonlat(&ss[1], "Parcels"), "undo"); + assert_eq!(ss[1].map().layer_by_name("Parcels").unwrap().dataset.coord_crs(), UTM); +} + +/// Features copied from a held layer and pasted into one held in longitude/latitude, and the +/// other way round, land where they were. +#[test] +fn features_are_copied_between_systems() { + let mut s = session(UTM); + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + s.map_mut().add_dataset(Dataset::new("Plain", GeometryType::Point, fields)); + s.run("select.rows", &json!({"layer": "Wells", "rows": [1, 2]})).unwrap(); + s.run("edit.copy", &Value::Null).unwrap(); + s.run("edit.paste", &json!({"layer": "Plain"})).unwrap(); + assert_eq!(s.map().layer_by_name("Plain").unwrap().dataset.coord_crs(), Crs::LonLat); + assert_close(&lonlat(&s, "Plain"), &lonlat(&s, "Wells")[1..3], "into longitude/latitude"); + s.run("select.clear", &Value::Null).unwrap(); + s.run("select.rows", &json!({"layer": "Plain", "rows": [0, 1]})).unwrap(); + s.run("edit.copy", &Value::Null).unwrap(); + s.run("edit.paste", &json!({"layer": "Wells"})).unwrap(); + let wells = lonlat(&s, "Wells"); + assert_close(&wells[9..], &wells[1..3], "into UTM"); +} + +/// A project saves a held layer in longitude/latitude, as older releases read it, and opens it +/// back held there, at the same places. +#[test] +fn a_held_layer_is_saved_in_lonlat() { + let [plain, mut held] = both(); + let dir = Dir::new("project"); + let path = dir.path().join("held.rgis"); + held.run("project.saveAs", &json!({"path": path.display().to_string()})).unwrap(); + let mut back = Session::new(Project::default()); + back.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); + for layer in ["Wells", "Roads", "Parcels"] { + assert_eq!(back.map().layer_by_name(layer).unwrap().dataset.coord_crs(), Crs::LonLat); + assert_close(&lonlat(&back, layer), &lonlat(&plain, layer), layer); + } +} + +/// The numbers of a text file (an OBJ's vertices), in order. +fn numbers(text: &str) -> Vec { + text.split(|c: char| c.is_whitespace() || c == ',' || c == '[' || c == ']').filter_map(|w| w.parse::().ok()).collect() +} + +/// `a` and `b` hold the same numbers, each within `tol`. +fn assert_numbers_close(a: &[f64], b: &[f64], tol: f64, what: &str) { + assert_eq!(a.len(), b.len(), "{what}: how many numbers"); + assert!(!a.is_empty(), "{what}: none"); + for (i, (p, q)) in a.iter().zip(b).enumerate() { + assert!((p - q).abs() <= tol, "{what}: number {i}: {p} vs {q}"); + } +} + +/// A 3D file, a web scene, a web layer and a mobile map package place the features alike. +#[test] +fn a_held_layer_is_shared_alike() { + let mut ss = both(); + let dir = Dir::new("shares"); + let file = |k: usize, name: &str| dir.path().join(format!("{k}-{name}")).display().to_string(); + for (k, s) in ss.iter_mut().enumerate() { + s.run("share.export3d", &json!({"layer": "Parcels", "path": file(k, "parcels.obj"), "heightField": "n"})).unwrap(); + s.run("layer.extrusion", &json!({"layer": "Parcels", "type": "height", "height": 50})).unwrap(); + s.run("share.webScene", &json!({"path": file(k, "scene.gltf")})).unwrap(); + s.run("share.webLayer", &json!({"layer": "Roads", "path": file(k, "roads.zip")})).unwrap(); + s.run("map.package", &json!({"path": file(k, "map.rgismpk"), "mobile": true, "tolerance": 0.0001})).unwrap(); + } + let read = |name: &str| [0, 1].map(|k| std::fs::read(file(k, name)).unwrap()); + // Metres from the layer's corner, which is that of its longitude/latitude box, a little further + // out for the held layer (see the extent above): the vertices from the first one, as the file + // writes them (to a centimetre), shrunk alike at the box's centre's latitude. + let [a, b] = read("parcels.obj").map(|t| { + let text = String::from_utf8(t).unwrap(); + let v: Vec<[f64; 3]> = text + .lines() + .filter_map(|l| l.strip_prefix("v ")) + .map(|l| { + let n = numbers(l); + [n[0], n[1], n[2]] + }) + .collect(); + let o = v[0]; + v.iter().flat_map(|p| [p[0] - o[0], p[1] - o[1], p[2] - o[2]]).collect::>() + }); + assert_numbers_close(&a, &b, 0.02, "3D file"); + // The scene's accessors' bounds, in metres from the map's centre. + let [a, b] = read("scene.gltf").map(|t| { + let g: Value = serde_json::from_slice(&t).unwrap(); + g["accessors"].as_array().unwrap().iter().flat_map(|a| numbers(&format!("{} {}", a["min"], a["max"]))).collect::>() + }); + assert_numbers_close(&a, &b, 1e-2, "web scene"); + let [a, b] = read("roads.zip").map(|z| { + let z = rustgis_data::zip::read(&z).unwrap(); + let items = z.iter().find(|e| e.0.ends_with("items.json")).unwrap(); + let index = z.iter().find(|e| e.0 == "index.html").unwrap(); + let mut n = numbers(&String::from_utf8_lossy(&items.1)); + // The viewer's features, in the page's own data. + n.extend( + numbers(&String::from_utf8_lossy(&index.1)).into_iter().filter(|x| (11.4..=11.6).contains(x) || (48.6..=48.8).contains(x)), + ); + n + }); + assert_numbers_close(&a, &b, CLOSE, "web layer"); + for s in &mut ss { + let k = usize::from(s.map().layer_by_name("Wells").unwrap().dataset.coord_crs() != Crs::LonLat); + s.run("map.import", &json!({"path": file(k, "map.rgismpk")})).unwrap(); + } + let [a, b] = [&ss[0], &ss[1]].map(|s| { + let m = s.project.maps.last().unwrap(); + let l = m.layer_by_name("Parcels").unwrap(); + assert_eq!(l.dataset.coord_crs(), Crs::LonLat); + l.dataset.features.iter().map(|f| f.geometry.clone()).collect::>() + }); + assert_close(&a, &b, "mobile map package"); +} + +/// A spatial join counts the same wells on each parcel (each has one, on its corner), whether +/// both layers are held in UTM or one of them in longitude/latitude. +#[test] +fn a_held_layer_is_joined_alike() { + let mut ss = both(); + let fields = vec![Field::new("name", FieldType::Text), Field::new("n", FieldType::Integer)]; + let mut plain = Dataset::new("Plain", GeometryType::Point, fields); + // Inside the parcels: one on a corner may read a hair either side of it through UTM. + for g in lonlat(&ss[0], "Wells") { + let Some(Geometry::Point(c)) = g else { continue }; + plain.push(Some(Geometry::Point(Coord::new(c.x + 0.001, c.y + 0.001))), vec![Cell::Text("w".into()), Cell::Int(0)]); + } + for s in &mut ss { + s.map_mut().add_dataset(plain.clone()); + } + let counts = |s: &Session, layer: &str| { + let ds = &s.map().layer_by_name(layer).unwrap().dataset; + let f = ds.field_index("join_count").unwrap(); + (0..ds.features.len()).map(|r| ds.value(r, f).as_f64().unwrap_or(-1.0)).collect::>() + }; + for (join, out) in [("Wells", "Held_Join"), ("Plain", "Mixed_Join")] { + let p = json!({"tool": "spatialJoin", "params": {"target": "Parcels", "join": join, "match": "Intersects", "output": out}}); + run_both(&mut ss, "gp.run", &p); + assert_eq!(counts(&ss[0], out), counts(&ss[1], out), "{join}"); + assert!(counts(&ss[0], out).iter().any(|&n| n > 0.0), "{join}: nothing joined"); + assert_close(&lonlat(&ss[0], out), &lonlat(&ss[1], out), out); + } +} + +/// The map is drawn alike, labels and all, on Web Mercator, another projection and the globe. +#[test] +fn a_held_layer_is_drawn_alike() { + let mut ss = both(); + let dir = Dir::new("drawn"); + run_both(&mut ss, "labels.enable", &json!({"layer": "Wells", "on": true})); + for (k, projection) in ["mercator", "epsg:3035", "globe"].into_iter().enumerate() { + let camera = camera_over_parcels(projection); + for s in &mut ss { + s.run("map.projection", &json!({"type": projection})).unwrap(); + // The same view on each, as the two layers' boxes differ a little. + s.map_mut().camera = camera; + } + let pngs = [0, 1].map(|i| { + let path = dir.path().join(format!("{k}-{i}.png")); + ss[i].run("share.exportMap", &json!({"path": path.display().to_string(), "width": 320, "height": 200})).unwrap(); + image::open(&path).unwrap().to_rgba8() + }); + let differ = pngs[0].pixels().zip(pngs[1].pixels()).filter(|(a, b)| a != b).count(); + let drawn = pngs[0].pixels().filter(|p| p.0 != pngs[0].get_pixel(0, 0).0).count(); + assert!(drawn > 1000, "{projection:?}: little drawn ({drawn} pixels)"); + // Anti-aliased edges may shade a little otherwise. + assert!(differ * 100 < drawn, "{projection:?}: {differ} of {drawn} drawn pixels differ"); + } +} + +/// A camera over the parcels on a map of `projection`, set alike on both maps. +fn camera_over_parcels(projection: &str) -> rustgis_map::Camera { + let mut s = session(Crs::LonLat); + s.run("map.projection", &json!({"type": projection})).unwrap(); + s.run("layer.zoomTo", &json!({"layer": "Parcels"})).unwrap(); + s.map().camera +} + +/// Rasterizing a held layer gives the grid of the same layer held in longitude/latitude (cells +/// off the parcels' edges, which may read a hair either side of a cell's through UTM). +#[test] +fn a_held_layer_is_rasterized_alike() { + let mut ss = both(); + let [a, b] = run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1})); + assert_eq!(a, b); +} + +/// Calculating a geometry property into a field, and `$area`/`$length` in a field calculation, +/// give the same values. +#[test] +fn a_held_layers_measures_are_calculated_alike() { + let mut ss = both(); + let steps = [ + ("edit.addField", json!({"layer": "Parcels", "name": "a", "type": "double"})), + ("edit.addField", json!({"layer": "Parcels", "name": "b", "type": "double"})), + ( + "edit.calculateGeometry", + json!({"layer": "Parcels", "field": "a", "property": "area", "unit": "m2", "scope": "all", "overwrite": true}), + ), + ("edit.calculateField", json!({"layer": "Parcels", "field": "b", "expression": "$area"})), + ("edit.addField", json!({"layer": "Wells", "name": "x", "type": "double"})), + ( + "edit.calculateGeometry", + json!({"layer": "Wells", "field": "x", "property": "x", "unit": "deg", "scope": "all", "overwrite": true}), + ), + ("edit.addField", json!({"layer": "Wells", "name": "e", "type": "double"})), + ( + "edit.calculateGeometry", + json!({"layer": "Wells", "field": "e", "property": "x", "unit": "projected", "epsg": 25832, "scope": "all", "overwrite": true}), + ), + ("edit.addField", json!({"layer": "Roads", "name": "l", "type": "double"})), + ("edit.calculateField", json!({"layer": "Roads", "field": "l", "expression": "$length"})), + ]; + for (cmd, p) in steps { + run_both(&mut ss, cmd, &p); + } + for (layer, field) in [("Parcels", "a"), ("Parcels", "b"), ("Wells", "x"), ("Wells", "e"), ("Roads", "l")] { + let [a, b] = [&ss[0], &ss[1]].map(|s| { + let ds = &s.map().layer_by_name(layer).unwrap().dataset; + let f = ds.field_index(field).unwrap(); + (0..ds.features.len()).map(|r| ds.value(r, f).as_f64().unwrap_or(f64::NAN)).collect::>() + }); + assert_numbers_close(&a, &b, 1e-6 * a.iter().fold(1.0, |m: f64, v| m.max(v.abs())), &format!("{layer}.{field}")); + } +} + +/// A layer made from the selection, labels converted to annotation, an interpolated surface, a +/// route along the roads and points simulated in the parcels are alike. +#[test] +fn a_held_layer_feeds_other_layers_alike() { + let mut ss = both(); + run_both(&mut ss, "select.rows", &json!({"layer": "Wells", "rows": [0, 4, 8]})); + let [a, b] = run_both(&mut ss, "select.layerFromSelection", &json!({"layer": "Wells"})); + let made = |s: &Session, v: &Value| s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().name.clone(); + let (na, nb) = (made(&ss[0], &a), made(&ss[1], &b)); + assert_close(&lonlat(&ss[0], &na), &lonlat(&ss[1], &nb), "layer from selection"); + run_both(&mut ss, "labels.enable", &json!({"layer": "Parcels", "on": true})); + run_both(&mut ss, "select.clear", &Value::Null); + let [a, b] = run_both(&mut ss, "labels.convert", &json!({"layer": "Parcels"})); + let (na, nb) = (made(&ss[0], &a), made(&ss[1], &b)); + let [pa, pb] = [lonlat(&ss[0], &na), lonlat(&ss[1], &nb)]; + assert!(!pa.is_empty(), "no annotation"); + // A label's place is its polygon's label point, found in each system: within a centimetre. + for (p, q) in pa.iter().zip(&pb) { + let (Some(Geometry::Point(p)), Some(Geometry::Point(q))) = (p, q) else { panic!("points") }; + assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "annotation: {p:?} vs {q:?}"); + } + // Cells off the wells' box's edges (the held layer's is a hair larger: see the extent above). + let [a, b] = run_both(&mut ss, "analysis.interpolate", &json!({"layer": "Wells", "field": "n", "cellSize": 0.0015})); + let grid = + |s: &Session, v: &Value| s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); + let (ga, gb) = (grid(&ss[0], &a), grid(&ss[1], &b)); + assert_eq!((ga.width, ga.height), (gb.width, gb.height)); + let [va, vb] = [&ga, &gb].map(|g| { + (0..g.height) + .flat_map(|y| (0..g.width).map(move |x| (x, y))) + .map(|(x, y)| f64::from(g.value(0, i64::from(x), i64::from(y)).unwrap_or(f32::NAN))) + .collect::>() + }); + assert_numbers_close(&va, &vb, 1e-3, "interpolation"); + // From and to off the road's vertices, which a held layer reads a hair away from them. + let route = json!({"layer": "Roads", "from": [11.4951, 48.6925], "to": [11.5295, 48.7290], "snapDistance": 100}); + let [a, b] = run_both(&mut ss, "analysis.route", &route); + assert_close(&lonlat(&ss[0], &made(&ss[0], &a)), &lonlat(&ss[1], &made(&ss[1], &b)), "route"); + let [a, b] = run_both(&mut ss, "analysis.simulate", &json!({"layer": "Parcels", "count": 5, "seed": 3})); + assert_eq!(a["points"], b["points"]); + assert_close(&lonlat(&ss[0], &made(&ss[0], &a)), &lonlat(&ss[1], &made(&ss[1], &b)), "simulation"); +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 3dfc3b5466..4066686644 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1081,30 +1081,51 @@ impl Layer { /// vertex index, which only the source geometry has. pub fn projected_in(&mut self, flat: &projection::Flat, key: &str) -> &[Option] { if !self.is_cached(key) { - self.display = None; if !matches!(flat, projection::Flat::Mercator) { self.display_levels.clear(); } - // From the layer's own coordinate system. Longitude/latitude, every layer's today, - // can't fail; a system that can't be converted draws nothing (a layer read in one is - // converted as it is read, which says why it can't be). - let crs = self.dataset.coord_crs(); - let to_lonlat = crs.to(Crs::LonLat).ok(); - let projected: Vec> = - self.dataset.features.iter().map(|ft| flat.project_from(to_lonlat.as_ref()?, ft.geometry.as_ref()?)).collect(); - self.projected_extents = - std::sync::Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); - self.projected_vertices = projected.iter().flatten().map(lod::thinnable).sum(); - self.projected = std::sync::Arc::new(projected); - self.thinned = Default::default(); - self.projected_rev = self.geometry_rev; - self.projected_for = key.to_string(); - self.projected_crs = Some(crs); - self.trim_display_levels(self.lod_budget()); + self.fill_projected(key, |to_lonlat, g| flat.project_from(to_lonlat, g)); + } + &self.projected + } + + /// Its geometry in longitude/latitude, for the globe, which draws there: kept in the + /// projected geometry cache ([`Layer::projected_cache`]) under its own key, so it is converted + /// once, not every frame. Empty while its coordinates are longitude/latitude, as every layer's + /// are unless held in another system: the geometry is then drawn as it is. + pub fn lonlat_in(&mut self) -> &[Option] { + const KEY: &str = "longitude/latitude"; + if self.dataset.coord_crs() == Crs::LonLat { + return &[]; + } + if !self.is_cached(KEY) { + self.display_levels.clear(); + self.fill_projected(KEY, |to_lonlat, g| Some(to_lonlat.geometry(g))); } &self.projected } + /// Fills the projected geometry cache for `key` with `project` of each geometry, given the + /// conversion of the layer's own coordinate system to longitude/latitude. Longitude/latitude, + /// every layer's unless held in another, can't fail; a system that can't be converted draws + /// nothing (a layer read in one is converted as it is read, which says why it can't be). + fn fill_projected(&mut self, key: &str, project: impl Fn(&rustgis_data::raster::Reprojection, &Geometry) -> Option) { + self.display = None; + let crs = self.dataset.coord_crs(); + let to_lonlat = crs.to(Crs::LonLat).ok(); + let projected: Vec> = + self.dataset.features.iter().map(|ft| project(to_lonlat.as_ref()?, ft.geometry.as_ref()?)).collect(); + self.projected_extents = + std::sync::Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); + self.projected_vertices = projected.iter().flatten().map(lod::thinnable).sum(); + self.projected = std::sync::Arc::new(projected); + self.thinned = Default::default(); + self.projected_rev = self.geometry_rev; + self.projected_for = key.to_string(); + self.projected_crs = Some(crs); + self.trim_display_levels(self.lod_budget()); + } + /// Web Mercator copies of every geometry (see [`Layer::projected_in`]). pub fn projected(&mut self) -> &[Option] { self.projected_in(&projection::Flat::Mercator, "mercator") @@ -3307,6 +3328,7 @@ impl Layer { crs_incomplete: _, zm_dropped: _, windowed: _, + held_in: _, } = dataset; if let Some(v) = provenance { out.push((LayerRole::Dataset, v.as_str(), true, paths::is_local(v))); diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index 04e13667da..df0b3cb212 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -196,8 +196,9 @@ impl Host for Messages<'_> { fn layer_geojson(inputs: &dyn Inputs, name: &str) -> Result { let ds = inputs.dataset(name).ok_or_else(|| format!("no layer named '{name}'"))?; let sel = inputs.selection(name); + // GeoJSON is longitude/latitude, whatever system the layer holds its coordinates in. if sel.is_empty() { - return Ok(rustgis_data::io::to_geojson(ds)); + return Ok(rustgis_data::io::to_geojson(&*ds.in_lonlat()?)); } let sub = rustgis_data::Dataset { name: ds.name.clone(), @@ -209,8 +210,9 @@ fn layer_geojson(inputs: &dyn Inputs, name: &str) -> Result { crs_incomplete: false, zm_dropped: false, windowed: false, + held_in: ds.held_in, }; - Ok(rustgis_data::io::to_geojson(&sub)) + Ok(rustgis_data::io::to_geojson(&*sub.in_lonlat()?)) } fn run(spec: &ToolSpec, inputs: &dyn Inputs, params: &Value) -> Result { diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index fbd21dc36d..02a2e77c92 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -472,7 +472,10 @@ fn units(layer: &rustgis_map::Layer, b: &Block, env: &rustgis_data::query::Env) if keep.as_ref().is_some_and(|k| !k.get(row).copied().unwrap_or(false)) { continue; } - let Some(Geometry::Polygon(polys)) = &ft.geometry else { continue }; + // In longitude/latitude, whatever system the layer holds its coordinates in; a polygon + // that can't be given there makes no contact, as the map draws none of it. + let Some(lonlat) = ft.geometry.as_ref().and_then(|g| layer.dataset.geometry_to_lonlat(g).ok()) else { continue }; + let Geometry::Polygon(polys) = &*lonlat else { continue }; for rings in polys { let mut e = Extent::EMPTY; rings.iter().flatten().for_each(|c| e.expand(*c)); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index cbc8be68e3..833dd99c76 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4708,6 +4708,10 @@ fn render_frame( && (!complete_source || thin_complete) && layer.diagram.is_none() && layer.prepare_display(&flat, thin_tol, complete_source); + if globe.is_some() { + // In longitude/latitude, which the globe draws (none for a layer held there). + layer.lonlat_in(); + } if globe.is_none() && !display_only { if complete_source { layer.projected_in(&flat, &key); @@ -4729,8 +4733,11 @@ fn render_frame( // move rows (#1046). let label_id = |row: usize| layer.dataset.features.get(row).map_or(row as u64, |f| f.id); let (labels, selection, ds_ptr) = (&layer.labels, &layer.selection, &layer.dataset); - // The globe draws the lon/lat geometry itself; the flat map its Web Mercator copy. - let geoms: Vec> = if globe.is_some() { + // The globe draws the lon/lat geometry itself (a layer held in another system, its + // copy in longitude/latitude); the flat map its Web Mercator copy. + let geoms: Vec> = if globe.is_some() && ds_ptr.coord_crs() != rustgis_data::raster::Crs::LonLat { + layer.projected_cache().iter().map(Option::as_ref).collect() + } else if globe.is_some() { ds_ptr.features.iter().map(|f| f.geometry.as_ref()).collect() } else if display_only { layer.display_cache().map_or(&[][..], |(g, _)| g).iter().map(Option::as_ref).collect() @@ -5985,7 +5992,12 @@ fn layer_masks( } } else if let Some(ml) = map.layers.get_mut(mi) { if ctx.globe.is_some() { - ml.dataset.features.iter().filter_map(|f| f.geometry.as_ref()).for_each(&mut add); + // In longitude/latitude: its copy there when it is held in another system. + if ml.lonlat_in().is_empty() { + ml.dataset.features.iter().filter_map(|f| f.geometry.as_ref()).for_each(&mut add); + } else { + ml.projected_cache().iter().flatten().for_each(&mut add); + } } else { ml.projected_in(flat, key).iter().flatten().for_each(&mut add); } @@ -6418,8 +6430,10 @@ fn square_lines( } let Some(layer) = map.layer_by_name(&name) else { continue }; let mut runs = Vec::new(); - for g in layer.dataset.features.iter().filter_map(|f| f.geometry.as_ref()) { - let (parts, rings): (Vec<&Vec>, bool) = match g { + // Read in longitude/latitude, whatever system the layer holds its coordinates in; a + // feature that can't be given there squares nothing. + for g in layer.dataset.features.iter().filter_map(|f| layer.dataset.geometry_to_lonlat(f.geometry.as_ref()?).ok()) { + let (parts, rings): (Vec<&Vec>, bool) = match &*g { Geometry::Line(parts) => (parts.iter().collect(), false), Geometry::Polygon(polys) => (polys.iter().flatten().collect(), true), _ => continue, diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 475fb3ec10..c5aae1a3e9 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -489,7 +489,10 @@ fn polygons(layer: &rustgis_map::Layer, level: Option<&str>, drawn: Option<&[boo if drawn.is_some_and(|d| !d.get(row).copied().unwrap_or(false)) { continue; } - let Some(Geometry::Polygon(parts)) = &ft.geometry else { continue }; + // In longitude/latitude, whatever system the layer holds its coordinates in; a polygon + // that can't be given there holds no water, as the map draws none of it. + let Some(lonlat) = ft.geometry.as_ref().and_then(|g| layer.dataset.geometry_to_lonlat(g).ok()) else { continue }; + let Geometry::Polygon(parts) = &*lonlat else { continue }; let given = field.and_then(|i| ft.attrs.get(i)).and_then(rustgis_data::Value::as_f64).filter(|v| v.is_finite()); for rings in parts { let rings: Vec> = rings.iter().map(|r| r.iter().map(|c| lonlat_to_merc(*c)).collect()).collect(); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 322588ef3a..38431b4604 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 = 833 +count = 824 From 34d6a7d8f7137ce84ffc6cddfd0b8a3303edfb9d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 13:56:00 +0100 Subject: [PATCH 2/4] fix(crs): review: field package sync from a held source, conversions made once per layer, glTF leaves out what it can't place --- crates/data/src/lib.rs | 15 +++-- crates/data/src/publish.rs | 2 + crates/engine/src/cmd/sharing.rs | 16 ++++- crates/engine/src/cmd/workspace.rs | 36 ++++++++--- crates/engine/src/tests/held_layers.rs | 87 ++++++++++++++++++++++++++ crates/render/src/block.rs | 8 ++- crates/render/src/lib.rs | 6 +- crates/render/src/terrain/water.rs | 8 ++- xtask/row-uses.txt | 2 +- 9 files changed, 160 insertions(+), 20 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 16658617ca..da3cd4ba7c 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -493,12 +493,19 @@ impl Dataset { /// naming its system, when its system can't be converted or one of its places can't be. pub fn geometry_to_lonlat<'a>(&self, g: &'a Geometry) -> std::result::Result, String> { let to = self.coord_crs().to(raster::Crs::LonLat)?; + Self::converted_to_lonlat(&to, g) + .ok_or_else(|| format!("a place of this feature in {} can't be given in longitude/latitude", to.source().label())) + } + + /// One of its geometries in longitude/latitude by `to`, its [`Dataset::lonlat_conversion`] + /// made once for many geometries (as a frame draws them), as [`Dataset::geometry_to_lonlat`] + /// converts it: borrowed when `to` is the identity, a missing coordinate kept, `None` when one + /// of its places can't be converted. + pub fn converted_to_lonlat<'a>(to: &raster::Reprojection, g: &'a Geometry) -> Option> { if to.is_identity() { - return Ok(Cow::Borrowed(g)); + return Some(Cow::Borrowed(g)); } - convert_keeping_missing(&to, g, &HeldPlaces::default()) - .map(Cow::Owned) - .ok_or_else(|| format!("a place of this feature in {} can't be given in longitude/latitude", to.source().label())) + convert_keeping_missing(to, g, &HeldPlaces::default()).map(Cow::Owned) } /// An edited geometry in longitude/latitude, written back in its own coordinates diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 3f1d901b8c..4ffb853de8 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -454,6 +454,7 @@ fn in_file<'a>(ds: &'a Dataset, crs: Option, as_held: Option<(&Dataset, &Da } let mut out = ds.clone(); out.features = rows.into(); + out.held_in = c; Ok(std::borrow::Cow::Owned(out)) } @@ -798,6 +799,7 @@ mod tests { assert!(matches!(same, std::borrow::Cow::Borrowed(_))); let other = in_file(&ds, Some(etrs), Some((&ds, &ds))).unwrap(); assert_eq!(other.features[0].geometry, Some(Geometry::Point(utm.to(etrs).unwrap().point(at).unwrap()))); + assert_eq!(other.coord_crs(), etrs); } /// A small polygon layer of parcels with an owner, an area with decimals and a count. diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 7850c944cb..d8f9241fd8 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -1007,6 +1007,8 @@ struct SceneBytes { skipped_outer: usize, holes_dropped: usize, single_vertex_lines: usize, + /// Features left out because a place of theirs can't be given in longitude/latitude. + unplaced: usize, /// Per layer, in scene order: its name and how many features had their base or height held /// to [`SCENE_TOP`]. held: Vec<(String, usize)>, @@ -1025,6 +1027,9 @@ impl SceneBytes { if self.limited > 0 { notes.push(format!("{} feature(s) left out of the scene: the {MAX_FEATURES} feature limit was reached", self.limited)); } + if self.unplaced > 0 { + notes.push(format!("{} feature(s) left out of the scene: a place can't be given in longitude/latitude", self.unplaced)); + } if self.skipped_outer > 0 { notes.push(format!("Skipped {} polygon(s) whose outer ring has fewer than 3 vertices", self.skipped_outer)); } @@ -1079,6 +1084,9 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { }; let (mut built, mut last): (usize, Option<([u8; 4], usize)>) = (0, None); let mut held = 0usize; + // The layer's conversion to longitude/latitude, made once (none: a system that can't be + // converted, whose features are all left out, and said). + let to_lonlat = l.dataset.lonlat_conversion().ok(); for (row, ft) in l.dataset.features.iter().enumerate() { if let Some((k, before)) = last.take() { built += size(&tri, &lines, &k).saturating_sub(before); @@ -1091,8 +1099,12 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result { scene.limited += 1; continue; } - // Placed from longitude/latitude, whatever system the layer holds its coordinates in. - let lonlat = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?; + // Placed from longitude/latitude, whatever system the layer holds its coordinates in; a + // feature with a place that can't be given there is left out, and said, as one too far. + let Some(lonlat) = to_lonlat.as_ref().and_then(|to| rustgis_data::Dataset::converted_to_lonlat(to, g)) else { + scene.unplaced += 1; + continue; + }; let g = &*lonlat; // A position too far for 32 bits would make the scene invalid: the feature is left out, // and said. Only what would be drawn counts (not a degenerate ring or a one-vertex line). diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 7117875216..0da3f9683f 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -814,22 +814,35 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // Layers are matched by id (the snapshot keeps them), so same-named layers don't mix. // Layers removed from either side since the download are left alone. let Some(sl) = src.layers.iter_mut().find(|l| l.id == ol.id && !l.is_raster()) else { continue }; - let baseline = area.data.layers.iter().find(|l| l.id == ol.id); - if !offline_fields_match(&sl.dataset.fields, &ol.dataset.fields) - && baseline.is_none_or(|l| { - !offline_fields_match(&l.dataset.fields, &ol.dataset.fields) || l.dataset.features != ol.dataset.features - }) + // Compared and merged in longitude/latitude, as a package returns its features, whatever + // system the source, its last synced copy or the package hold them in; the source is + // written back in its own, its unchanged places as stored (`results_from_lonlat`). + let ol_ds = ol.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + let baseline = area + .data + .layers + .iter() + .find(|l| l.id == ol.id) + .map(|l| l.dataset.in_lonlat()) + .transpose() + .map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + if !offline_fields_match(&sl.dataset.fields, &ol_ds.fields) + && baseline.as_ref().is_none_or(|b| !offline_fields_match(&b.fields, &ol_ds.fields) || b.features != ol_ds.features) { return Err(format!("cannot sync layer '{}': source and offline fields differ; align the fields before syncing", ol.name)); } + let held = (sl.dataset.coord_crs() != rustgis_data::raster::Crs::LonLat).then(|| sl.dataset.clone()); + if held.is_some() { + sl.dataset = sl.dataset.in_lonlat().map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?.into_owned(); + } // The ids the area held when it was last synced. let had: std::collections::HashSet = - baseline.map(|l| l.dataset.features.iter().map(|f| f.id).collect()).unwrap_or_default(); - let now_ids: std::collections::HashSet = ol.dataset.features.iter().map(|f| f.id).collect(); + baseline.as_ref().map(|b| b.features.iter().map(|f| f.id).collect()).unwrap_or_default(); + let now_ids: std::collections::HashSet = ol_ds.features.iter().map(|f| f.id).collect(); // The area's copies as last synced: only features changed offline since then go back, // so edits made to the source meanwhile aren't overwritten by stale copies. let base: std::collections::HashMap = - baseline.map(|l| l.dataset.features.iter().map(|f| (f.id, f)).collect()).unwrap_or_default(); + baseline.as_ref().map(|b| b.features.iter().map(|f| (f.id, f)).collect()).unwrap_or_default(); // Deletions first, so a fresh id given to a new feature below can't be swept away. let before = sl.dataset.features.len(); sl.dataset.features.retain(|x| { @@ -841,7 +854,7 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - keep }); deleted += before - sl.dataset.features.len(); - for f in &ol.dataset.features { + for f in &ol_ds.features { if had.contains(&f.id) { let changed_offline = base.get(&f.id).is_none_or(|b| *b != f); match sl.dataset.features.iter_mut().find(|x| x.id == f.id) { @@ -874,6 +887,11 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - added += 1; } } + if let Some(own) = held { + // Its own coordinates back while the merge is converted (and kept, should that fail). + let merged = std::mem::replace(&mut sl.dataset, own); + sl.dataset = sl.dataset.results_from_lonlat(merged).map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + } sl.selection.clear(); sl.touch_geometry(); } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index d84ac5e746..01d4fae795 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -84,10 +84,26 @@ fn lonlat(s: &Session, layer: &str) -> Vec> { l.dataset.in_lonlat().unwrap().features.iter().map(|f| f.geometry.clone()).collect() } +/// A geometry's shape: its kind, then how many parts it has and how many places each part (or +/// ring) has. +fn shape(g: &Option) -> Vec { + match g { + None => vec![0], + Some(Geometry::Point(_)) => vec![1], + Some(Geometry::MultiPoint(v)) => vec![2, v.len()], + Some(Geometry::Line(parts)) => [3, parts.len()].into_iter().chain(parts.iter().map(Vec::len)).collect(), + Some(Geometry::Polygon(polys)) => [4, polys.len()] + .into_iter() + .chain(polys.iter().flat_map(|rings| std::iter::once(rings.len()).chain(rings.iter().map(Vec::len)))) + .collect(), + } +} + /// Every coordinate of `a` within [`CLOSE`] of `b`'s, in the same shapes. fn assert_close(a: &[Option], b: &[Option], 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()); if let Some(g) = a { g.for_each_coord(|c| ca.push(c)); @@ -216,6 +232,7 @@ fn a_held_layer_is_analysed_alike() { .collect::>() }); assert!(!a.is_empty(), "{layer}: no measures"); + assert_eq!(a.len(), b.len(), "{layer}: how many measures"); for (p, q) in a.iter().zip(&b) { assert!((p - q).abs() <= 1e-6 * p.abs().max(1.0), "{layer}: {a:?} vs {b:?}"); } @@ -236,7 +253,9 @@ fn a_held_layer_is_edited_alike() { run_both(&mut ss, "edit.move", &json!({"dx": 250.0, "dy": -100.0})); let [a, b] = [lonlat(&ss[0], "Parcels"), lonlat(&ss[1], "Parcels")]; // A move in metres on the map: the two agree to well within a centimetre. + assert_eq!(a.len(), b.len(), "move: feature count"); for (p, q) in a.iter().zip(&b) { + assert_eq!(shape(p), shape(q), "move: shape"); let (mut ca, mut cb) = (Vec::new(), Vec::new()); p.as_ref().unwrap().for_each_coord(|c| ca.push(c)); q.as_ref().unwrap().for_each_coord(|c| cb.push(c)); @@ -431,6 +450,19 @@ fn a_held_layer_is_rasterized_alike() { let mut ss = both(); let [a, b] = run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1})); assert_eq!(a, b); + // And the same cells: every value, the no-data ones too. + let [ga, gb] = [(&ss[0], &a), (&ss[1], &b)] + .map(|(s, v)| s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.clone().unwrap()); + assert_eq!((ga.width, ga.height), (gb.width, gb.height)); + let cells = |g: &rustgis_data::raster::Raster| { + (0..g.height) + .flat_map(|y| (0..g.width).map(move |x| (x, y))) + .map(|(x, y)| g.value(0, i64::from(x), i64::from(y))) + .collect::>() + }; + let (ca, cb) = (cells(&ga), cells(&gb)); + assert!(ca.iter().any(Option::is_some) && ca.iter().any(Option::is_none), "burned and empty cells"); + assert_eq!(ca, cb); } /// Calculating a geometry property into a field, and `$area`/`$length` in a field calculation, @@ -488,6 +520,7 @@ fn a_held_layer_feeds_other_layers_alike() { let (na, nb) = (made(&ss[0], &a), made(&ss[1], &b)); let [pa, pb] = [lonlat(&ss[0], &na), lonlat(&ss[1], &nb)]; assert!(!pa.is_empty(), "no annotation"); + assert_eq!(pa.len(), pb.len(), "annotation count"); // A label's place is its polygon's label point, found in each system: within a centimetre. for (p, q) in pa.iter().zip(&pb) { let (Some(Geometry::Point(p)), Some(Geometry::Point(q))) = (p, q) else { panic!("points") }; @@ -514,3 +547,57 @@ fn a_held_layer_feeds_other_layers_alike() { assert_eq!(a["points"], b["points"]); assert_close(&lonlat(&ss[0], &made(&ss[0], &a)), &lonlat(&ss[1], &made(&ss[1], &b)), "simulation"); } + +/// An offline area's edits sync back alike, also when they come back in longitude/latitude (as a +/// field package's do) to a source held in UTM: a moved well and a changed value reach the +/// source, and it keeps every place the edits didn't touch exactly as it held it. +#[test] +fn a_held_layers_offline_edits_sync_alike() { + let mut ss = both(); + let before: Vec> = + ss[1].map().layer_by_name("Wells").unwrap().dataset.features.iter().map(|f| f.geometry.clone()).collect(); + run_both(&mut ss, "offline.download", &json!({"name": "Field", "extent": [11.4, 48.6, 11.6, 48.8]})); + run_both(&mut ss, "offline.open", &json!({"name": "Field"})); + let g = json!({"type": "Point", "coordinates": [11.505, 48.705]}); + run_both(&mut ss, "edit.setGeometry", &json!({"layer": "Wells", "row": 0, "geometry": g})); + run_both(&mut ss, "edit.setValue", &json!({"layer": "Wells", "row": 1, "field": "n", "value": 99})); + run_both(&mut ss, "map.activate", &json!({"name": "Map"})); + ss[0].run("offline.sync", &json!({"name": "Field"})).unwrap(); + // The held session's edits come back as a field package brings them: in longitude/latitude, + // beside a source and a last synced copy held in UTM. + let mut returned = ss[1].project.maps.iter().find(|m| m.name == "Field (offline)").unwrap().clone(); + for l in &mut returned.layers { + l.dataset = l.dataset.in_lonlat().unwrap().into_owned(); + } + let ai = ss[1].project.offline_areas.iter().position(|a| a.name == "Field").unwrap(); + crate::cmd::workspace::sync_area(&mut ss[1], ai, &returned).unwrap(); + assert_close(&lonlat(&ss[0], "Wells"), &lonlat(&ss[1], "Wells"), "synced"); + let held = &ss[1].map().layer_by_name("Wells").unwrap().dataset; + assert_eq!(held.coord_crs(), UTM); + let n = held.field_index("n").unwrap(); + assert_eq!(held.value(1, n), &Cell::Int(99)); + // Feature 0 moved; every other place is as it was held, to the bit. + let after: Vec> = held.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(after.len(), before.len()); + assert_ne!(after[0], before[0]); + assert_eq!(after[1..], before[1..]); +} + +/// A web scene leaves out, and says, a feature of a held layer with a place that can't be given +/// in longitude/latitude, rather than failing the whole scene. +#[test] +fn a_web_scene_leaves_out_what_it_cannot_place() { + let mut s = session(UTM); + let dir = Dir::new("unplaced"); + // Far beyond any place UTM 32N holds. + s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.push(Some(Geometry::Point(Coord::new(1e12, 1e12))), vec![]); + let mark = s.notice_mark(); + let path = dir.path().join("scene.gltf"); + s.run("share.webScene", &json!({"path": path.display().to_string()})).unwrap(); + assert!(path.exists()); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.iter().any(|n| n.contains("1 feature(s) left out of the scene: a place can't be given in longitude/latitude")), + "{said:?}" + ); +} diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 02a2e77c92..13543ca82a 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -468,13 +468,19 @@ fn units(layer: &rustgis_map::Layer, b: &Block, env: &rustgis_data::query::Env) // The polygons reaching the box (Web Mercator rings, and their box), each part on its own, in // row order. let mut parts: Vec<(usize, Vec>, Extent)> = Vec::new(); + // Its conversion to longitude/latitude, made once for its polygons (none: a system that can't + // be converted, of which the map draws nothing either). + let to = layer.dataset.lonlat_conversion().ok(); for (row, ft) in layer.dataset.features.iter().enumerate() { if keep.as_ref().is_some_and(|k| !k.get(row).copied().unwrap_or(false)) { continue; } // In longitude/latitude, whatever system the layer holds its coordinates in; a polygon // that can't be given there makes no contact, as the map draws none of it. - let Some(lonlat) = ft.geometry.as_ref().and_then(|g| layer.dataset.geometry_to_lonlat(g).ok()) else { continue }; + let Some(lonlat) = ft.geometry.as_ref().zip(to.as_ref()).and_then(|(g, to)| rustgis_data::Dataset::converted_to_lonlat(to, g)) + else { + continue; + }; let Geometry::Polygon(polys) = &*lonlat else { continue }; for rings in polys { let mut e = Extent::EMPTY; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 833dd99c76..64968202d2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6431,8 +6431,10 @@ fn square_lines( let Some(layer) = map.layer_by_name(&name) else { continue }; let mut runs = Vec::new(); // Read in longitude/latitude, whatever system the layer holds its coordinates in; a - // feature that can't be given there squares nothing. - for g in layer.dataset.features.iter().filter_map(|f| layer.dataset.geometry_to_lonlat(f.geometry.as_ref()?).ok()) { + // feature that can't be given there squares nothing (nor any, in a system that can't be + // converted), as the map draws none of it. + let Ok(to) = layer.dataset.lonlat_conversion() else { continue }; + for g in layer.dataset.features.iter().filter_map(|f| rustgis_data::Dataset::converted_to_lonlat(&to, f.geometry.as_ref()?)) { let (parts, rings): (Vec<&Vec>, bool) = match &*g { Geometry::Line(parts) => (parts.iter().collect(), false), Geometry::Polygon(polys) => (polys.iter().flatten().collect(), true), diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index c5aae1a3e9..053044b1ca 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -485,13 +485,19 @@ fn still_good(water: &Water, read_at: web_time::Instant) -> bool { fn polygons(layer: &rustgis_map::Layer, level: Option<&str>, drawn: Option<&[bool]>) -> Vec<(Vec>, Option)> { let field = level.and_then(|f| layer.dataset.field_index(f)); let mut polygons = Vec::new(); + // Its conversion to longitude/latitude, made once for its polygons (none: a system that can't + // be converted, of which the map draws nothing either). + let to = layer.dataset.lonlat_conversion().ok(); for (row, ft) in layer.dataset.features.iter().enumerate() { if drawn.is_some_and(|d| !d.get(row).copied().unwrap_or(false)) { continue; } // In longitude/latitude, whatever system the layer holds its coordinates in; a polygon // that can't be given there holds no water, as the map draws none of it. - let Some(lonlat) = ft.geometry.as_ref().and_then(|g| layer.dataset.geometry_to_lonlat(g).ok()) else { continue }; + let Some(lonlat) = ft.geometry.as_ref().zip(to.as_ref()).and_then(|(g, to)| rustgis_data::Dataset::converted_to_lonlat(to, g)) + else { + continue; + }; let Geometry::Polygon(parts) = &*lonlat else { continue }; let given = field.and_then(|i| ft.attrs.get(i)).and_then(rustgis_data::Value::as_f64).filter(|v| v.is_finite()); for rings in parts { diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 38431b4604..53f968dd99 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 = 824 +count = 823 From 387a4aad056fe850528313ddb4795556dd8587f8 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 15:02:23 +0100 Subject: [PATCH 3/4] fix(crs): review: publish compares a held layer in longitude/latitude; a sync writes back only what it changed --- crates/data/src/lib.rs | 81 ++++++++++++++++++++++++++ crates/data/src/publish.rs | 26 ++++++++- crates/engine/src/cmd/workspace.rs | 24 +++++--- crates/engine/src/tests/held_layers.rs | 8 +++ xtask/row-uses.txt | 2 +- 5 files changed, 130 insertions(+), 11 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index da3cd4ba7c..e5384a598a 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1036,6 +1036,52 @@ impl Dataset { Ok(results) } + /// `merged`, its features in longitude/latitude as [`Dataset::in_lonlat`] gives them with some + /// updated, added or left out (an offline area's sync), in its own coordinates: a feature whose + /// id isn't in `changed` is taken as it holds it, not converted back; a changed one is written + /// back as [`Dataset::results_from_lonlat`] writes it, holding only its own places near the + /// changes, so the search is as large as the changes, not the layer. As it is while its + /// coordinates are longitude/latitude, as every dataset's are today. + pub fn merged_from_lonlat( + &self, + mut merged: Dataset, + changed: &std::collections::HashSet, + ) -> std::result::Result { + if self.edits_in_lonlat() { + return Ok(merged); + } + let own: std::collections::HashMap = self.features.iter().map(|f| (f.id, f)).collect(); + let is_changed = |id: u64| changed.contains(&id) || !own.contains_key(&id); + let edits: Vec<&Geometry> = merged.features.iter().filter(|f| is_changed(f.id)).filter_map(|f| f.geometry.as_ref()).collect(); + let mut held = HeldPlaces::default(); + if !edits.is_empty() { + let mut near = Extent::EMPTY; + for g in &edits { + g.for_each_coord(|c| near.expand(c)); + } + let mut within = self.extent_from_lonlat(&near); + // More than the box: it is converted from samples along its edges, and a projected + // edge bulges between them (under a metre for a degree in UTM). + let pad = 0.01 * (within.width() + within.height()) + 1.0; + within = Extent::new(within.min_x - pad, within.min_y - pad, within.max_x + pad, within.max_y + pad); + held.want_only(&edits); + for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) { + self.hold_places(g, Some(&within), &mut held); + } + } + for f in &mut merged.features { + if is_changed(f.id) { + if let Some(g) = f.geometry.take() { + f.geometry = Some(self.edit_from_lonlat(g, &held).map_err(|e| format!("{}: feature {}: {e}", self.name, f.id))?); + } + } else if let Some(o) = own.get(&f.id) { + f.geometry = o.geometry.clone(); + } + } + merged.held_in = self.held_in; + Ok(merged) + } + /// Pushes a feature with the next id, padding/truncating attributes to the schema. pub fn push(&mut self, geometry: Option, mut attrs: Vec) { attrs.resize(self.fields.len(), Value::Null); @@ -1234,6 +1280,41 @@ mod tests { assert_eq!(window.coord_crs(), raster::Crs::LonLat); } + /// A merge in longitude/latitude written back to a held dataset: what it left as it was stays + /// as stored, a changed feature keeps the places it didn't move, and only a moved or new place + /// is converted. + #[test] + fn a_merge_converts_back_only_what_it_changed() { + let utm = raster::Crs::Epsg(32632); + let mut ds = Dataset::new("held", GeometryType::Point, vec![Field::new("NAME", FieldType::Text)]); + for (i, x) in [11.1, 11.3, 11.5].into_iter().enumerate() { + ds.push(Some(Geometry::Point(Coord::new(x, 48.7 + 0.01 * i as f64))), vec![Value::Text(format!("p{i}"))]); + } + ds.hold_in(utm).unwrap(); + let mut merged = ds.in_lonlat().unwrap().into_owned(); + let mut rows: Vec = merged.features.iter().cloned().collect(); + let ids: Vec = rows.iter().map(|f| f.id).collect(); + rows[1].attrs[0] = Value::Text("renamed".into()); + let Some(Geometry::Point(moved)) = &mut rows[2].geometry else { panic!("a point") }; + moved.y += 0.001; + let moved = *moved; + let new = Coord::new(11.4, 48.75); + rows.push(Feature { id: 99, geometry: Some(Geometry::Point(new)), ..rows[0].clone() }); + merged.features = rows.into(); + let changed = std::collections::HashSet::from([ids[1], ids[2], 99]); + let back = ds.merged_from_lonlat(merged, &changed).unwrap(); + assert_eq!(back.coord_crs(), utm); + let to = utm.transformer().unwrap(); + let stored: Vec<_> = ds.features.iter().map(|f| f.geometry.clone()).collect(); + let got: Vec<_> = back.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(got.len(), 4); + assert_eq!(got[0], stored[0]); + assert_eq!(got[1], stored[1]); + assert_eq!(back.features.get(1).unwrap().attrs[0], Value::Text("renamed".into())); + assert_eq!(got[2], Some(Geometry::Point(to.from_lonlat(moved).unwrap()))); + assert_eq!(got[3], Some(Geometry::Point(to.from_lonlat(new).unwrap()))); + } + /// An export in Web Mercator counts the places past where it ends by their latitude, from the /// system the layer holds its coordinates in (UTM 32N here): one at 86° N, not every northing. #[test] diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 4ffb853de8..91ecb4cd73 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -300,12 +300,15 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result = ds.features.iter().cloned().collect(); + rows[0].attrs[0] = Value::Text("Smyth".into()); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(published.notes.is_empty(), "{:?}", published.notes); + let (back, _) = crate::io::read_path(&path).unwrap(); + assert_eq!(back.features.iter().next().unwrap().attrs[0], Value::Text("Smyth".into())); + } + /// A projected file's unedited shapes stay where they were, to the tolerance. #[test] fn a_projected_file_keeps_its_unedited_shapes() { diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 0da3f9683f..74e248e338 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -843,6 +843,9 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - // so edits made to the source meanwhile aren't overwritten by stale copies. let base: std::collections::HashMap = baseline.as_ref().map(|b| b.features.iter().map(|f| (f.id, f)).collect()).unwrap_or_default(); + // The features this sync writes, by their ids in the source: only these are converted + // back to a held source's system. + let mut written = std::collections::HashSet::new(); // Deletions first, so a fresh id given to a new feature below can't be swept away. let before = sl.dataset.features.len(); sl.dataset.features.retain(|x| { @@ -855,21 +858,23 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - }); deleted += before - sl.dataset.features.len(); for f in &ol_ds.features { - if had.contains(&f.id) { - let changed_offline = base.get(&f.id).is_none_or(|b| *b != f); - match sl.dataset.features.iter_mut().find(|x| x.id == f.id) { + let fid = f.id; + if had.contains(&fid) { + let changed_offline = base.get(&fid).is_none_or(|b| *b != f); + match sl.dataset.features.iter_mut().find(|x| x.id == fid) { Some(x) if changed_offline && x != f => { - if base.get(&f.id).is_some_and(|b| *b != x) { - conflicts.push(tag(&sl.name, f.id)); + if base.get(&fid).is_some_and(|b| *b != x) { + conflicts.push(tag(&sl.name, fid)); } *x = f.clone(); + written.insert(fid); updated += 1; } // Changed offline but deleted from the source meanwhile: left deleted, and // reported. None if changed_offline => { skipped += 1; - dropped.push(tag(&sl.name, f.id)); + dropped.push(tag(&sl.name, fid)); } _ => {} } @@ -884,13 +889,16 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) - f.id }; sl.dataset.features.push(rustgis_data::Feature { id, ..f.clone() }); + written.insert(id); added += 1; } } if let Some(own) = held { - // Its own coordinates back while the merge is converted (and kept, should that fail). + // Its own coordinates back while the merge is converted (and kept, should that fail): + // the features it left as they were stay as stored, only those it wrote are converted. let merged = std::mem::replace(&mut sl.dataset, own); - sl.dataset = sl.dataset.results_from_lonlat(merged).map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; + sl.dataset = + sl.dataset.merged_from_lonlat(merged, &written).map_err(|e| format!("cannot sync layer '{}': {e}", ol.name))?; } sl.selection.clear(); sl.touch_geometry(); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 01d4fae795..5988950179 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -589,6 +589,14 @@ fn a_held_layers_offline_edits_sync_alike() { fn a_web_scene_leaves_out_what_it_cannot_place() { let mut s = session(UTM); let dir = Dir::new("unplaced"); + let left_out = "left out of the scene: a place can't be given in longitude/latitude"; + // Every place converts: nothing is left out, nor said to be. + let mark = s.notice_mark(); + let clean = dir.path().join("clean.gltf"); + s.run("share.webScene", &json!({"path": clean.display().to_string()})).unwrap(); + assert!(clean.exists()); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(!said.iter().any(|n| n.contains(left_out)), "{said:?}"); // Far beyond any place UTM 32N holds. s.map_mut().layers.iter_mut().find(|l| l.name == "Wells").unwrap().dataset.push(Some(Geometry::Point(Coord::new(1e12, 1e12))), vec![]); let mark = s.notice_mark(); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 53f968dd99..13fd181ee9 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 = 823 +count = 818 From 90d2b1bfa8fcd13e4de3d8938b3cb944a72b4e8b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 20 Nov 2026 15:31:11 +0100 Subject: [PATCH 4/4] fix(crs): review: interpolation samples a polygon at its longitude/latitude label point; a sync holds stored places without a box --- crates/data/src/lib.rs | 76 +++++++++++++++--------------- crates/engine/src/cmd/workflows.rs | 14 +++++- 2 files changed, 49 insertions(+), 41 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index e5384a598a..bacb62ad3b 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -1039,8 +1039,9 @@ impl Dataset { /// `merged`, its features in longitude/latitude as [`Dataset::in_lonlat`] gives them with some /// updated, added or left out (an offline area's sync), in its own coordinates: a feature whose /// id isn't in `changed` is taken as it holds it, not converted back; a changed one is written - /// back as [`Dataset::results_from_lonlat`] writes it, holding only its own places near the - /// changes, so the search is as large as the changes, not the layer. As it is while its + /// back as [`Dataset::results_from_lonlat`] writes it: every stored place is read, but only + /// those the changes read as are held, so what is held is as large as the changes, not the + /// layer. As it is while its /// coordinates are longitude/latitude, as every dataset's are today. pub fn merged_from_lonlat( &self, @@ -1053,20 +1054,15 @@ impl Dataset { let own: std::collections::HashMap = self.features.iter().map(|f| (f.id, f)).collect(); let is_changed = |id: u64| changed.contains(&id) || !own.contains_key(&id); let edits: Vec<&Geometry> = merged.features.iter().filter(|f| is_changed(f.id)).filter_map(|f| f.geometry.as_ref()).collect(); + // Every stored place is read, but only those an edit reads as are kept: what is held is + // as large as the changes, and a place is found however far its system's inverse is from + // exact (about a metre and a half in places for Robinson), which no box around the + // edits would bound. let mut held = HeldPlaces::default(); if !edits.is_empty() { - let mut near = Extent::EMPTY; - for g in &edits { - g.for_each_coord(|c| near.expand(c)); - } - let mut within = self.extent_from_lonlat(&near); - // More than the box: it is converted from samples along its edges, and a projected - // edge bulges between them (under a metre for a degree in UTM). - let pad = 0.01 * (within.width() + within.height()) + 1.0; - within = Extent::new(within.min_x - pad, within.min_y - pad, within.max_x + pad, within.max_y + pad); held.want_only(&edits); for g in self.features.iter().filter_map(|f| f.geometry.as_ref()) { - self.hold_places(g, Some(&within), &mut held); + self.hold_places(g, None, &mut held); } } for f in &mut merged.features { @@ -1285,34 +1281,36 @@ mod tests { /// is converted. #[test] fn a_merge_converts_back_only_what_it_changed() { - let utm = raster::Crs::Epsg(32632); - let mut ds = Dataset::new("held", GeometryType::Point, vec![Field::new("NAME", FieldType::Text)]); - for (i, x) in [11.1, 11.3, 11.5].into_iter().enumerate() { - ds.push(Some(Geometry::Point(Coord::new(x, 48.7 + 0.01 * i as f64))), vec![Value::Text(format!("p{i}"))]); + // UTM, and Robinson, whose inverse is a metre or so from exact in places. + for crs in [raster::Crs::Epsg(32632), raster::Crs::parse("ESRI:54030").unwrap()] { + let mut ds = Dataset::new("held", GeometryType::Point, vec![Field::new("NAME", FieldType::Text)]); + for (i, x) in [11.1, 11.3, 11.5].into_iter().enumerate() { + ds.push(Some(Geometry::Point(Coord::new(x, 48.7 + 0.01 * i as f64))), vec![Value::Text(format!("p{i}"))]); + } + ds.hold_in(crs).unwrap(); + let mut merged = ds.in_lonlat().unwrap().into_owned(); + let mut rows: Vec = merged.features.iter().cloned().collect(); + let ids: Vec = rows.iter().map(|f| f.id).collect(); + rows[1].attrs[0] = Value::Text("renamed".into()); + let Some(Geometry::Point(moved)) = &mut rows[2].geometry else { panic!("a point") }; + moved.y += 0.001; + let moved = *moved; + let new = Coord::new(11.4, 48.75); + rows.push(Feature { id: 99, geometry: Some(Geometry::Point(new)), ..rows[0].clone() }); + merged.features = rows.into(); + let changed = std::collections::HashSet::from([ids[1], ids[2], 99]); + let back = ds.merged_from_lonlat(merged, &changed).unwrap(); + assert_eq!(back.coord_crs(), crs); + let to = crs.transformer().unwrap(); + let stored: Vec<_> = ds.features.iter().map(|f| f.geometry.clone()).collect(); + let got: Vec<_> = back.features.iter().map(|f| f.geometry.clone()).collect(); + assert_eq!(got.len(), 4); + assert_eq!(got[0], stored[0]); + assert_eq!(got[1], stored[1]); + assert_eq!(back.features.get(1).unwrap().attrs[0], Value::Text("renamed".into())); + assert_eq!(got[2], Some(Geometry::Point(to.from_lonlat(moved).unwrap()))); + assert_eq!(got[3], Some(Geometry::Point(to.from_lonlat(new).unwrap()))); } - ds.hold_in(utm).unwrap(); - let mut merged = ds.in_lonlat().unwrap().into_owned(); - let mut rows: Vec = merged.features.iter().cloned().collect(); - let ids: Vec = rows.iter().map(|f| f.id).collect(); - rows[1].attrs[0] = Value::Text("renamed".into()); - let Some(Geometry::Point(moved)) = &mut rows[2].geometry else { panic!("a point") }; - moved.y += 0.001; - let moved = *moved; - let new = Coord::new(11.4, 48.75); - rows.push(Feature { id: 99, geometry: Some(Geometry::Point(new)), ..rows[0].clone() }); - merged.features = rows.into(); - let changed = std::collections::HashSet::from([ids[1], ids[2], 99]); - let back = ds.merged_from_lonlat(merged, &changed).unwrap(); - assert_eq!(back.coord_crs(), utm); - let to = utm.transformer().unwrap(); - let stored: Vec<_> = ds.features.iter().map(|f| f.geometry.clone()).collect(); - let got: Vec<_> = back.features.iter().map(|f| f.geometry.clone()).collect(); - assert_eq!(got.len(), 4); - assert_eq!(got[0], stored[0]); - assert_eq!(got[1], stored[1]); - assert_eq!(back.features.get(1).unwrap().attrs[0], Value::Text("renamed".into())); - assert_eq!(got[2], Some(Geometry::Point(to.from_lonlat(moved).unwrap()))); - assert_eq!(got[3], Some(Geometry::Point(to.from_lonlat(new).unwrap()))); } /// An export in Web Mercator counts the places past where it ends by their latitude, from the diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 481f232cd5..647854bfd7 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1568,10 +1568,20 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { let (mut no_point, mut no_value) = (0usize, 0usize); let mut pts: Vec<(Coord, f64)> = Vec::with_capacity(ds.features.len()); // Each place in longitude/latitude, whatever system the layer holds its coordinates in; one - // that can't be given there has no place. + // that can't be given there has no place. A point is converted alone; any other shape is + // converted first, so its label point (a polygon's centroid) is the one it has in + // longitude/latitude, not the one in the layer's own system. A shape with a place that can't + // be converted gives its label point in its own system, converted, as long as that converts. let to = ds.lonlat_conversion()?; + let place = |g: &Geometry| match g { + Geometry::Point(c) => to.point(*c), + g => match Dataset::converted_to_lonlat(&to, g) { + Some(g) => g.label_point(), + None => g.label_point().and_then(|c| to.point(c)), + }, + }; for (r, ft) in ds.features.iter().enumerate() { - let Some(c) = ft.geometry.as_ref().and_then(|g| g.label_point()).and_then(|c| to.point(c)).filter(|c| c.is_finite()) else { + let Some(c) = ft.geometry.as_ref().and_then(place).filter(|c| c.is_finite()) else { no_point += 1; continue; };