From d14557be6d428493646a07c7bc38be0048d641a3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 10:47:11 +0100 Subject: [PATCH 1/3] Topology checked in a held layer's own system: tolerance and least area in its unit, covering layer converted into it (#2032 C2e-5) --- crates/analysis/src/convert.rs | 12 +++++ crates/analysis/src/lib.rs | 9 +--- crates/analysis/src/topology.rs | 63 +++++++++++++++++------ crates/engine/src/cmd/design.rs | 70 +++++++++++++++++++++----- crates/engine/src/tests/held_layers.rs | 53 +++++++++++++++++++ docs/user-guide/editing.md | 6 +++ 6 files changed, 177 insertions(+), 36 deletions(-) diff --git a/crates/analysis/src/convert.rs b/crates/analysis/src/convert.rs index 308432c606..98ed767c8a 100644 --- a/crates/analysis/src/convert.rs +++ b/crates/analysis/src/convert.rs @@ -74,6 +74,18 @@ impl Drop for PlaneInstalled { } } +/// The plane of work on geometry held in `crs`: the analysis plane for longitude/latitude, a +/// projected system's own coordinates otherwise, with its unit and axes +/// ([`rustgis_data::raster::Crs::unit_and_axes`]). For a system [`crate::works_in`] takes. +pub fn run_plane_for(crs: rustgis_data::raster::Crs) -> RunPlane { + if crs == rustgis_data::raster::Crs::LonLat { + RunPlane { plane: Plane::Analysis, unit_m: 1.0, axes: EAST_NORTH } + } else { + let (unit_m, axes) = crs.unit_and_axes(); + RunPlane { plane: Plane::Own, unit_m, axes } + } +} + /// Makes `run` the plane of the work on this thread until the guard is dropped. pub fn install(run: RunPlane) -> PlaneInstalled { PlaneInstalled(PLANE.with(|p| p.replace(run))) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index b68ba78319..2b777e36d9 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -772,14 +772,7 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result(inputs: &dyn Inputs, work: impl FnOnce() -> T) -> T { - let crs = inputs.work_crs(); - let run = if crs == rustgis_data::raster::Crs::LonLat { - convert::RunPlane { plane: convert::Plane::Analysis, unit_m: 1.0, axes: convert::EAST_NORTH } - } else { - let (unit_m, axes) = crs.unit_and_axes(); - convert::RunPlane { plane: convert::Plane::Own, unit_m, axes } - }; - let _plane = convert::install(run); + let _plane = convert::install(convert::run_plane_for(inputs.work_crs())); work() } diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 2cc9725cce..873e45b5c8 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -1,13 +1,17 @@ //! Editing geometry: merging features, and topology checks (overlaps, gaps, self-intersections, -//! dangles, coverage). Computed in the analysis plane ([`rustgis_geom::lonlat_to_plane`]). +//! dangles, coverage). Computed in the plane of the run ([`crate::convert::plane`]): the analysis +//! plane ([`rustgis_geom::lonlat_to_plane`]) for longitude/latitude, with the poles where they are +//! in it; a projected system's own coordinates as they are, with no poles, the tolerance and the +//! least area taken in its unit (#2032 C2e-5). use geo::{Area, BooleanOps, BoundingRect, Contains, Intersects, Orient, orient::Direction}; use rustgis_data::{Dataset, Geometry}; use rustgis_geom::{Coord, Extent, MAX_LAT, WGS84_POLAR_RADIUS_M, lonlat_to_plane, plane_to_lonlat}; -use crate::convert::{from_multipolygon, to_multipolygon}; +use crate::convert::{Plane, from_multipolygon, from_plane, own_length, own_unit_m, plane, to_multipolygon, to_plane}; -/// A topology problem: the rows involved and where it is (longitude/latitude). +/// A topology problem: the rows involved and where it is, in the coordinates the layer was given +/// in (longitude/latitude, or a projected system's own in a run there). #[derive(Clone, Debug, PartialEq)] pub struct TopologyError { pub rows: Vec, @@ -122,7 +126,13 @@ fn polygons(ds: &Dataset, rows: &[usize]) -> Vec<(usize, geo::MultiPolygon, fn centre(mp: &geo::MultiPolygon) -> Coord { use geo::InteriorPoint; - mp.interior_point().map(|p| plane_to_lonlat(Coord::new(p.x(), p.y()))).unwrap_or_default() + mp.interior_point().map(|p| from_plane(Coord::new(p.x(), p.y()))).unwrap_or_default() +} + +/// The least area an overlap or gap has to be one, in the plane's units: a square metre (shared +/// edges leave slivers of floating-point area), in a projected system's own unit there. +fn least_area() -> f64 { + own_unit_m().map_or(1.0, |u| 1.0 / (u * u)) } fn rects_touch(a: &geo::Rect, b: &geo::Rect) -> bool { @@ -155,7 +165,7 @@ pub fn overlaps(ds: &Dataset, rows: &[usize]) -> Checked { } let inter = a.intersection(b); // Shared edges leave slivers of floating-point area; a square metre is a real overlap. - if inter.unsigned_area() > 1.0 { + if inter.unsigned_area() > least_area() { out.push(TopologyError { rows: vec![*ra, *rb], at: centre(&inter) }); if out.len() >= MAX_ERRORS { return Checked::partial(out); @@ -176,7 +186,7 @@ pub fn gaps(ds: &Dataset, rows: &[usize]) -> Checked { for poly in &u.0 { for hole in poly.interiors() { let mp = geo::MultiPolygon::new(vec![geo::Polygon::new(hole.clone(), vec![])]); - if mp.unsigned_area() > 1.0 { + if mp.unsigned_area() > least_area() { out.push(TopologyError { rows: Vec::new(), at: centre(&mp) }); if out.len() >= MAX_ERRORS { return Checked::partial(out); @@ -257,7 +267,7 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { _ => Vec::new(), }; for (p, closed) in paths { - let m: Vec = p.iter().map(|c| lonlat_to_plane(*c)).collect(); + let m: Vec = p.iter().map(|c| to_plane(*c)).collect(); let found = match self_crossing(&m, closed) { Ok(c) => c, // Stopped by Cancel, not by the limit: nothing to list (the run is dropped). @@ -268,7 +278,7 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { } }; if let Some(c) = found { - out.push(TopologyError { rows: vec![*r], at: plane_to_lonlat(c) }); + out.push(TopologyError { rows: vec![*r], at: from_plane(c) }); break; } } @@ -281,18 +291,20 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { /// Line ends that touch no other line (within `tol_m` metres). Line parts are indexed on a grid, /// so each end is measured only against parts near it; an end beyond 85.05° in a frame about its -/// pole (`PolarEnds`). +/// pole (`PolarEnds`). In a projected system's own plane, the tolerance is measured flat there, in +/// its unit ([`own_length`]), as the run's other distances are. pub fn dangles(ds: &Dataset, rows: &[usize], tol_m: f64) -> Checked { let lines: Vec<(usize, Vec>)> = rows .iter() .filter_map(|r| match ds.features.get(*r)?.geometry.as_ref()? { - Geometry::Line(parts) => Some((*r, parts.iter().map(|p| p.iter().map(|c| lonlat_to_plane(*c)).collect()).collect())), + Geometry::Line(parts) => Some((*r, parts.iter().map(|p| p.iter().map(|c| to_plane(*c)).collect()).collect())), _ => None, }) .collect(); + let own_tol = own_length(tol_m); // Within ±85.05°, tolerance in the plane's meters grows with latitude; index with the largest // it can be there. - let max_tol = tol_m / MAX_LAT.to_radians().cos(); + let max_tol = own_tol.unwrap_or(tol_m / MAX_LAT.to_radians().cos()); let mut ext = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); for c in lines.iter().flat_map(|(_, ps)| ps.iter().flatten()) { ext = (ext.0.min(c.x), ext.1.min(c.y), ext.2.max(c.x), ext.3.max(c.y)); @@ -345,16 +357,15 @@ pub fn dangles(ds: &Dataset, rows: &[usize], tol_m: f64) -> Checked { } for (end, at_start) in [(part.first(), true), (part.last(), false)] { let Some(end) = end else { continue }; - let at = plane_to_lonlat(*end); - let lat = at.y; - let touches = if lat.abs() > MAX_LAT { + let at = from_plane(*end); + let touches = if plane() == Plane::Analysis && at.y.abs() > MAX_LAT { let polar = polar.get_or_insert_with(|| PolarEnds::new(&lines, &grid, cells)); match polar.meets((li, pi, at_start), (*end, at), tol_m, &mut work) { Ok(touches) => touches, Err(WorkLimit) => return Checked::partial(out), } } else { - let tol = tol_m / lat.to_radians().cos().max(0.01); + let tol = own_tol.unwrap_or_else(|| tol_m / at.y.to_radians().cos().max(0.01)); let near = grid.get(&cells.key(end.x, end.y)).map(Vec::as_slice).unwrap_or(&[]); // The end's own part counts too, past the stretch next to the end (a line // curling back onto itself, like a 6, doesn't dangle there). @@ -1087,7 +1098,7 @@ pub fn not_covered(ds: &Dataset, rows: &[usize], by: &Dataset) -> Checked { _ => continue, }; for c in pts { - let m = lonlat_to_plane(c); + let m = to_plane(c); let p = geo::Point::new(m.x, m.y); let surrounded = match crate::convert::reaches_poles(c.y, c.y) { (true, _) => holds_north.get_or_insert_with(|| surrounds_pole(parts(), true)).0, @@ -1114,6 +1125,26 @@ mod tests { use super::*; use rustgis_data::GeometryType; + /// In a projected system's own plane, the dangle tolerance is measured flat there in its unit: + /// in feet, an end 2 ft (0.61 m) from another line touches it within a metre, not within half + /// of one; there are no poles to measure about (#2032 C2e-5). + #[test] + fn a_dangle_tolerance_is_in_the_systems_own_unit() { + use crate::convert::{EAST_NORTH, RunPlane, install}; + let _feet = install(RunPlane { plane: Plane::Own, unit_m: 0.3048, axes: EAST_NORTH }); + let c = Coord::new; + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![c(0.0, 0.0), c(100.0, 0.0)]])), vec![]); + ds.push(Some(Geometry::Line(vec![vec![c(102.0, 0.0), c(102.0, 100.0)]])), vec![]); + let ends = |tol_m: f64| dangles(&ds, &[0, 1], tol_m).errors.iter().map(|e| (e.rows.clone(), e.at)).collect::>(); + // Both lines' far ends dangle; the near ones touch within a metre. + assert_eq!(ends(1.0), [(vec![0], c(0.0, 0.0)), (vec![1], c(102.0, 100.0))]); + assert_eq!(ends(0.5).len(), 4); + // Places are given as the layer holds them, even past what a latitude can be. + ds.push(Some(Geometry::Line(vec![vec![c(0.0, 1e7), c(1.0, 1e7)]])), vec![]); + assert!(dangles(&ds, &[2], 1.0).errors.iter().all(|e| e.at.y == 1e7)); + } + #[test] fn holes_are_taken_from_an_outline_in_one_pass() { // Holes overlapping each other, one running across two stretches, one covering a stretch. diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 0a64dd7719..161ebe6463 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2400,9 +2400,11 @@ struct TopologyChecked { /// Checks each rule and its query on the worker, with Cancel between rows/rules and counted /// query progress. Each rule's row indices and converted data are released before the next. /// One row's expression evaluation or coordinate conversion, the initial full-row copy for a -/// projected dataset, each complete latitude-validation pass and a gaps check's polygon union +/// dataset converted to longitude/latitude (or a covering layer converted into the checked one's +/// projected system), each complete latitude-validation pass and a gaps check's polygon union /// are indivisible library steps, checked around them; geometric checks otherwise look between -/// features. +/// features. A layer held in a projected system is checked in its own coordinates +/// ([`rustgis_analysis::works_in`]), the dangle tolerance flat there in its unit (#2032 C2e-5). /// A cancellable run takes no work limit (see `rustgis_analysis::topology`). fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result { use rustgis_analysis::topology as t; @@ -2440,10 +2442,30 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result Some(b.in_crs(crs).ok()?), + None => None, + }; + Some((crs, by)) + }); + let (work, data, by) = match own { + Some((crs, by)) => (crs, std::borrow::Cow::Borrowed(&i.data), by), + None => ( + rustgis_data::raster::Crs::LonLat, + i.data.in_lonlat().map_err(|e| named(&i.data.name, &i.layer, e))?, + i.by.as_ref().map(|b| b.in_lonlat().map_err(|e| named(&b.name, &i.by_layer, e))).transpose()?, + ), + }; + let _plane = rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(work)); + let lonlat = work == rustgis_data::raster::Crs::LonLat; rustgis_data::progress::check().map_err(|_| cancelled())?; - rustgis_analysis::validate_latitudes(&data, rows.iter().copied())?; + if lonlat { + rustgis_analysis::validate_latitudes(&data, rows.iter().copied())?; + } rustgis_data::progress::check().map_err(|_| cancelled())?; let checked = match (&i.rule, &by) { (TopologyRule::MustNotOverlap { .. }, _) => t::overlaps(&data, &rows), @@ -2451,7 +2473,9 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result t::self_intersections(&data, &rows), (TopologyRule::MustNotHaveDangles { .. }, _) => t::dangles(&data, &rows, tol), (TopologyRule::MustBeCoveredBy { .. }, Some(by)) => { - rustgis_analysis::validate_latitudes(by, 0..by.features.len())?; + if lonlat { + rustgis_analysis::validate_latitudes(by, 0..by.features.len())?; + } rustgis_data::progress::check().map_err(|_| cancelled())?; t::not_covered(&data, &rows, by) } @@ -2470,14 +2494,30 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result issue.at, + Some(to) => to.point(issue.at).filter(|c| c.is_finite()).ok_or_else(|| { + let feature = issue.rows.first().and_then(|&r| i.data.features.row(r)).map(|r| format!("feature {}", r.id())); + format!( + "{}: {} has a place in {} that can't be given in longitude/latitude", + i.layer, + feature.as_deref().unwrap_or("a gap"), + work.label() + ) + })?, + }; errors.push(crate::TopologyIssue { rule: i.rule.label().to_string(), layer: i.layer.clone(), rows: issue.rows, - lon: issue.at.x, - lat: issue.at.y, + lon: at.x, + lat: at.y, }); } query_errors.push(error); @@ -2792,8 +2832,10 @@ mod tests { assert!(errors[0] > 0, "the overlap is found"); } - /// A held layer with a place that can't be given in longitude/latitude is refused, naming - /// the layer once; a covering layer's is named as that layer, not the one checked. + /// A held layer with an error at a place that can't be given in longitude/latitude (checked in + /// its own system, #2032 C2e-5) is refused, naming the layer once; a covering layer the + /// checked one's system can't hold is checked in longitude/latitude, where its place that + /// can't be given there is refused, named as that layer, not the one checked. #[test] fn a_topology_refusal_names_its_layer_once() { let held = |name: &str, kind: GeometryType, far: bool| { @@ -2805,7 +2847,8 @@ mod tests { let shape = match kind { GeometryType::Polygon => Geometry::Polygon(vec![vec![ring]]), GeometryType::Point => Geometry::Point(Coord::new(x, y)), - _ => Geometry::Line(vec![ring]), + // Open, so its ends dangle there. + _ => Geometry::Line(vec![ring[..3].to_vec()]), }; ds.push(Some(shape), vec![]); ds @@ -2826,7 +2869,10 @@ mod tests { let mut s = Session::new(crate::Project::default()); s.map_mut().add_dataset(held("Cities", GeometryType::Point, false)); - s.map_mut().add_dataset(held("Countries", GeometryType::Polygon, true)); + // In UTM 33N, which UTM 32N can't hold there: the rule is checked in longitude/latitude. + let mut countries = held("Countries", GeometryType::Polygon, true); + countries.held_in = rustgis_data::raster::Crs::Epsg(32633); + s.map_mut().add_dataset(countries); s.run("topology.rules", &json!({"add": {"rule": "mustBeCoveredBy", "layer": "Cities", "by": "Countries"}})).unwrap(); let Err(e) = check_topology(&topology_checks(&s), 1.0) else { panic!("the check is refused") }; assert!(e.starts_with("Countries: feature"), "{e}"); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index f555191b69..4969ce46d8 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2580,3 +2580,56 @@ fn a_point_its_own_system_cant_give_is_said_as_such() { assert!(said.iter().any(|t| t.contains(&own)), "{said:?}"); assert!(!said.iter().any(|t| t.contains("beyond what")), "{said:?}"); } + +/// Topology is checked in a held layer's own system (#2032 C2e-5): overlapping squares, a +/// bow-tie, dangling ends (a tolerance of a metre, flat in UTM) and a point outside the blocks are +/// found as they are for the same layers in longitude/latitude, at the same places. +#[test] +fn topology_is_checked_in_a_held_layers_own_system() { + let o = (650_000.0, 5_400_000.0); + let at = |x: f64, y: f64| Coord::new(o.0 + x, o.1 + y); + let ring = |pts: &[(f64, f64)]| pts.iter().map(|&(x, y)| at(x, y)).collect::>(); + let blocks = vec![ + Geometry::Polygon(vec![vec![ring(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)])]]), + Geometry::Polygon(vec![vec![ring(&[(50.0, 0.0), (150.0, 0.0), (150.0, 100.0), (50.0, 100.0), (50.0, 0.0)])]]), + Geometry::Polygon(vec![vec![ring(&[(300.0, 0.0), (400.0, 100.0), (400.0, 0.0), (300.0, 100.0), (300.0, 0.0)])]]), + ]; + let paths = vec![ + Geometry::Line(vec![ring(&[(0.0, 200.0), (100.0, 200.0)])]), + // Starts half a metre from the first's end: they touch. + Geometry::Line(vec![ring(&[(100.5, 200.0), (200.0, 250.0)])]), + // Starts five metres from it: dangles. + Geometry::Line(vec![ring(&[(100.0, 205.0), (100.0, 300.0)])]), + ]; + let wells = vec![Geometry::Point(at(50.0, 50.0)), Geometry::Point(at(1000.0, 1000.0))]; + let to_lonlat = |g: &Geometry| g.map_coords(&|c| UTM.to(Crs::LonLat).unwrap().point(c).unwrap()); + let checked = |crs: Crs| { + let mut s = Session::new(Project::default()); + for (name, kind, geoms) in + [("Blocks", GeometryType::Polygon, &blocks), ("Paths", GeometryType::Polyline, &paths), ("Wells", GeometryType::Point, &wells)] + { + let geoms = geoms.iter().map(|g| if crs == UTM { g.clone() } else { to_lonlat(g) }).collect(); + add_in(&mut s, name, kind, geoms, crs); + } + for rule in [ + json!({"rule": "mustNotOverlap", "layer": "Blocks"}), + json!({"rule": "mustNotSelfIntersect", "layer": "Blocks"}), + json!({"rule": "mustNotHaveDangles", "layer": "Paths"}), + json!({"rule": "mustBeCoveredBy", "layer": "Wells", "by": "Blocks"}), + ] { + s.run("topology.rules", &json!({"add": rule})).unwrap(); + } + s.run("topology.validate", &json!({"toleranceM": 1.0})).unwrap(); + assert_eq!(s.map().layer_by_name("Paths").unwrap().dataset.coord_crs(), crs); + s.topology_errors.clone() + }; + let (a, b) = (checked(Crs::LonLat), checked(UTM)); + let found = |e: &[crate::TopologyIssue]| e.iter().map(|e| (e.rule.clone(), e.rows.clone())).collect::>(); + assert_eq!(found(&a), found(&b)); + // An overlap, a bow-tie, four dangling ends (the first line's start, the second's end, both + // of the third's) and a well outside the blocks. + assert_eq!(a.len(), 1 + 1 + 4 + 1, "{a:?}"); + for (p, q) in a.iter().zip(&b) { + assert!((p.lon - q.lon).abs() < 1e-6 && (p.lat - q.lat).abs() < 1e-6, "{p:?} vs {q:?}"); + } +} diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 663b15e688..b216001a37 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -156,6 +156,12 @@ you edit the value or choose units; click **Apply elevation** to apply the new i Primary rows follow the layer's definition query, independently of selection, time windows and display filters. For **must be covered by**, every resident row of the covering layer supplies the reference coverage; its map filters do not narrow that reference set. + A layer held in a projected system is checked in its own coordinates, as the analysis tools + work in it: the dangle tolerance (`toleranceM`, 1 m by default) is measured flat there in its + unit, an overlap or gap counts from a square metre of it, and a covering layer is converted + into it (one that system can't hold is checked in longitude/latitude, as before). An error at a + place that can't be given in longitude/latitude, where the Error Inspector would zoom, refuses + the check, naming the layer and feature. On the desktop the check runs in the background, so the map stays in use: the status bar shows **Error Inspector** with its progress and **Cancel**, and a check that can be cancelled takes any amount of work (a gaps rule first joins all its polygons in one step, which From caa45f4af91501fc93b2164313cf605dc1f2f74b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 11:03:15 +0100 Subject: [PATCH 2/3] Review: a covering layer's fallback and bent edges said, Cancel kept --- crates/engine/src/cmd/design.rs | 51 ++++++++++++++++++++------ crates/engine/src/tests/held_layers.rs | 28 ++++++++++++++ docs/user-guide/editing.md | 4 +- 3 files changed, 71 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 161ebe6463..2203f6d2ef 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2395,6 +2395,9 @@ struct TopologyChecked { incomplete: Vec, skipped: Vec, query_errors: Vec>, + /// What changed how a rule was checked: one checked in longitude/latitude, not its layer's + /// own system, and a covering layer's edges bent by their conversion into it (#2032 C2e-5). + notes: Vec, } /// Checks each rule and its query on the worker, with Cancel between rows/rules and counted @@ -2413,6 +2416,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result Result Some(b.in_crs(crs).ok()?), - None => None, - }; - Some((crs, by)) - }); + // tools work in it (#2032 C2e-5), its covering layer converted into it (a copy of it, when + // it is held in another system), with a notice when its edges bend there, as a tool's. One + // that system can't hold sends the rule to longitude/latitude, and says so. + let mut own = None; + if let Some(crs) = Some(i.data.coord_crs()).filter(|c| rustgis_analysis::works_in(*c)) { + match i.by.as_ref().map(|b| b.in_crs(crs)).transpose() { + Ok(by) => own = Some((crs, by)), + Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => { + return Err(cancelled()); + } + Err(e) => notes.push(format!( + "{} on '{}': checked in longitude/latitude, as '{}' can't be held in {}: {e}", + i.rule.label(), + i.layer, + i.by_layer, + crs.label() + )), + } + } + if let (Some((crs, Some(std::borrow::Cow::Owned(converted)))), Some(original)) = (&own, &i.by) { + let (n, far) = super::gp::bent_edges(original, converted, *crs).map_err(|e| named(&original.name, &i.by_layer, e))?; + if n > 0 { + notes.push(format!( + "{} on '{}': {n} edge(s) of '{}', converted into {}, are taken straight there, up to {far:.0} m from where a check in longitude/latitude takes them; their vertices are where they were", + i.rule.label(), + i.layer, + i.by_layer, + crs.label() + )); + } + } let (work, data, by) = match own { Some((crs, by)) => (crs, std::borrow::Cow::Borrowed(&i.data), by), None => ( @@ -2522,7 +2548,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result CmdResult { super::gp::record_read(s, TOPOLOGY_AHEAD, p, recorded); return answer; } - let TopologyChecked { errors, incomplete, skipped, query_errors } = found?; + let TopologyChecked { errors, incomplete, skipped, query_errors, notes } = found?; + for note in notes { + s.warn(note); + } // Rules whose layer, or covering layer, isn't on the map are checked for nothing: said. let unchecked: Vec = s .map() diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 4969ce46d8..e41932ebbe 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2633,3 +2633,31 @@ fn topology_is_checked_in_a_held_layers_own_system() { assert!((p.lon - q.lon).abs() < 1e-6 && (p.lat - q.lat).abs() < 1e-6, "{p:?} vs {q:?}"); } } + +/// A covering layer converted into a held layer's system for its topology check says when its long +/// edges, straight there, run more than a metre from where a check in longitude/latitude takes +/// them; one that system can't hold sends the rule to longitude/latitude, and says so; one in the +/// same system says nothing (#2032 C2e-5). +#[test] +fn a_covering_layers_conversion_is_said() { + let said = |cover: Geometry, crs: Crs, checked: Crs| { + let mut s = Session::new(Project::default()); + add_held(&mut s, "Wells", GeometryType::Point, vec![Geometry::Point(Coord::new(11.5, 48.7))], checked); + add_held(&mut s, "Cover", GeometryType::Polygon, vec![cover], crs); + s.run("topology.rules", &json!({"add": {"rule": "mustBeCoveredBy", "layer": "Wells", "by": "Cover"}})).unwrap(); + let mark = s.notice_mark(); + s.run("topology.validate", &json!({})).unwrap(); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("'Cover'")).collect::>() + }; + let box_of = |w: f64, s: f64, e: f64, n: f64| { + Geometry::Polygon(vec![vec![vec![Coord::new(w, s), Coord::new(e, s), Coord::new(e, n), Coord::new(w, n), Coord::new(w, s)]]]) + }; + // A degree-wide box: its east–west edges follow their parallels in longitude/latitude, and are + // chords in UTM, some 120 m away. + let bent = said(box_of(11.0, 48.0, 12.0, 49.0), Crs::LonLat, UTM); + assert!(bent.len() == 1 && bent[0].contains("edge(s) of 'Cover', converted into"), "{bent:?}"); + assert!(said(box_of(11.0, 48.0, 12.0, 49.0), UTM, UTM).is_empty(), "the same system: nothing to say"); + // Reaching the South Pole, which the NSIDC north polar stereographic system can't hold. + let fell_back = said(box_of(0.0, -90.0, 10.0, -89.0), Crs::LonLat, Crs::Epsg(3413)); + assert!(fell_back.len() == 1 && fell_back[0].contains("checked in longitude/latitude"), "{fell_back:?}"); +} diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index b216001a37..ea592106e8 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -159,7 +159,9 @@ you edit the value or choose units; click **Apply elevation** to apply the new i A layer held in a projected system is checked in its own coordinates, as the analysis tools work in it: the dangle tolerance (`toleranceM`, 1 m by default) is measured flat there in its unit, an overlap or gap counts from a square metre of it, and a covering layer is converted - into it (one that system can't hold is checked in longitude/latitude, as before). An error at a + into it, with a notice when its long edges, taken straight there, run more than a metre from + where a check in longitude/latitude takes them. A rule whose covering layer that system can't + hold is checked in longitude/latitude instead, and says so. An error at a place that can't be given in longitude/latitude, where the Error Inspector would zoom, refuses the check, naming the layer and feature. On the desktop the check runs in the background, so the map stays in use: the status bar From cb1054f80781d676bf014a958bc9adc0498feca1 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 11:50:50 +0100 Subject: [PATCH 3/3] Review: topology notices one per kind (with the reason a rule fell back), world projections named in the guide; Service Area lines held in the network's system as they are added (#2766 follow-up) --- crates/analysis/src/tools/network_analysis.rs | 26 ++++++++-- crates/engine/src/cmd/design.rs | 49 ++++++++++--------- crates/engine/src/tests/held_layers.rs | 6 ++- docs/user-guide/editing.md | 9 ++-- 4 files changed, 57 insertions(+), 33 deletions(-) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 3c921c2108..282eca4555 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -310,6 +310,26 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result>| -> Result>, String> { + if to_own.is_identity() { + return Ok(lines); + } + lines + .into_iter() + .map(|part| { + part.into_iter() + .map(|c| { + to_own.point(c).filter(|c| c.is_finite()).ok_or_else(|| { + format!("{TOOL}: a place it reached can't be held in {}, the system of '{}'", ds.coord_crs().label(), ds.name) + }) + }) + .collect() + }) + .collect() + }; for ((row, band, facility), lines) in parts { crate::control::check()?; let Some(f) = ds.features.get(row) else { continue }; @@ -318,11 +338,9 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result, skipped: Vec, query_errors: Vec>, - /// What changed how a rule was checked: one checked in longitude/latitude, not its layer's - /// own system, and a covering layer's edges bent by their conversion into it (#2032 C2e-5). - notes: Vec, + /// What changed how a rule was checked (#2032 C2e-5), said once per kind: rules checked in + /// longitude/latitude, not their layer's own system, as it can't hold their covering layer; + /// and covering layers whose edges bend by their conversion into it (how many, how far). + fell_back: Vec, + bent: Vec<(String, usize, f64)>, } /// Checks each rule and its query on the worker, with Cancel between rows/rules and counted @@ -2416,7 +2418,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result Result own = Some((crs, by)), Err(e) if matches!(rustgis_data::DataError::of_conversion(e.clone()), rustgis_data::DataError::Cancelled) => { return Err(cancelled()); } - Err(e) => notes.push(format!( - "{} on '{}': checked in longitude/latitude, as '{}' can't be held in {}: {e}", - i.rule.label(), - i.layer, - i.by_layer, - crs.label() - )), + Err(e) => fell_back.push(format!("{} on '{}' ('{}' in {}: {e})", i.rule.label(), i.layer, i.by_layer, crs.label())), } } if let (Some((crs, Some(std::borrow::Cow::Owned(converted)))), Some(original)) = (&own, &i.by) { let (n, far) = super::gp::bent_edges(original, converted, *crs).map_err(|e| named(&original.name, &i.by_layer, e))?; if n > 0 { - notes.push(format!( - "{} on '{}': {n} edge(s) of '{}', converted into {}, are taken straight there, up to {far:.0} m from where a check in longitude/latitude takes them; their vertices are where they were", - i.rule.label(), - i.layer, - i.by_layer, - crs.label() - )); + bent.push((format!("'{}' for {} on '{}' ({n}, into {})", i.by_layer, i.rule.label(), i.layer, crs.label()), n, far)); } } let (work, data, by) = match own { @@ -2548,7 +2539,7 @@ fn check_topology(inputs: &[TopologyInput], tol: f64) -> Result CmdResult { super::gp::record_read(s, TOPOLOGY_AHEAD, p, recorded); return answer; } - let TopologyChecked { errors, incomplete, skipped, query_errors, notes } = found?; - for note in notes { - s.warn(note); + let TopologyChecked { errors, incomplete, skipped, query_errors, fell_back, bent } = found?; + if !fell_back.is_empty() { + s.warn(format!( + "{} topology rule(s) checked in longitude/latitude, as their layer's own system can't hold their covering layer: {}", + fell_back.len(), + fell_back.join(", ") + )); + } + if !bent.is_empty() { + let n: usize = bent.iter().map(|(_, n, _)| n).sum(); + let far = bent.iter().map(|(.., far)| *far).fold(0.0, f64::max); + let which = bent.iter().map(|(which, ..)| which.as_str()).collect::>().join(", "); + s.warn(format!( + "{n} edge(s) of covering layers converted into their checked layer's system are taken straight there, up to {far:.0} m from where a check in longitude/latitude takes them; their vertices are where they were: {which}" + )); } // Rules whose layer, or covering layer, isn't on the map are checked for nothing: said. let unchecked: Vec = s diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 40b32da7af..a9aeb70555 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2672,6 +2672,8 @@ fn a_moved_label_the_layers_system_cant_hold_is_said() { } else { assert_eq!(a.labels.default.moved.len(), 1); } + } +} /// Topology is checked in a held layer's own system (#2032 C2e-5): overlapping squares, a /// bow-tie, dangling ends (a tolerance of a metre, flat in UTM) and a point outside the blocks are @@ -2747,9 +2749,9 @@ fn a_covering_layers_conversion_is_said() { // A degree-wide box: its east–west edges follow their parallels in longitude/latitude, and are // chords in UTM, some 120 m away. let bent = said(box_of(11.0, 48.0, 12.0, 49.0), Crs::LonLat, UTM); - assert!(bent.len() == 1 && bent[0].contains("edge(s) of 'Cover', converted into"), "{bent:?}"); + assert!(bent.len() == 1 && bent[0].contains("edge(s) of covering layers converted") && bent[0].contains("'Cover' for"), "{bent:?}"); assert!(said(box_of(11.0, 48.0, 12.0, 49.0), UTM, UTM).is_empty(), "the same system: nothing to say"); // Reaching the South Pole, which the NSIDC north polar stereographic system can't hold. let fell_back = said(box_of(0.0, -90.0, 10.0, -89.0), Crs::LonLat, Crs::Epsg(3413)); - assert!(fell_back.len() == 1 && fell_back[0].contains("checked in longitude/latitude"), "{fell_back:?}"); + assert!(fell_back.len() == 1 && fell_back[0].starts_with("1 topology rule(s) checked in longitude/latitude"), "{fell_back:?}"); } diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index ea592106e8..b3103294c9 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -157,13 +157,14 @@ you edit the value or choose units; click **Apply elevation** to apply the new i and display filters. For **must be covered by**, every resident row of the covering layer supplies the reference coverage; its map filters do not narrow that reference set. A layer held in a projected system is checked in its own coordinates, as the analysis tools - work in it: the dangle tolerance (`toleranceM`, 1 m by default) is measured flat there in its + work in it. The dangle tolerance (`toleranceM`, 1 m by default) is measured flat there in its unit, an overlap or gap counts from a square metre of it, and a covering layer is converted into it, with a notice when its long edges, taken straight there, run more than a metre from where a check in longitude/latitude takes them. A rule whose covering layer that system can't - hold is checked in longitude/latitude instead, and says so. An error at a - place that can't be given in longitude/latitude, where the Error Inspector would zoom, refuses - the check, naming the layer and feature. + hold is checked in longitude/latitude instead, and says so. A layer in Web Mercator, another + world projection or a geographic system is checked in longitude/latitude, its dangle tolerance + on the ground. An error at a place that can't be given in longitude/latitude, where the Error + Inspector would zoom, refuses the check, naming the layer and feature. On the desktop the check runs in the background, so the map stays in use: the status bar shows **Error Inspector** with its progress and **Cancel**, and a check that can be cancelled takes any amount of work (a gaps rule first joins all its polygons in one step, which