From 73e63d2b743baf90ebb0764df3794e9b84104483 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 07:56:42 +0100 Subject: [PATCH 01/11] WFS and downloaded feature services asked in their own coordinate system (#2032 C2f-3b) A WFS feature type whose default system is a projected one RustGIS reads is asked for in it (SRSNAME=EPSG:), and an ArcGIS layer in its service's system (outSR by EPSG code, 3857 for 102100); the layer is held in it. Other systems keep today's CRS84 or EPSG:4326 request, and one RustGIS doesn't read is said in the listing. Each answer is checked before it is read: positions within degrees' range are read as longitude/latitude (a server that didn't convert); others are judged against the layer's bounds in the asked system, turned round when north first, and named in the asked system when the answer names none (added in place, no copy of the answer). --- crates/data/src/esripbf.rs | 16 +- crates/data/src/io.rs | 2 +- crates/data/src/ogc.rs | 1137 ++++++++++++++++++++++- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/service.rs | 63 +- crates/engine/src/cmd/service_group.rs | 2 +- crates/engine/src/tests.rs | 3 + crates/engine/src/tests/services_own.rs | 164 ++++ docs/user-guide/data-formats.md | 29 +- 9 files changed, 1374 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/tests/services_own.rs diff --git a/crates/data/src/esripbf.rs b/crates/data/src/esripbf.rs index cec58a9b96..844b872b9d 100644 --- a/crates/data/src/esripbf.rs +++ b/crates/data/src/esripbf.rs @@ -13,7 +13,7 @@ //! before them, as Esri writes them and as [`crate::filegdb`] reads them. A ring with no area is //! left out, and said. //! - The coordinate system is the answer's (`latestWkid`, `wkid`, else its WKT), read as -//! [`crate::filegdb`] reads one; geometry is turned to longitude/latitude. +//! [`crate::filegdb`] reads one; geometry is held in it when RustGIS converts it. //! - Fields: integers, object ids and dates are integers, dates in milliseconds since 1970 (UTC), //! as the same query gives them as GeoJSON; single and double precision numbers are doubles; //! strings, GUIDs, XML, date-only, time-only and offset timestamps are text, as the service @@ -123,6 +123,9 @@ pub struct Page { pub struct Losses { /// Features with a geometry, in an answer naming no coordinate system. pub no_crs: bool, + /// Features with a geometry, in an answer naming one RustGIS can't use, by a code or a WKT + /// (read as longitude/latitude, and said in the report). + pub unread_code: bool, /// Values that don't fit their field's type. pub unreadable: usize, /// Values, field names or aliases that aren't valid UTF-8. @@ -139,6 +142,7 @@ impl Losses { /// Adds another page's. pub fn add(&mut self, other: &Losses) { self.no_crs |= other.no_crs; + self.unread_code |= other.unread_code; self.unreadable = self.unreadable.saturating_add(other.unreadable); self.not_utf8 = self.not_utf8.saturating_add(other.not_utf8); self.flat_rings = self.flat_rings.saturating_add(other.flat_rings); @@ -321,12 +325,21 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result { report.messages.push("the coordinate system's WKT isn't valid UTF-8; the bytes that can't be read are replaced with U+FFFD"); } + let said_before = report.messages.len(); let (crs, to_lonlat) = crate::filegdb::esri_crs(code, wkt.as_deref(), &mut report)?; + // A WKT that couldn't be read (or converted) is read as longitude/latitude, and said so; + // a geographic one gives no system and says nothing. + let mut unread_code = crs.is_none() + && report + .messages + .get(said_before..) + .is_some_and(|m| m.iter().any(|m| m.ends_with("; coordinates are read as longitude/latitude"))); if crs.is_none() && wkt.is_none() && let Some(code) = code && crate::filegdb::crs_of_code(code) != Some(crate::raster::Crs::LonLat) { + unread_code = true; report.messages.push(format!("coordinate system {code} can't be used; coordinates are read as longitude/latitude")); } @@ -372,6 +385,7 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result let losses = Losses { // Assumed, so said: an answer that names no coordinate system. no_crs: any_geometry && code.is_none() && wkt.is_none(), + unread_code: any_geometry && unread_code, unreadable: tally.unreadable, not_utf8: tally.not_utf8, flat_rings: tally.flat_rings, diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c5a60512d5..7cd6486d77 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1457,7 +1457,7 @@ fn legacy_crs(decl: &Json) -> std::result::Result/N`, or CRS84 as `CRS84`, `OGC:CRS84`, /// `urn:ogc:def:crs:OGC::CRS84` or /// `http(s)://www.opengis.net/def/crs/OGC//CRS84` (any case, whitespace around). -fn is_epsg_or_crs84_name(name: &str) -> bool { +pub(crate) fn is_epsg_or_crs84_name(name: &str) -> bool { let up = name.trim().to_ascii_uppercase(); let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); let version = |s: &str| s.bytes().all(|b| b.is_ascii_digit() || b == b'.'); diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index bfc694faa4..57a069246b 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -1774,6 +1774,8 @@ fn wfs(url: &str, root: &Node) -> Service { note_past_read_limit(&mut service, left, "feature types", limit); note_copied_addresses(&mut service, per_layer, limit); } + // Types whose own systems RustGIS doesn't read, and the first of those systems. + let mut unread: (usize, Option) = (0, None); for ft in children(&list, "FeatureType").take(limit) { let Some(name) = child_text(&ft, "Name") else { continue }; let title = child_text(&ft, "Title").unwrap_or_else(|| name.clone()); @@ -1797,7 +1799,25 @@ fn wfs(url: &str, root: &Node) -> Service { let crs84 = ft.children().any(|c| { c.is_element() && matches!(local(&c), "DefaultCRS" | "OtherCRS" | "DefaultSRS" | "OtherSRS" | "SRS") && is_crs84(&text_of(&c)) }); - let srs = if crs84 { "urn:ogc:def:crs:OGC:1.3:CRS84" } else { "EPSG:4326" }; + // The type's own system first, when it is a projected one RustGIS reads (#2032): asked + // as `EPSG:`, east first at the servers tried, and its answer judged against the + // type's bounds (`place_answer`). A system RustGIS doesn't read is asked as above, and said. + let default = + ft.children().find(|c| c.is_element() && matches!(local(c), "DefaultCRS" | "DefaultSRS" | "SRS")).map(|c| text_of(&c)); + // By its canonical code: an alias (`EPSG:102100`) is asked as the system's own (3857), as + // ArcGIS's `outSR` is. + let own = default.as_deref().and_then(projected_system).map(|(_, crs)| format!("EPSG:{}", crs.epsg())); + // Said too: a projected one RustGIS reads but by a name it can't ask a server in (an + // `ESRI:` code, a WKT); a geographic one is asked as longitude/latitude anyway. + if own.is_none() + && let Some(d) = default.as_deref().map(str::trim) + && !is_crs84(d) + && unread_default(d) + { + unread.0 += 1; + unread.1.get_or_insert_with(|| d.to_string()); + } + let srs = own.as_deref().unwrap_or(if crs84 { "urn:ogc:def:crs:OGC:1.3:CRS84" } else { "EPSG:4326" }); // WFS 2.0 names the type and the count differently. let query = if version.starts_with('2') { format!( @@ -1826,10 +1846,24 @@ fn wfs(url: &str, root: &Node) -> Service { legends: Vec::new(), }); } + if let (n, Some(first)) = unread { + let which = if n == 1 { "1 feature type is".to_string() } else { format!("{n} feature types are") }; + service.notes.push(format!( + "{which} asked for in longitude/latitude, converted by the server: RustGIS can't ask for {} own system ({}{})", + if n == 1 { "its" } else { "their" }, + if n == 1 { "" } else { "the first: " }, + clip_code(&first) + )); + } cut_listing(&mut service); service } +/// A system's code as a note shows it: at most 80 characters. +fn clip_code(code: &str) -> String { + if code.chars().count() <= 80 { code.to_string() } else { format!("{}…", code.chars().take(80).collect::()) } +} + // --------------------------------------------------------------------------------------------- // Features over an area @@ -2330,7 +2364,15 @@ fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> { let (e, n) = merc_to_lonlat(x1, y1); lonlat_box(w.max(-180.0), s.max(-85.06), e.min(180.0), n.min(85.06)) } - _ => None, + // Another system RustGIS reads: its box converted, its edges followed. + _ => { + let crs = crate::filegdb::crs_of_code(u32::try_from(wkid).ok()?)?; + let b = crs.to(crate::raster::Crs::LonLat).ok()?.extent(&rustgis_geom::Extent { min_x: x0, min_y: y0, max_x: x1, max_y: y1 }); + if b.is_empty() { + return None; + } + lonlat_box(b.min_x.max(-180.0), b.min_y.max(-90.0), b.max_x.min(180.0), b.max_y.min(90.0)) + } } } @@ -2370,6 +2412,31 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { // Feature layers (FeatureServer, and a MapServer's layers): queried as GeoJSON, so only from a // service that allows queries: "Query", or "Data" on a MapServer (a cached basemap's // capabilities are often just "Map,Tilemap"). + // The service's own system, when it is a projected one RustGIS reads (#2032): its layers are + // asked in it, by its EPSG code (3857 for 102100), else in longitude/latitude. + let wkids: Vec = [ + "/spatialReference/latestWkid", + "/spatialReference/wkid", + "/fullExtent/spatialReference/latestWkid", + "/fullExtent/spatialReference/wkid", + ] + .iter() + .filter_map(|k| v.pointer(k).and_then(|w| w.as_u64()).and_then(|w| u32::try_from(w).ok())) + .filter(|w| *w != 0) + .collect(); + let own = wkids.iter().find_map(|&w| crate::filegdb::crs_of_code(w)); + let out_sr = own.and_then(own_system).map_or(4326, |c| u32::from(c.epsg())); + // Said when its features are asked in 4326 though its system is projected (a code RustGIS + // doesn't read, one without an EPSG code to ask by, or projected WKT only). + let asked_own = own.and_then(own_system).is_some() || own.is_some_and(|c| c == crate::raster::Crs::LonLat || c.is_geographic()); + let unread_system = wkids.first().map(u32::to_string).or_else(|| { + // A system given only as WKT has no code to ask for it by. + let wkt = ["/spatialReference/wkt", "/fullExtent/spatialReference/wkt"].iter().find_map(|k| v.pointer(k)?.as_str())?; + // A geographic one is asked as longitude/latitude anyway. Told by its keyword, not parsed: + // the service's text would be kept in the process's table of systems defined by files. + (!geographic_text(wkt)).then(|| "WKT only".to_string()) + }); + let unread_system = unread_system.filter(|_| !asked_own); let features = |service: &mut Service| { let queries = v .get("capabilities") @@ -2381,13 +2448,14 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { } return; } + let mut listed = false; for l in v.get("layers").and_then(|l| l.as_array()).into_iter().flatten().take(MAX_LISTED_LAYERS) { let (Some(id), Some(name)) = (l.get("id").and_then(|i| i.as_i64()), l.get("name").and_then(|n| n.as_str())) else { continue }; // Group layers have sub-layers and no features of their own. if l.get("subLayerIds").is_some_and(|s| s.as_array().is_some_and(|a| !a.is_empty())) { continue; } - let url = format!("{b}/{id}/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=4326&f=geojson"); + let url = format!("{b}/{id}/query?where=1%3D1&outFields=*&returnGeometry=true&outSR={out_sr}&f=geojson"); service.layers.push(ServiceLayer { zooms: None, name: id.to_string(), @@ -2399,6 +2467,12 @@ fn arcgis(url: &str, v: &serde_json::Value) -> Result { feature_info: None, legends: Vec::new(), }); + listed = true; + } + if let (true, Some(wkid)) = (listed, unread_system) { + service.notes.push(format!( + "its layers' features are asked for in longitude/latitude, converted by the server: RustGIS can't ask for its coordinate system ({wkid})" + )); } }; if lower.ends_with("/featureserver") { @@ -3446,6 +3520,9 @@ pub struct Pages { phase: Phase, /// The protocol buffer pages read, as one layer, and what reading them said. decoded: Option<(crate::Dataset, crate::ReadReport, crate::esripbf::Losses)>, + /// What the joined pages with positions say of their system ([`placed_as`]); `None` until a + /// page has positions. + placed_as: Option, /// The memory those pages take, in bytes, and the most they may ([`max_decoded_bytes`]). decoded_bytes: usize, decoded_budget: usize, @@ -3621,6 +3698,7 @@ fn start(url: &str, max: usize, pbf: bool) -> Step { from: url.to_string(), phase, decoded: None, + placed_as: None, decoded_bytes: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, @@ -3689,6 +3767,7 @@ fn read_first(url: &str, first: Vec, max: usize, paging: Option self.decoded = Some((page.dataset, report, page.losses)), + None => { + self.placed_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url).is_some()); + self.decoded = Some((page.dataset, report, page.losses)); + } Some((ds, joined, losses)) => { // By name and type: the first page's aliases are kept. let same = |a: &crate::Field, b: &crate::Field| a.name == b.name && a.ty == b.ty; if ds.fields.len() != page.dataset.fields.len() || !ds.fields.iter().zip(&page.dataset.fields).all(|(a, b)| same(a, b)) { return self.stop(format!("the page after feature {read} has other fields than the first; the rest aren't read")); } - // Each page's positions are in its own system, and its geometries of its own type; - // a page that doesn't say one is joined. - let other_crs = ds.crs.is_some() && page.dataset.crs.is_some() && ds.crs != page.dataset.crs; + // Each page's positions are read as it says: the pages joined say the same of their + // system (`placed_as`), or their positions would be taken for another's. A page + // without positions says nothing, and until a page has some, the joined pages take + // the system of the next. + let page_as = placed_as(&page.dataset, &page.losses, asked_system(&self.url).is_some()); + let other_crs = matches!((&self.placed_as, &page_as), (Some(joined), Some(this)) if joined != this); let none = crate::GeometryType::None; let other_type = ds.geometry_type != none && page.dataset.geometry_type != none && ds.geometry_type != page.dataset.geometry_type; @@ -4103,6 +4188,12 @@ impl Pages { let what = if other_crs { "coordinate system" } else { "geometry type" }; return self.stop(format!("the page after feature {read} has another {what} than the first; the rest aren't read")); } + // Joined: the first page with positions gives the system. + if self.placed_as.is_none() && page_as.is_some() { + ds.crs = page.dataset.crs; + ds.held_in = page.dataset.held_in; + self.placed_as = page_as; + } // A page without features may not say its geometry type. if ds.geometry_type == none { ds.geometry_type = page.dataset.geometry_type; @@ -4221,7 +4312,35 @@ impl Pages { } else { note }; - if let Some((ds, mut report, losses)) = self.decoded.take() { + if let Some((mut ds, mut report, mut losses)) = self.decoded.take() { + // Pages naming no system, asked for in a projected one: held in it as they came (as + // a GeoJSON answer naming none is), and said so, not read as longitude/latitude; + // unless their positions are in degrees (a server that didn't convert), read so. + // In degrees as each page joined was judged (`placed_as`), not by the pages' extent + // together: pages in degrees in different axis orders stay in degrees. + let degrees = self.placed_as.is_some_and(|p| p.degrees); + // Only when no page named one: a system a page named is kept. + if (losses.no_crs || losses.unread_code) + && ds.crs.is_none() + && let Some(asked) = asked_system(&self.url) + && !degrees + { + ds.held_in = asked; + ds.crs = Some(asked); + let asked = asked.label(); + if std::mem::take(&mut losses.no_crs) { + report + .messages + .push(format!("the answer names no coordinate system; coordinates are read in {asked}, the system asked for")); + } + // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a + // GeoJSON answer's is), and its message says so. + for m in &mut report.messages { + if let Some(said) = m.strip_suffix("; coordinates are read as longitude/latitude") { + *m = format!("{said}; coordinates are read in {asked}, the system asked for"); + } + } + } report.messages.extend(losses.messages()); return Step::Decoded(Box::new(ds), report, note); } @@ -4275,17 +4394,36 @@ fn fits(extent: [f64; 4], bounds: [f64; 4]) -> bool { /// without keeping them: `[min x, min y, max x, max y]`, or `None` for an answer that isn't JSON /// or has no position. fn positions_extent(bytes: &[u8]) -> Option<[f64; 4]> { + scan_answer(bytes)?.0 +} + +/// What [`scan_answer`] keeps of an answer's outermost object: its `crs` member and its `type`. +#[derive(Default)] +struct Top { + crs: Option, + kind: Option, +} + +/// A GeoJSON answer read through once without keeping its features: the extent of its positions +/// (as [`positions_extent`] gives it), and its own `crs` member and `type`, when it has them; +/// `None` for an answer that isn't JSON. +fn scan_answer(bytes: &[u8]) -> Option<(Option<[f64; 4]>, Top)> { use serde::de::DeserializeSeed; let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + let mut top = Top::default(); let mut de = serde_json::Deserializer::from_slice(bytes); - Members { extent: &mut extent, depth: 0 }.deserialize(&mut de).ok()?; - (extent[0] <= extent[2] && extent[1] <= extent[3]).then_some(extent) + Members { extent: &mut extent, top: &mut top, depth: 0 }.deserialize(&mut de).ok()?; + // Text after the value: not JSON, left for the reader to refuse. + de.end().ok()?; + Some(((extent[0] <= extent[2] && extent[1] <= extent[3]).then_some(extent), top)) } /// A GeoJSON object (or an array of them) whose `features`, `geometry`, `geometries` and -/// `coordinates` are walked for [`positions_extent`]; its other members are skipped. +/// `coordinates` are walked for [`scan_answer`], and the outermost object's `crs` and `type` kept; +/// its other members are skipped. struct Members<'a> { extent: &'a mut [f64; 4], + top: &'a mut Top, depth: usize, } @@ -4308,7 +4446,14 @@ impl<'de> serde::de::Visitor<'de> for Members<'_> { while let Some(key) = map.next_key::()? { match key.as_str() { "features" | "geometry" | "geometries" if self.depth < 16 => { - map.next_value_seed(Members { extent: &mut *self.extent, depth: self.depth + 1 })?; + map.next_value_seed(Members { extent: &mut *self.extent, top: &mut *self.top, depth: self.depth + 1 })?; + } + "crs" if self.depth == 0 => { + self.top.crs = Some(map.next_value()?); + } + "type" if self.depth == 0 => { + let kind: serde_json::Value = map.next_value()?; + self.top.kind = kind.as_str().map(str::to_string); } "coordinates" => { map.next_value_seed(Positions { extent: &mut *self.extent, depth: 0 })?; @@ -4326,7 +4471,7 @@ impl<'de> serde::de::Visitor<'de> for Members<'_> { while seq.next_element::()?.is_some() {} return Ok(()); } - while seq.next_element_seed(Members { extent: &mut *self.extent, depth: self.depth + 1 })?.is_some() {} + while seq.next_element_seed(Members { extent: &mut *self.extent, top: &mut *self.top, depth: self.depth + 1 })?.is_some() {} Ok(()) } @@ -4476,15 +4621,24 @@ fn swap_geometry(g: &mut serde_json::Value, depth: usize) { /// answer that fits both ways (or neither), it can't tell, and nothing is turned. pub fn fix_axes(bytes: &[u8], bounds: Option<[f64; 4]>) -> Option> { let bounds = bounds?; - let [x0, y0, x1, y1] = positions_extent(bytes)?; - if fits([x0, y0, x1, y1], bounds) || !fits([y0, x0, y1, x1], bounds) { + if !latitude_first(positions_extent(bytes), Some(bounds)) { return None; } - let mut v: serde_json::Value = serde_json::from_slice(bytes).ok()?; // A GeoJSON answer is one object; anything else (a list of features) is left as it came. - let o = v.as_object_mut()?; - o.remove("crs"); - o.remove("bbox"); + rewritten(bytes, None, true) +} + +/// Whether positions whose extent is `extent` are latitude first, as [`fix_axes`] judges them +/// against the layer's longitude/latitude `bounds`: they miss them, and fit them turned round. +fn latitude_first(extent: Option<[f64; 4]>, bounds: Option<[f64; 4]>) -> bool { + let (Some(bounds), Some([x0, y0, x1, y1])) = (bounds, extent) else { return false }; + !fits([x0, y0, x1, y1], bounds) && fits([y0, x0, y1, x1], bounds) +} + +/// A GeoJSON answer `v` (one object) with its positions turned round and its boxes dropped; +/// `None` for anything else, left as it is. +fn turn_axes(v: &mut serde_json::Value) -> Option<()> { + v.as_object_mut()?.remove("bbox"); match v.get("type").and_then(|t| t.as_str()) { Some("FeatureCollection") => { for f in v.get_mut("features").and_then(|f| f.as_array_mut()).into_iter().flatten() { @@ -4501,9 +4655,445 @@ pub fn fix_axes(bytes: &[u8], bounds: Option<[f64; 4]>) -> Option> { swap_geometry(g, 0); } } - _ => swap_geometry(&mut v, 0), + _ => swap_geometry(v, 0), + } + Some(()) +} + +/// A projected system a service's features may be asked for in: one RustGIS reads, not in +/// degrees, with an EPSG code to name it by (Web Mercator's is 3857). +fn own_system(crs: crate::raster::Crs) -> Option { + (crs != crate::raster::Crs::LonLat && !crs.is_geographic() && crs.epsg() != 0).then_some(crs) +} + +/// The projected system a service names by `code` (`EPSG:2056`, `urn:ogc:def:crs:EPSG::2056`, +/// `http://www.opengis.net/def/crs/EPSG/0/2056`, or GeoServer's WFS 1.1 +/// `urn:x-ogc:def:crs:EPSG:2056`), with the EPSG number as written, when [`own_system`] takes it. +fn projected_system(code: &str) -> Option<(u32, crate::raster::Crs)> { + let code = code.trim(); + let x_ogc = code + .get(..23) + .filter(|p| p.eq_ignore_ascii_case("urn:x-ogc:def:crs:EPSG:")) + .and_then(|_| code.get(23..)) + .filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + .map(|n| format!("EPSG:{n}")); + let code = x_ogc.as_deref().unwrap_or(code); + if is_crs84(code) || !crate::io::is_epsg_or_crs84_name(code) { + return None; + } + let n = code.rsplit([':', '/']).next()?.parse().ok()?; + Some((n, own_system(crate::raster::Crs::parse(code).ok()?)?)) +} + +/// The projected system an [`Offer::Features`] address asks its answer in: a WFS GetFeature's +/// `SRSNAME`, or an ArcGIS layer query's `outSR` (a number). `None` for longitude/latitude, a +/// system RustGIS doesn't read and any other address: the answer is then read in the system its +/// own `crs` member names (longitude/latitude without one), latitude-first positions turned round +/// as [`fix_axes`] judges them. +pub fn asked_system(url: &str) -> Option { + let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); + if is("service", "wfs") && is("request", "getfeature") { + let srs = query_value(url, "srsname")?.replace("%3A", ":").replace("%3a", ":").replace("%2F", "/").replace("%2f", "/"); + projected_system(&srs).map(|(_, crs)| crs) + } else if is_arcgis_query(url) { + own_system(crate::filegdb::crs_of_code(query_value(url, "outSR")?.trim().parse().ok()?)?) + } else { + None + } +} + +/// Where a service's positions are, judged against its layer's bounds. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Placed { + /// In the system asked for, east first. + Asked, + /// In the system asked for, north first. + Turned, + /// In longitude/latitude: the server didn't answer in the system asked for. + LonLat, + /// It can't tell (no bounds, no positions, or they fit neither): in the system the answer + /// names when RustGIS reads it, else as asked (and said, see [`place_answer`]). + Unknown, +} + +/// The longitude/latitude `bounds` (west, south, east, north), widened by [`margin`], as a box in +/// `crs`: its edges' places there, sixteen along each; `None` when one has no place in it. +fn bounds_in(bounds: [f64; 4], crs: crate::raster::Crs) -> Option<[f64; 4]> { + let [w, s, e, n] = bounds; + let (mx, my) = (margin(w, e), margin(s, n)); + // Web Mercator has no place for the poles: a world layer's box is taken to its edge. + let pole = if crs == crate::raster::Crs::WebMercator { MERCATOR_EDGE } else { 90.0 }; + let (w, e, s, n) = ((w - mx).max(-180.0), (e + mx).min(180.0), (s - my).max(-pole), (n + my).min(pole)); + let t = crs.transformer().ok()?; + let mut out = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + const STEPS: usize = 16; + for i in 0..=STEPS { + let f = i as f64 / STEPS as f64; + let (x, y) = (w + (e - w) * f, s + (n - s) * f); + for (lon, lat) in [(x, s), (x, n), (w, y), (e, y)] { + let c = t.from_lonlat(rustgis_geom::Coord::new(lon, lat)).filter(|c| c.x.is_finite() && c.y.is_finite())?; + out = [out[0].min(c.x), out[1].min(c.y), out[2].max(c.x), out[3].max(c.y)]; + } + } + Some(out) +} + +/// The latitude Web Mercator ends at, north and south (its square's edge). +const MERCATOR_EDGE: f64 = 85.051_128_779_806_59; + +/// Whether the extent lies within the box. +fn inside(extent: [f64; 4], b: [f64; 4]) -> bool { + extent[0] >= b[0] && extent[1] >= b[1] && extent[2] <= b[2] && extent[3] <= b[3] +} + +/// What a page with positions says of its system: the one it names (`None`: none, or one by a +/// code RustGIS can't use, both read in the system asked for when it is projected), and, naming +/// none, whether its positions are in degrees (when a projected system was asked for). `None` for +/// a page without positions. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PlacedAs { + named: Option, + degrees: bool, + /// In degrees only north first: pages joined must agree, as they aren't turned round. + turned: bool, +} + +fn placed_as(ds: &crate::Dataset, losses: &crate::esripbf::Losses, projected_asked: bool) -> Option { + if !ds.features.iter().any(|f| f.geometry.is_some()) { + return None; + } + // Only where a projected system was asked for does it matter whether positions naming none + // are in degrees: otherwise they are read as longitude/latitude, as one naming WGS 84 is, so + // those pages join, as on main; one naming another system doesn't. + if !projected_asked { + let named = if losses.no_crs || losses.unread_code { None } else { ds.crs.filter(|c| *c != crate::raster::Crs::LonLat) }; + return Some(PlacedAs { named, degrees: true, turned: false }); + } + if losses.no_crs || losses.unread_code { + let e = ds.extent(); + let as_is = !e.is_empty() && in_degrees([e.min_x, e.min_y, e.max_x, e.max_y]); + let turned = !e.is_empty() && !as_is && in_degrees([e.min_y, e.min_x, e.max_y, e.max_x]); + return Some(PlacedAs { named: None, degrees: as_is || turned, turned }); + } + Some(PlacedAs { named: Some(ds.crs.unwrap_or(crate::raster::Crs::LonLat)), degrees: false, turned: false }) +} + +/// Whether a feature type's default system `d` (trimmed, not CRS84), not asked for in its own +/// system, is to be said: a projected one RustGIS can't ask a server for (a code it doesn't read, +/// an `ESRI:` code, PROJ or WKT text). A geographic one is asked as longitude/latitude anyway, and +/// a blank one says nothing. Only a name by code is parsed: a WKT or PROJ text from the server +/// would be kept in the process's table of systems defined by files. +fn unread_default(d: &str) -> bool { + if crate::io::is_epsg_or_crs84_name(d) { + return crate::raster::Crs::parse(d).map_or(true, |c| c != crate::raster::Crs::LonLat && !c.is_geographic()); + } + if let Some(n) = d.get(..5).filter(|p| p.eq_ignore_ascii_case("ESRI:")).and_then(|_| d[5..].trim().parse::().ok()) { + // As an ArcGIS service's code. + return crate::filegdb::crs_of_code(n).is_none_or(|c| c != crate::raster::Crs::LonLat && !c.is_geographic()); + } + !d.is_empty() && !geographic_text(d) +} + +/// A WFS GetFeature address asking for its features in a projected system ([`asked_system`]), +/// asked in `EPSG:4326` instead, as before RustGIS asked a type in its own system: for a server +/// that refuses the system it lists. `None` for any other address. +pub fn wfs_lonlat_fallback(url: &str) -> Option { + let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); + (is("service", "wfs") && is("request", "getfeature") && asked_system(url).is_some()) + .then(|| with_query_value(url, "SRSNAME", "EPSG:4326")) +} + +/// Whether a system given as text (WKT, or a PROJ string) is a geographic one, told by its +/// keyword without parsing it: a server's text isn't kept in the process's table of systems +/// defined by files. +fn geographic_text(text: &str) -> bool { + let t = text.trim_start().to_ascii_uppercase(); + ["GEOGCS", "GEOGCRS", "GEODCRS", "GEOGRAPHICCRS"].iter().any(|k| t.starts_with(k) && t[k.len()..].trim_start().starts_with('[')) + || ["+PROJ=LONGLAT", "+PROJ=LATLONG", "+PROJ=LONLAT", "+PROJ=LATLON"].iter().any(|k| t.split_whitespace().any(|w| w == *k)) +} + +/// Whether an extent lies within degrees' range, longitude first. +fn in_degrees(e: [f64; 4]) -> bool { + e[0] >= -180.0 && e[2] <= 180.0 && e[1] >= -90.0 && e[3] <= 90.0 +} + +/// Where an answer's positions (their `extent`) are. Positions within degrees' range are in +/// longitude/latitude, with or without bounds: a server that didn't answer in the system asked +/// for (a world layer's box in Web Mercator would hold them too). Projected data whose x lies +/// within ±180 and y within ±90 is taken for longitude/latitude too. +fn placed(extent: Option<[f64; 4]>, bounds: Option<[f64; 4]>, crs: crate::raster::Crs) -> Placed { + let Some([x0, y0, x1, y1]) = extent else { return Placed::Unknown }; + let turned = [y0, x0, y1, x1]; + if in_degrees([x0, y0, x1, y1]) || in_degrees(turned) { + return Placed::LonLat; + } + let Some(bounds) = bounds else { return Placed::Unknown }; + match bounds_in(bounds, crs) { + Some(b) if inside([x0, y0, x1, y1], b) => return Placed::Asked, + Some(b) if inside(turned, b) => return Placed::Turned, + _ => {} + } + if fits([x0, y0, x1, y1], bounds) || fits(turned, bounds) { Placed::LonLat } else { Placed::Unknown } +} + +/// What an answer's own `crs` member says, against the system asked for. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Named { + /// No member. + Absent, + /// The system asked for. + Asked, + /// Longitude/latitude. + LonLat, + /// Another system RustGIS reads: the answer is read in it. + Other, + /// One RustGIS doesn't read (as `EPSG:999999`, or an `ESRI:` code). + Unread, +} + +fn named(member: Option<&serde_json::Value>, crs: crate::raster::Crs) -> Named { + // (A `null` member is replaced, not put after: the reader would take the last one.) + let Some(member) = member else { return Named::Absent }; + let Some(name) = + member.pointer("/properties/name").and_then(|n| n.as_str()).filter(|_| member.get("type").and_then(|t| t.as_str()) == Some("name")) + else { + return Named::Unread; + }; + if is_crs84(name) { + return Named::LonLat; + } + if !crate::io::is_epsg_or_crs84_name(name) { + return Named::Unread; + } + match crate::raster::Crs::parse(name) { + Ok(crate::raster::Crs::LonLat) => Named::LonLat, + Ok(c) if c == crs => Named::Asked, + Ok(_) => Named::Other, + Err(_) => Named::Unread, + } +} + +/// The `crs` member naming `crs` as the GeoJSON reader takes it. +fn crs_member(crs: crate::raster::Crs) -> serde_json::Value { + serde_json::json!({"type": "name", "properties": {"name": format!("urn:ogc:def:crs:EPSG::{}", crs.epsg())}}) +} + +/// What [`place_answer`] assumed of an answer, to be said, once per kind with a count. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Assumed { + /// It named no system, and its positions couldn't be checked against the layer's bounds: read + /// in the system asked for. + Unnamed, + /// It named a system RustGIS doesn't read (or `null`): read in the system asked for. + Unread, + /// It named a system other than longitude/latitude over positions in degrees: read in + /// longitude/latitude. + InDegrees, + /// It named longitude/latitude over positions in the system asked for: read in it. + InAsked, + /// It named longitude/latitude over positions out of degrees' range: read as named. + NotDegrees, + /// It named no system, and its positions are in degrees though a projected system was asked + /// for (a server that didn't convert): read in longitude/latitude. + DegreesUnnamed, +} + +impl Assumed { + /// Its notice, `{n}` the number of answers. + pub fn template(self) -> &'static str { + match self { + Assumed::Unnamed => { + "{n} service answer(s) named no coordinate system and couldn't be checked against their layer's bounds: read in the system they were asked for" + } + Assumed::Unread => { + "{n} service answer(s) named a coordinate system RustGIS doesn't read: read in the system they were asked for" + } + Assumed::InDegrees => { + "{n} service answer(s) named a coordinate system other than longitude/latitude, but their positions are in degrees: read in longitude/latitude" + } + Assumed::InAsked => { + "{n} service answer(s) named longitude/latitude, but their positions lie in the system they were asked for: read in it" + } + Assumed::NotDegrees => { + "{n} service answer(s) named longitude/latitude, but their positions aren't in degrees' range: read as named" + } + Assumed::DegreesUnnamed => { + "{n} service answer(s) named no coordinate system, and their positions are in degrees though another system was asked for: read in longitude/latitude" + } + } + } +} + +/// A service's GeoJSON answer to `url` made ready to read: in the projected system `url` asks it +/// in ([`asked_system`]), with a `crs` member naming that system (as a server may leave it out, +/// or name it by a code RustGIS doesn't read) and its positions east first; else as +/// [`fix_axes`] turns it; as it came when there is nothing to change. +/// +/// The data decide. Positions within degrees' range are longitude/latitude (a server that didn't +/// answer in the system asked for), read as such. Others are judged against the layer's +/// longitude/latitude `bounds` from the capabilities in the asked system: positions north first +/// are turned round (as a server may write them for a system EPSG defines north first). An answer +/// naming another system RustGIS reads is read in it; with no bounds, or positions that fit none +/// of them, it is read as it names itself, else as asked. +/// +/// What it assumed is given back to be said: a system named that RustGIS doesn't read, or none +/// where the positions can't be checked, read as asked; a system named against what the positions +/// show. Positions turned round because the layer's bounds show them north first aren't said: +/// the bounds decide it, as they do for [`fix_axes`]. +/// +/// It runs to its end once called, with no Cancel check or progress count: one pass over the +/// downloaded answer, two when it is written again ([`rewritten`]). +/// +/// The common case, an answer in the system asked for that names it or none, takes no copy: a +/// member is added at its end, in place. Turning positions round, or replacing a member, reads +/// the whole answer, as [`fix_axes`] does. +pub fn place_answer(bytes: Vec, url: &str, bounds: Option<[f64; 4]>) -> (Vec, Option) { + let Some(crs) = asked_system(url) else { return (fix_axes(&bytes, bounds).unwrap_or(bytes), None) }; + let Some((extent, top)) = scan_answer(&bytes) else { return (bytes, None) }; + let named = named(top.crs.as_ref(), crs); + // Named in another system RustGIS reads: read in it, unless its positions are in degrees + // (judged without the bounds, which are for the system asked for). + let at = placed(extent, if named == Named::Other { None } else { bounds }, crs); + // The reader takes a `crs` member from a collection only: a lone feature or geometry in the + // system asked for is put in one (`rewritten`). + // (An object with no `type` isn't GeoJSON: named in place as before, for the reader to refuse.) + let collection = top.kind.as_deref().is_none_or(|k| k == "FeatureCollection"); + let as_asked = |bytes: Vec, turn: bool| rewritten(&bytes, Some(crs_member(crs)), turn).unwrap_or(bytes); + // Turned round when latitude first: as `fix_axes` judges it, from the extent read already, or + // when only that order lies within degrees' range. + let lonlat = |bytes: Vec, drop_member: bool| { + let only_turned = extent.is_some_and(|[x0, y0, x1, y1]| !in_degrees([x0, y0, x1, y1]) && in_degrees([y0, x0, y1, x1])); + // Turned by the bounds only into degrees' range. + let turn = only_turned || (latitude_first(extent, bounds) && extent.is_some_and(|[x0, y0, x1, y1]| in_degrees([y0, x0, y1, x1]))); + if turn || drop_member { rewritten(&bytes, None, turn).unwrap_or(bytes) } else { bytes } + }; + match (at, named) { + (Placed::LonLat, Named::LonLat) => (lonlat(bytes, false), None), + // Asked in a projected system, answered in degrees naming none: read so, and said. + (Placed::LonLat, Named::Absent) => (lonlat(bytes, false), Some(Assumed::DegreesUnnamed)), + // Read as it names itself; positions out of degrees' range are said (none: nothing to say). + (Placed::Unknown, Named::LonLat) => (lonlat(bytes, false), extent.map(|_| Assumed::NotDegrees)), + // Named as asked, by a code RustGIS doesn't read, or as another system, but in degrees: + // read as such, without the member. + (Placed::LonLat, _) => (lonlat(bytes, true), Some(Assumed::InDegrees)), + // Read in the system it names: a lone feature or geometry is put in a collection keeping + // its member, which the reader takes it from. + (_, Named::Other) => (if collection { bytes } else { rewritten(&bytes, top.crs.clone(), false).unwrap_or(bytes) }, None), + (Placed::Asked | Placed::Unknown, Named::Asked) => (if collection { bytes } else { as_asked(bytes, false) }, None), + (Placed::Asked | Placed::Unknown, Named::Absent) => { + let bytes = if collection { with_member(bytes, &crs_member(crs)) } else { as_asked(bytes, false) }; + // An answer with no positions (an empty page) has nothing to place, nor to say. + (bytes, (at == Placed::Unknown && extent.is_some()).then_some(Assumed::Unnamed)) + } + // (An empty page has nothing to place, nor to say.) + (_, Named::Unread) => (as_asked(bytes, at == Placed::Turned), extent.map(|_| Assumed::Unread)), + (_, Named::LonLat) => (as_asked(bytes, at == Placed::Turned), extent.map(|_| Assumed::InAsked)), + (Placed::Turned, Named::Asked | Named::Absent) => (as_asked(bytes, true), None), + } +} + +/// A GeoJSON answer written again with its `crs` member set to `member` (or removed), its +/// positions turned round when `turn`; `None` when it isn't one object. Given a member, a lone +/// feature or geometry is put in a collection, which the reader takes a `crs` from. +/// +/// Without turning, only the outermost object's members are read, each kept as its text, so the +/// peak is about twice the answer (it and the text written). Turning reads it whole, as +/// [`fix_axes`] does: some sixteen times the answer, measured on a 94 MB collection of polygons. +/// Either way it runs to its end with no Cancel check, as the answer's reading after it does. +fn rewritten(bytes: &[u8], member: Option, turn: bool) -> Option> { + if turn { + let mut v: serde_json::Value = serde_json::from_slice(bytes).ok()?; + v.as_object_mut()?.remove("crs"); + turn_axes(&mut v)?; + let v = match member { + None => v, + Some(m) => match v.get("type").and_then(|t| t.as_str()) { + Some("FeatureCollection") => { + v.as_object_mut()?.insert("crs".into(), m); + v + } + Some("Feature") => serde_json::json!({"type": "FeatureCollection", "crs": m, "features": [v]}), + Some(_) => { + serde_json::json!({"type": "FeatureCollection", "crs": m, "features": [{"type": "Feature", "geometry": v, "properties": {}}]}) + } + None => return None, + }, + }; + return serde_json::to_vec(&v).ok(); + } + use serde_json::value::RawValue; + let top: std::collections::BTreeMap = serde_json::from_slice(bytes).ok()?; + let kind: Option = top.get("type").and_then(|t| serde_json::from_str(t.get()).ok()); + // The object's members as written, but its `crs`. + let object = |out: &mut Vec| -> Option<()> { + out.push(b'{'); + for (i, (k, v)) in top.iter().filter(|(k, _)| k.as_str() != "crs").enumerate() { + if i > 0 { + out.push(b','); + } + serde_json::to_writer(&mut *out, k).ok()?; + out.push(b':'); + out.extend_from_slice(v.get().as_bytes()); + } + out.push(b'}'); + Some(()) + }; + let mut out = Vec::with_capacity(bytes.len() + 160); + match member { + None => object(&mut out)?, + Some(m) => { + let m = serde_json::to_string(&m).ok()?; + match kind.as_deref() { + Some("FeatureCollection") => { + object(&mut out)?; + out.pop(); + if top.keys().any(|k| k != "crs") { + out.push(b','); + } + out.extend_from_slice(b"\"crs\":"); + out.extend_from_slice(m.as_bytes()); + out.push(b'}'); + } + Some(k) => { + out.extend_from_slice(b"{\"type\":\"FeatureCollection\",\"crs\":"); + out.extend_from_slice(m.as_bytes()); + out.extend_from_slice(b",\"features\":["); + if k == "Feature" { + object(&mut out)?; + } else { + out.extend_from_slice(b"{\"type\":\"Feature\",\"geometry\":"); + object(&mut out)?; + out.extend_from_slice(b",\"properties\":{}}"); + } + out.extend_from_slice(b"]}"); + } + None => return None, + } + } + } + Some(out) +} + +/// A GeoJSON object's text with the member `crs` added at its end, in place, without reading +/// the rest (it may be large); text that isn't one object (or has a member of that name, which +/// [`place_answer`] has looked for) comes back unchanged. +fn with_member(mut bytes: Vec, crs: &serde_json::Value) -> Vec { + let Some(first) = bytes.iter().position(|b| !b.is_ascii_whitespace()) else { return bytes }; + let Some(last) = bytes.iter().rposition(|b| !b.is_ascii_whitespace()) else { return bytes }; + if last <= first || bytes.get(first) != Some(&b'{') || bytes.get(last) != Some(&b'}') { + return bytes; } - serde_json::to_vec(&v).ok() + let Ok(member) = serde_json::to_string(crs) else { return bytes }; + let empty = bytes.get(first + 1..last).is_some_and(|inner| inner.iter().all(u8::is_ascii_whitespace)); + bytes.truncate(last); + bytes.reserve_exact(member.len() + 8); + if !empty { + bytes.push(b','); + } + bytes.extend_from_slice(b"\"crs\":"); + bytes.extend_from_slice(member.as_bytes()); + bytes.push(b'}'); + bytes } #[cfg(test)] @@ -4699,8 +5289,41 @@ mod tests { assert_eq!(s.kind, "ArcGIS FeatureServer"); assert_eq!(s.layers.iter().map(|l| l.title.as_str()).collect::>(), ["Parcels", "Roads"]); assert!( - matches!(&s.layers[0].offer, Offer::Features { url } if url == "https://x.org/arcgis/rest/services/A/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=4326&f=geojson") + matches!(&s.layers[0].offer, Offer::Features { url } if url == "https://x.org/arcgis/rest/services/A/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=3857&f=geojson") + ); + assert!(!s.notes.iter().any(|n| n.contains("coordinate system")), "{:?}", s.notes); + // A full extent in another system RustGIS reads is its bounds, converted (Bern in LV95). + let lv95 = fs.replace( + r#""fullExtent": {"xmin": -1000000, "ymin": 0, "xmax": 1000000, "ymax": 1000000, "spatialReference": {"wkid": 102100, "latestWkid": 3857}}"#, + r#""fullExtent": {"xmin": 2550000, "ymin": 1150000, "xmax": 2650000, "ymax": 1250000, "spatialReference": {"wkid": 2056}}"#, ); + assert_ne!(lv95, fs); + let bern = parse("https://x.org/arcgis/rest/services/A/FeatureServer", lv95.as_bytes()).unwrap(); + let [w, so, e, n] = bern.layers[0].bbox.unwrap(); + assert!(w < 7.44 && e > 7.44 && so < 46.95 && n > 46.95 && e - w < 2.0 && n - so < 1.5, "{:?}", bern.layers[0].bbox); + // In longitude/latitude, or a system RustGIS doesn't read (said): asked in EPSG:4326. + // A system given only as WKT has no code to ask for it by: said too. + for (sr, note) in [ + (r#"{"wkid": 4326}"#, None), + (r#"{"wkid": 999999}"#, Some("999999")), + // An ESRI code RustGIS reads, with no EPSG code to ask a server by. + (r#"{"wkid": 102033}"#, Some("102033")), + (r#"{"wkt": "PROJCS[\"Local\"]"}"#, Some("WKT only")), + (r#"{"wkid": 0, "wkt": "PROJCS[\"Local\"]"}"#, Some("WKT only")), + ( + r#"{"wkt": "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"}"#, + None, + ), + ] { + let other = fs.replace(r#"{"wkid": 102100, "latestWkid": 3857}"#, sr); + let s = parse("https://x.org/arcgis/rest/services/A/FeatureServer", other.as_bytes()).unwrap(); + assert!(matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("&outSR=4326&")), "{sr}: {:?}", s.layers[0].offer); + let said: Vec<&String> = s.notes.iter().filter(|n| n.contains("RustGIS can't ask for its coordinate system")).collect(); + match note { + Some(code) => assert!(said.len() == 1 && said[0].ends_with(&format!("({code})")), "{sr}: {:?}", s.notes), + None => assert!(said.is_empty(), "{sr}: {:?}", s.notes), + } + } let b = s.layers[0].bbox.unwrap(); assert!((b[0] + 8.983).abs() < 0.01 && b[1].abs() < 1e-9, "{b:?}"); let tiled = r#"{"currentVersion": 10.9, "mapName": "World", "singleFusedMapCache": true, @@ -4978,11 +5601,76 @@ mod tests { "{:?}", s.layers[0].offer ); - // WFS 2.0 offering CRS84: asked for it, longitude first by definition. + // WFS 2.0 whose type is in a projected system RustGIS reads: asked in it (#2032). let v20 = r#"aurn:ogc:def:crs:EPSG::25832urn:ogc:def:crs:OGC:1.3:CRS84"#; let s = parse("https://x.org/wfs", v20.as_bytes()).unwrap(); assert!( - matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("VERSION=2.0.0") && url.contains("TYPENAMES=a") && url.contains("SRSNAME=urn:ogc:def:crs:OGC:1.3:CRS84&COUNT=")), + matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("VERSION=2.0.0") && url.contains("TYPENAMES=a") && url.contains("SRSNAME=EPSG:25832&COUNT=")), + "{:?}", + s.layers[0].offer + ); + assert!(s.notes.is_empty(), "{:?}", s.notes); + // Offering CRS84, in a geographic system or one RustGIS doesn't read: asked in CRS84, + // longitude first by definition, as before; the one it doesn't read is said. + for (default, note) in + // An ESRI code RustGIS reads, but no server is asked by: said too. + [ + ("urn:ogc:def:crs:EPSG::4258", false), + ("urn:ogc:def:crs:EPSG::999999", true), + ("urn:ogc:def:crs:OGC:1.3:CRS84", false), + ("ESRI:102033", true), + // A geographic ESRI code, and a blank default: nothing to say. + ("ESRI:4269", false), + ("", false), + ] + { + let caps = v20.replace("urn:ogc:def:crs:EPSG::25832", default); + let s = parse("https://x.org/wfs", caps.as_bytes()).unwrap(); + assert!( + matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("SRSNAME=urn:ogc:def:crs:OGC:1.3:CRS84&COUNT=")), + "{default}: {:?}", + s.layers[0].offer + ); + assert_eq!(s.notes.len(), usize::from(note), "{default}: {:?}", s.notes); + } + let caps = v20.replace("urn:ogc:def:crs:EPSG::25832", "urn:ogc:def:crs:EPSG::999999"); + let s = parse("https://x.org/wfs", caps.as_bytes()).unwrap(); + assert_eq!( + s.notes, + [ + "1 feature type is asked for in longitude/latitude, converted by the server: RustGIS can't ask for its own system (urn:ogc:def:crs:EPSG::999999)" + ] + ); + // An alias of Web Mercator: asked by its own code, as ArcGIS's `outSR` is. + let caps = v20.replace("urn:ogc:def:crs:EPSG::25832", "urn:ogc:def:crs:EPSG::102100"); + let s = parse("https://x.org/wfs", caps.as_bytes()).unwrap(); + assert!(matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("SRSNAME=EPSG:3857&")), "{:?}", s.layers[0].offer); + // A default given as PROJ text isn't parsed (a server's text isn't kept as a system): a + // projected one is said, a geographic one, told by its keyword, isn't. + let caps = v20.replace("urn:ogc:def:crs:EPSG::25832", "+proj=utm +zone=32 +datum=WGS84 +no_defs"); + let s = parse("https://x.org/wfs", caps.as_bytes()).unwrap(); + assert!(s.notes.iter().any(|n| n.contains("can't ask for its own system (+proj=utm")), "{:?}", s.notes); + let caps = v20.replace("urn:ogc:def:crs:EPSG::25832", "+proj=longlat +datum=WGS84 +no_defs"); + let s = parse("https://x.org/wfs", caps.as_bytes()).unwrap(); + assert!(s.notes.is_empty(), "{:?}", s.notes); + assert!( + geographic_text(" GEOGCS [\"x\"]") + && geographic_text("geogcrs[\"x\"]") + && !geographic_text("PROJCS[\"x\"]") + && !geographic_text("G") + ); + // The fallback for a server that refuses the system it lists: asked in EPSG:4326, the rest + // of the address kept; none for an address already in longitude/latitude. + let own = "https://x.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=t&SRSNAME=EPSG:2056&COUNT=10"; + assert_eq!( + wfs_lonlat_fallback(own).as_deref(), + Some("https://x.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=t&COUNT=10&SRSNAME=EPSG:4326") + ); + assert_eq!(wfs_lonlat_fallback(&own.replace("EPSG:2056", "EPSG:4326")), None); + // WFS 1.0 in a projected system: asked in it too. + let s = parse("https://old.example.org/wfs", v10.replace("EPSG:4326", "EPSG:2056").as_bytes()).unwrap(); + assert!( + matches!(&s.layers[0].offer, Offer::Features { url } if url.contains("SRSNAME=EPSG:2056&MAXFEATURES=")), "{:?}", s.layers[0].offer ); @@ -5058,6 +5746,406 @@ mod tests { assert!(fix_axes(deep.as_bytes(), hamburg).is_none()); } + /// A WFS or ArcGIS answer asked in a projected system is read in it (#2032): named when it + /// isn't, turned round when written north first, and read as longitude/latitude when the + /// server answered in it anyway; an answer naming another system is left to it. Judged + /// against the type's longitude/latitude bounds. + #[test] + fn answers_asked_in_their_own_system_are_read_in_it() { + let wfs = "https://x.org/wfs?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=a&OUTPUTFORMAT=application%2Fjson&SRSNAME=EPSG:2056&COUNT=50000"; + let lv95 = crate::raster::Crs::from_epsg(2056).unwrap(); + assert_eq!(asked_system(wfs), Some(lv95)); + assert_eq!(asked_system(&wfs.replace("EPSG:2056", "urn%3Aogc%3Adef%3Acrs%3AEPSG%3A%3A2056")), Some(lv95)); + assert_eq!(asked_system(&wfs.replace("EPSG:2056", "urn:x-ogc:def:crs:EPSG:2056")), Some(lv95)); + assert_eq!(projected_system("urn:x-ogc:def:crs:EPSG:2056"), Some((2056, lv95))); + let arcgis = + "https://x.org/arcgis/rest/services/A/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=2056&f=geojson"; + assert_eq!(asked_system(arcgis), Some(lv95)); + let mercator = arcgis.replace("outSR=2056", "outSR=3857"); + assert_eq!(asked_system(&arcgis.replace("outSR=2056", "outSR=102100")), Some(crate::raster::Crs::WebMercator)); + for lonlat in [ + wfs.replace("EPSG:2056", "EPSG:4326"), + wfs.replace("EPSG:2056", "urn:ogc:def:crs:OGC:1.3:CRS84"), + wfs.replace("EPSG:2056", "EPSG:4258"), + arcgis.replace("outSR=2056", "outSR=4326"), + ] { + assert_eq!(asked_system(&lonlat), None, "{lonlat}"); + } + let bern = Some([7.0, 46.5, 8.0, 47.2]); + let collection = |member: &str, x: f64, y: f64| { + format!( + r#"{{"type":"FeatureCollection",{member}"features":[{{"type":"Feature","properties":{{"n":1}},"geometry":{{"type":"Point","coordinates":[{x},{y}]}}}}]}}"# + ) + }; + let place = |text: &str, url: &str, bounds| place_answer(text.as_bytes().to_vec(), url, bounds).0; + let note = |text: &str, url: &str, bounds| place_answer(text.as_bytes().to_vec(), url, bounds).1; + let read = |bytes: &[u8]| { + let (ds, _) = crate::io::read_geojson(std::str::from_utf8(bytes).unwrap(), "a").unwrap(); + let Some(crate::Geometry::Point(c)) = ds.features.iter().next().unwrap().geometry.clone() else { panic!() }; + (ds.coord_crs(), c.x, c.y) + }; + let member = |name: &str| format!(r#""crs":{{"type":"name","properties":{{"name":"{name}"}}}},"#); + // No member: named, positions as they are, with or without bounds; without bounds to + // check them against, that is said. + let plain = collection("", 2_600_000.0, 1_200_000.0); + for bounds in [bern, None] { + let placed = place(&plain, wfs, bounds); + assert_eq!(read(&placed), (lv95, 2_600_000.0, 1_200_000.0)); + assert_eq!(place(&plain, arcgis, bounds), placed); + } + assert_eq!(note(&plain, wfs, bern), None); + // An empty page has nothing to say. + let empty_page = r#"{"type":"FeatureCollection","features":[]}"#; + assert_eq!(note(empty_page, wfs, None), None); + assert_eq!(note(empty_page, wfs, bern), None); + assert_eq!(note(&plain, wfs, None), Some(Assumed::Unnamed)); + // A lone feature, or a bare geometry, in the system asked for: put in a collection, which + // the reader takes the system from. + let feature = r#"{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[2600000,1200000]}}"#; + let point = r#"{"type":"Point","coordinates":[2600000,1200000]}"#; + for (lone, member) in + [(feature, ""), (point, ""), (feature, r#","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::2056"}}"#)] + { + let text = format!("{}{member}}}", &lone[..lone.len() - 1]); + assert_eq!(read(&place(&text, wfs, bern)), (lv95, 2_600_000.0, 1_200_000.0), "{text}"); + } + // Named as asked: as it came. + let named = collection(&member("urn:ogc:def:crs:EPSG::2056"), 2_600_000.0, 1_200_000.0); + assert_eq!(place(&named, wfs, bern), named.as_bytes()); + // North first: turned round and named. + let turned = collection(&member("urn:ogc:def:crs:EPSG::2056"), 1_200_000.0, 2_600_000.0); + assert_eq!(read(&place(&turned, wfs, bern)), (lv95, 2_600_000.0, 1_200_000.0)); + // Named by a code RustGIS doesn't read, or `null`: named as asked. + for odd in [member("EPSG:999999"), r#""crs":null,"#.to_string()] { + let text = collection(&odd, 2_600_000.0, 1_200_000.0); + assert_eq!(read(&place(&text, wfs, bern)), (lv95, 2_600_000.0, 1_200_000.0), "{odd}"); + assert_eq!(read(&place(&text, wfs, None)), (lv95, 2_600_000.0, 1_200_000.0), "{odd}"); + // Said. + for bounds in [bern, None] { + assert_eq!(note(&text, wfs, bounds), Some(Assumed::Unread), "{odd}"); + } + } + // Named as asked, in its bounds: nothing to say. + assert_eq!(note(&named, wfs, bern), None); + // Named longitude/latitude, but in the bounds in the system asked for: read in it, and said. + let lonlat_named = collection(&member("urn:ogc:def:crs:OGC:1.3:CRS84"), 2_600_000.0, 1_200_000.0); + assert_eq!(read(&place(&lonlat_named, wfs, bern)), (lv95, 2_600_000.0, 1_200_000.0)); + assert_eq!(note(&lonlat_named, wfs, bern), Some(Assumed::InAsked)); + // North first too: turned round, and said. + let lonlat_turned = collection(&member("urn:ogc:def:crs:OGC:1.3:CRS84"), 1_200_000.0, 2_600_000.0); + assert_eq!(read(&place(&lonlat_turned, wfs, bern)), (lv95, 2_600_000.0, 1_200_000.0)); + assert_eq!(note(&lonlat_turned, wfs, bern), Some(Assumed::InAsked)); + // In longitude/latitude after all, with or without bounds: read so, without a member + // saying otherwise, and turned round when latitude first. + let lonlat = crate::raster::Crs::LonLat; + for bounds in [bern, None] { + let answer = collection("", 7.44, 46.95); + assert_eq!(place(&answer, wfs, bounds), answer.as_bytes()); + // Naming none, though a projected system was asked for: said. + assert_eq!(note(&answer, wfs, bounds), Some(Assumed::DegreesUnnamed)); + for name in ["EPSG:2056", "EPSG:4326", "urn:ogc:def:crs:OGC:1.3:CRS84"] { + let named = collection(&member(name), 7.44, 46.95); + assert_eq!(read(&place(&named, wfs, bounds)), (lonlat, 7.44, 46.95), "{name} {bounds:?}"); + // A member naming the asked system over degrees is said; one naming degrees isn't. + assert_eq!(note(&named, wfs, bounds).is_some(), name == "EPSG:2056", "{name} {bounds:?}"); + } + } + let misnamed = collection(&member("EPSG:2056"), 46.95, 7.44); + assert_eq!(read(&place(&misnamed, wfs, bern)), (lonlat, 7.44, 46.95)); + assert_eq!(read(&place(&collection("", 46.95, 7.44), wfs, bern)), (lonlat, 7.44, 46.95)); + // A world layer in Web Mercator answered in longitude/latitude: its box there holds the + // degrees too, which are still read as such. + let world = Some([-180.0, -60.0, 180.0, 75.0]); + assert_eq!(read(&place(&collection("", 7.44, 46.95), &mercator, world)), (lonlat, 7.44, 46.95)); + let bern_3857 = collection("", 828_000.0, 5_934_000.0); + assert_eq!(read(&place(&bern_3857, &mercator, world)), (crate::raster::Crs::WebMercator, 828_000.0, 5_934_000.0)); + // A layer reaching the North Pole: its box is taken to Web Mercator's edge, so north-first + // positions are still turned round. (A whole world's box in Web Mercator holds positions + // either way round, and can't tell.) + let poles = Some([5.0, 45.0, 11.0, 90.0]); + assert_eq!(read(&place(&bern_3857, &mercator, poles)), (crate::raster::Crs::WebMercator, 828_000.0, 5_934_000.0)); + let north_first = collection("", 5_934_000.0, 828_000.0); + assert_eq!(read(&place(&north_first, &mercator, poles)), (crate::raster::Crs::WebMercator, 828_000.0, 5_934_000.0)); + // Named in another system RustGIS reads: read in it. + let other = collection(&member("EPSG:21781"), 600_000.0, 200_000.0); + assert_eq!(place(&other, wfs, bern), other.as_bytes()); + assert_eq!(note(&other, wfs, bern), None); + // A lone feature naming it: put in a collection keeping its member. + let lone_other = r#"{"type":"Feature","crs":{"type":"name","properties":{"name":"EPSG:21781"}},"properties":{},"geometry":{"type":"Point","coordinates":[600000,200000]}}"#; + assert_eq!(read(&place(lone_other, wfs, bern)), (crate::raster::Crs::from_epsg(21781).unwrap(), 600_000.0, 200_000.0)); + // Latitude first in degrees, with no bounds to judge by: only that order is in range, so + // it is turned round. + assert_eq!(read(&place(&collection("", 46.95, 120.0), wfs, None)), (lonlat, 120.0, 46.95)); + // Bounds don't turn positions out of degrees' range (stale bounds a margin away). + assert_eq!(read(&place(&collection("", 100.0, 45.0), wfs, Some([40.0, -90.0, 50.0, 90.0]))), (lonlat, 100.0, 45.0)); + // Unless its positions are in degrees: read so, and said. + let other_degrees = collection(&member("EPSG:21781"), 7.44, 46.95); + assert_eq!(read(&place(&other_degrees, wfs, bern)), (lonlat, 7.44, 46.95)); + assert_eq!(note(&other_degrees, wfs, bern), Some(Assumed::InDegrees)); + // Asked in longitude/latitude: as `fix_axes` has it. + let asked_lonlat = wfs.replace("EPSG:2056", "EPSG:4326"); + let lat_first = collection("", 46.95, 7.44); + assert_eq!(Some(place(&lat_first, &asked_lonlat, bern)), fix_axes(lat_first.as_bytes(), bern)); + // An empty object, surrounding whitespace, and text that isn't an object. + let empty = place(" {} \n", wfs, None); + assert_eq!(serde_json::from_slice::(&empty).unwrap()["crs"]["properties"]["name"], "urn:ogc:def:crs:EPSG::2056"); + let spaced = place(&format!("\n {plain} \n"), wfs, None); + assert_eq!(read(&spaced), (lv95, 2_600_000.0, 1_200_000.0)); + assert_eq!(place("[]", wfs, None), b"[]"); + assert_eq!(place("not json", wfs, bern), b"not json"); + // Text after the object: left as it came, for the reader to refuse. + let trailing = format!("{plain} x"); + assert_eq!(place(&trailing, wfs, None), trailing.as_bytes()); + // An area asked over a type asked in its own system: the box stays in longitude/latitude, + // latitude first as its name fixes. + let wfs11 = wfs.replace("VERSION=2.0.0", "VERSION=1.1.0"); + assert_eq!( + features_in_area(&wfs11, [7.0, 46.5, 8.0, 47.2]).unwrap(), + format!("{wfs11}&BBOX=46.5,7,47.2,8,urn:ogc:def:crs:EPSG::4326") + ); + } + + /// Protocol-buffer pages naming no system, asked for in a projected one (`outSR`), are held in + /// it as they came, and that is said, not read as longitude/latitude. + #[test] + fn pbf_pages_naming_no_system_are_held_in_the_system_asked_for() { + use crate::esripbf::tests::encode::{answer, feature, geometry, transform}; + let query = + "https://x.org/arcgis/rest/services/P/FeatureServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=2056&f=geojson"; + let layer = br#"{"objectIdField": "OBJECTID", "maxRecordCount": 1000, "supportedQueryFormats": "JSON, geoJSON, PBF", + "advancedQueryCapabilities": {"supportsPagination": true}}"#; + let page = answer(&[transform(false, 1.0, 0.0, 0.0), feature(&[geometry(&[], &[2_600_000, 1_200_000])])]); + let mut step = begin_with_pbf(query, 100); + let (ds, report) = loop { + match step { + Step::Fetch(pages) => { + let a = if pages.next_url().contains("/query") { page.clone() } else { layer.to_vec() }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, _) => break (*ds, report), + other => panic!("{other:?}"), + } + }; + let lv95 = crate::raster::Crs::from_epsg(2056).unwrap(); + assert_eq!((ds.coord_crs(), ds.crs), (lv95, Some(lv95))); + let Some(crate::Geometry::Point(c)) = ds.features.iter().next().unwrap().geometry.clone() else { panic!() }; + assert_eq!((c.x, c.y), (2_600_000.0, 1_200_000.0)); + assert!(report.messages.iter().any(|m| m.contains("read in EPSG:2056, the system asked for")), "{:?}", report.messages); + assert!(!report.messages.iter().any(|m| m.contains("as longitude/latitude")), "{:?}", report.messages); + // Pages of which some name a system and others none: the join stops at the first that + // differs, either way round, so no page's positions are taken for another system's. + use crate::esripbf::tests::encode::{field, message, number, uint}; + let paged = br#"{"objectIdField": "OBJECTID", "maxRecordCount": 1, "supportedQueryFormats": "JSON, geoJSON, PBF", + "advancedQueryCapabilities": {"supportsPagination": true}}"#; + let one = |id: u64, named: bool, more: bool| { + let mut parts = vec![number(7, 0)]; + if named { + parts.push(message(8, &number(1, 21781))); + } + parts.extend([transform(false, 1.0, 0.0, 0.0), field("OBJECTID", 6)]); + if more { + parts.push(number(9, 1)); + } + parts.push(feature(&[uint(id), geometry(&[], &[600_000, 200_000])])); + answer(&parts) + }; + for first_named in [false, true] { + let mut step = begin_with_pbf(query, 100); + let (ds, note) = loop { + match step { + Step::Fetch(pages) => { + let url = pages.next_url().to_string(); + let a = if !url.contains("/query") { + paged.to_vec() + } else if url.contains("resultOffset=1") { + one(2, !first_named, false) + } else { + one(1, first_named, true) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, _, note) => break (*ds, note), + other => panic!("{other:?}"), + } + }; + assert_eq!(ds.features.len(), 1, "first named: {first_named}"); + assert!(note.as_deref().is_some_and(|n| n.contains("another coordinate system")), "{note:?}"); + let expected = if first_named { crate::raster::Crs::from_epsg(21781).unwrap() } else { lv95 }; + assert_eq!(ds.coord_crs(), expected, "first named: {first_named}"); + } + // A first page whose feature has no geometry, naming a system: the next, with positions + // and naming none, isn't read in it (it is held in the system asked for, as a page naming + // none is). + let empty_named = || { + answer(&[ + number(7, 0), + message(8, &number(1, 21781)), + transform(false, 1.0, 0.0, 0.0), + field("OBJECTID", 6), + number(9, 1), + feature(&[uint(1)]), + ]) + }; + let mut step = begin_with_pbf(query, 100); + let ds = loop { + match step { + Step::Fetch(pages) => { + let url = pages.next_url().to_string(); + let a = if !url.contains("/query") { + paged.to_vec() + } else if !url.contains("resultOffset=1") { + empty_named() + } else { + one(2, false, false) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, _, _) => break *ds, + other => panic!("{other:?}"), + } + }; + assert_eq!((ds.features.len(), ds.coord_crs()), (2, lv95)); + // Two pages with positions: one naming WGS 84, one LV03; and two naming none, one in + // degrees, one not. Each pair stops after its first page, as read alone. + let page_at = |id: u64, code: Option, x: i64, y: i64, more: bool| { + let mut parts = vec![number(7, 0)]; + if let Some(code) = code { + parts.push(message(8, &number(1, code))); + } + parts.extend([transform(false, 0.01, 0.0, 0.0), field("OBJECTID", 6)]); + if more { + parts.push(number(9, 1)); + } + parts.push(feature(&[uint(id), geometry(&[], &[x, y])])); + answer(&parts) + }; + let lonlat = crate::raster::Crs::LonLat; + for (first, second, expected) in [ + ((Some(4326), 744, 4695), (Some(21781), 60_000_000, 20_000_000), lonlat), + ((None, 744, 4695), (None, 260_000_000, 120_000_000), lonlat), + ((None, 260_000_000, 120_000_000), (None, 744, 4695), lv95), + ] { + let mut step = begin_with_pbf(query, 100); + let (ds, note) = loop { + match step { + Step::Fetch(pages) => { + let url = pages.next_url().to_string(); + let a = if !url.contains("/query") { + paged.to_vec() + } else if url.contains("resultOffset=1") { + page_at(2, second.0, second.1, second.2, false) + } else { + page_at(1, first.0, first.1, first.2, true) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, _, note) => break (*ds, note), + other => panic!("{other:?}"), + } + }; + assert_eq!((ds.features.len(), ds.coord_crs()), (1, expected), "{first:?} {second:?}"); + assert!(note.as_deref().is_some_and(|n| n.contains("another coordinate system")), "{note:?}"); + } + // Pages read as each would be alone: two in degrees in different axis orders, asked in + // LV95, don't join; and, asked in WGS 84, a page naming WGS 84 and one naming none join, + // as on main. + let read_two = |q: &str, first: (Option, i64, i64), second: (Option, i64, i64)| { + let mut step = begin_with_pbf(q, 100); + loop { + match step { + Step::Fetch(pages) => { + let url = pages.next_url().to_string(); + let a = if !url.contains("/query") { + paged.to_vec() + } else if url.contains("resultOffset=1") { + page_at(2, second.0, second.1, second.2, false) + } else { + page_at(1, first.0, first.1, first.2, true) + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, _, note) => break (*ds, note), + other => panic!("{other:?}"), + } + } + }; + // In degrees in different axis orders: stopped at the second, as pages aren't turned + // round, the first kept as it came. + let (ds, note) = read_two(query, (None, 12_000, 4_500), (None, 4_500, 12_000)); + assert_eq!((ds.features.len(), ds.coord_crs()), (1, lonlat), "{note:?}"); + assert!(note.as_deref().is_some_and(|n| n.contains("another coordinate system")), "{note:?}"); + let Some(crate::Geometry::Point(c)) = ds.features.iter().next().unwrap().geometry.clone() else { panic!() }; + assert_eq!((c.x, c.y), (120.0, 45.0)); + let wgs84 = query.replace("outSR=2056", "outSR=4326"); + let (ds, note) = read_two(&wgs84, (Some(4326), 744, 4695), (None, 750, 4700)); + assert_eq!((ds.features.len(), ds.coord_crs()), (2, lonlat), "{note:?}"); + // A page naming a code RustGIS can't use, asked in LV95: held in it, and said so. + let mut step = begin_with_pbf(query, 100); + let (ds, report) = loop { + match step { + Step::Fetch(pages) => { + let a = if pages.next_url().contains("/query") { + page_at(1, Some(999_999), 260_000_000, 120_000_000, false) + } else { + layer.to_vec() + }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, _) => break (*ds, report), + other => panic!("{other:?}"), + } + }; + assert_eq!(ds.coord_crs(), lv95); + assert!( + report + .messages + .iter() + .any(|m| m == "coordinate system 999999 can't be used; coordinates are read in EPSG:2056, the system asked for"), + "{:?}", + report.messages + ); + // Likewise one whose WKT can't be read. + let bad_wkt = answer(&[ + number(7, 0), + message(8, &message(5, b"PROJCS[\"broken\"")), + transform(false, 0.01, 0.0, 0.0), + field("OBJECTID", 6), + feature(&[uint(1), geometry(&[], &[260_000_000, 120_000_000])]), + ]); + let mut step = begin_with_pbf(query, 100); + let (ds, report) = loop { + match step { + Step::Fetch(pages) => { + let a = if pages.next_url().contains("/query") { bad_wkt.clone() } else { layer.to_vec() }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, _) => break (*ds, report), + other => panic!("{other:?}"), + } + }; + assert_eq!(ds.coord_crs(), lv95, "{:?}", report.messages); + assert!( + report.messages.iter().any(|m| m.ends_with("; coordinates are read in EPSG:2056, the system asked for")), + "{:?}", + report.messages + ); + // Positions in degrees all the same (a server that didn't convert): read so, as before. + let degrees = answer(&[transform(false, 0.01, 0.0, 0.0), feature(&[geometry(&[], &[744, 4695])])]); + let mut step = begin_with_pbf(query, 100); + let (ds, report) = loop { + match step { + Step::Fetch(pages) => { + let a = if pages.next_url().contains("/query") { degrees.clone() } else { layer.to_vec() }; + step = (*pages).land(Ok(a)); + } + Step::Decoded(ds, report, _) => break (*ds, report), + other => panic!("{other:?}"), + } + }; + assert_eq!((ds.coord_crs(), ds.crs), (crate::raster::Crs::LonLat, None)); + assert!(report.messages.iter().any(|m| m.contains("read as longitude/latitude")), "{:?}", report.messages); + } + /// An OGC API collection's extent is its longitude/latitude bounds only in CRS84 (named, or /// by default), with or without heights: a box in EPSG:4326's latitude-first order would turn /// longitude-first features round (#1053). @@ -5693,6 +6781,7 @@ mod tests { from: String::new(), phase: Phase::Offsets { size: 2, order: None, start: None, first: None, pbf: true, smaller: 0, fallback_size: 2 }, decoded: None, + placed_as: None, decoded_bytes: 0, decoded_budget: max_decoded_bytes(), pbf_failed: None, diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7b3259d8d2..63e0052a6e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6777,7 +6777,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // paging. let bytes = if service { let label = ps(p, "name").map(str::to_string).unwrap_or_else(|| crate::sources::address_in_message(&url)); - super::service::features_answer(s, &label, bytes, bounds) + super::service::features_answer(s, &label, &url, bytes, bounds) } else { bytes }; diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index f07598500c..964f72f25c 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -502,15 +502,21 @@ fn vet(mut svc: Service, caps: &str) -> Service { svc } -/// A service's GeoJSON answer made ready to read: latitude-first coordinates turned round, judged -/// against the layer's longitude/latitude `bounds` from its capabilities (see -/// [`fix_axes`](rustgis_data::ogc::fix_axes); none: left as they come), and a cut-off answer -/// pointed out. -pub fn features_answer(s: &mut Session, name: &str, bytes: Vec, bounds: Option<[f64; 4]>) -> Vec { +/// A service's GeoJSON answer to `url` made ready to read: in the projected system `url` asks it +/// in, named and east first, else latitude-first coordinates turned round, judged against the +/// layer's longitude/latitude `bounds` from its capabilities (see +/// [`place_answer`](rustgis_data::ogc::place_answer); none: left as they come), and a cut-off +/// answer and a system assumed pointed out. +pub fn features_answer(s: &mut Session, name: &str, url: &str, bytes: Vec, bounds: Option<[f64; 4]>) -> Vec { if let Some(note) = rustgis_data::ogc::partial_note(&bytes) { s.notify(format!("{name}: {note}"), false); } - rustgis_data::ogc::fix_axes(&bytes, bounds).unwrap_or(bytes) + let (bytes, assumed) = rustgis_data::ogc::place_answer(bytes, url, bounds); + // Once per kind with a count over the command (a service group reads many answers). + if let Some(assumed) = assumed { + s.notify_counted(None, assumed.template(), 1); + } + bytes } /// The layers an add's result `r` names (`layer`, `layers`) marked as read from the service @@ -609,13 +615,48 @@ pub(crate) fn add_service_layer( zoom: Option, file: impl FnOnce(&[u8]) -> Result, ) -> CmdResult { - let (downloaded, drawing) = download_layer_with(s, name, url, cache::MAX_DOWNLOAD, true, |url, max, timeout, ceiling| { - let ceiling = if public { ceiling.min(Reach::Public) } else { ceiling }; - cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) - })?; + let fetch = |s: &mut Session, url: &str| { + download_layer_with(s, name, url, cache::MAX_DOWNLOAD, true, |url, max, timeout, ceiling| { + let ceiling = if public { ceiling.min(Reach::Public) } else { ceiling }; + cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) + }) + }; + let first = fetch(s, url); + // A WFS type asked in its own system that the server refuses (an error, or an exception + // report where features were expected) is asked once more in EPSG:4326, as before RustGIS + // asked types in their own system, and that is said. + let refused = |r: &Result<(Downloaded, Drawing), String>| match r { + Err(_) => true, + // An OWS or WFS 1.0 exception report (not GML, which a server ignoring the JSON output + // format would send). + Ok((Downloaded::Bytes(b), _)) => { + let head = String::from_utf8_lossy(&b[..b.len().min(1024)]); + head.trim_start().starts_with('<') && head.contains("ExceptionReport") + } + Ok(_) => false, + }; + let fallback = rustgis_data::ogc::wfs_lonlat_fallback(url).filter(|_| refused(&first)); + let (url, (downloaded, drawing)) = match fallback { + Some(lonlat) => { + let why = match &first { + Err(e) => e.chars().take(200).collect::(), + Ok(_) => "it answered with an exception report".into(), + }; + // Failing too, both are said. + let second = fetch(s, &lonlat).map_err(|e| format!("{e} (asked in its own system first: {why})"))?; + let asked = rustgis_data::ogc::asked_system(url).map(|c| c.label()).unwrap_or_default(); + s.notify( + format!("{name}: the server refused its own system ({asked}: {why}); its features were asked for in EPSG:4326 instead"), + false, + ); + (lonlat, second) + } + None => (url.to_string(), first?), + }; + let url = url.as_str(); let r = match downloaded { Downloaded::Bytes(bytes) => { - let bytes = features_answer(s, name, bytes, bounds); + let bytes = features_answer(s, name, url, bytes, bounds); let file = file(&bytes)?; super::raster::add_named_bytes(s, p, file, bytes, zoom)? } diff --git a/crates/engine/src/cmd/service_group.rs b/crates/engine/src/cmd/service_group.rs index e7e62bb04f..ca611b98c3 100644 --- a/crates/engine/src/cmd/service_group.rs +++ b/crates/engine/src/cmd/service_group.rs @@ -239,7 +239,7 @@ fn read(s: &mut Session, p: &Value) -> Result<(Value, Vec<(ServiceChild, Dataset } // The collection's bounds, from the listing: none read leaves the axes as they come. let bounds = super::bounds_of(layer.get("bbox")).ok().flatten(); - let bytes = super::features_answer(s, name, bytes, bounds); + let bytes = super::features_answer(s, name, url, bytes, bounds); let text = std::str::from_utf8(&bytes).map_err(|e| format!("{name}: {e}"))?; let (mut dataset, report) = rustgis_data::io::read_geojson(text, name).map_err(|e| format!("{name}: {e}"))?; if dataset.features.is_empty() && !feature_collection(text) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 79cb03ee8c..587d2109b0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -11,6 +11,9 @@ mod held_databases; #[path = "tests/scene_losses.rs"] mod scene_losses; #[cfg(not(target_arch = "wasm32"))] +#[path = "tests/services_own.rs"] +mod services_own; +#[cfg(not(target_arch = "wasm32"))] #[path = "tests/sources_own.rs"] mod sources_own; diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs new file mode 100644 index 0000000000..a52bc38139 --- /dev/null +++ b/crates/engine/src/tests/services_own.rs @@ -0,0 +1,164 @@ +//! Services' features asked for in their own coordinate system (#2032 C2f-3b): a WFS type in its +//! default system and an ArcGIS layer in its service's, held in it as they come, with the +//! longitude/latitude request kept where the system isn't one RustGIS reads. + +use super::ogc_server::{Route, Server, arcgis_layer}; +use crate::{Project, Session}; +use rustgis_data::raster::Crs; +use serde_json::json; + +fn first_point(s: &Session, name: &str) -> (Crs, f64, f64) { + let l = s.map().layer_by_name(name).unwrap(); + let Some(rustgis_data::Geometry::Point(c)) = l.dataset.features.iter().next().unwrap().geometry.clone() else { panic!("not a point") }; + (l.dataset.coord_crs(), c.x, c.y) +} + +fn notices(s: &Session) -> Vec { + s.notices.iter().map(|n| n.text.clone()).collect() +} + +/// A WFS 1.1 type in LV95 is asked for in it and held in it, whether its answer names the system +/// or not, and turned round when written north first; a server answering in degrees anyway is +/// read so, and said; a type in a system RustGIS doesn't read is asked in CRS84 as before. +#[test] +fn a_wfs_type_is_asked_for_in_its_own_system() { + let point = |x: f64, y: f64, member: &str| { + format!( + r#"{{"type":"FeatureCollection",{member}"features":[{{"type":"Feature","properties":{{"n":1}},"geometry":{{"type":"Point","coordinates":[{x},{y}]}}}}]}}"# + ) + }; + let named = r#""crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::2056"}},"#; + let server = Server::new(vec![ + Route::new("/plain", &point(2_600_000.0, 1_200_000.0, "")), + Route::new("/turned", &point(1_200_000.0, 2_600_000.0, named)), + Route::new("/lonlat", &point(7.44, 46.95, "")), + ]); + let caps = |path: &str, system: &str| { + format!( + r#" +townsTowns{system}urn:ogc:def:crs:OGC:1.3:CRS84 +7.0 46.58.0 47.2"#, + server.base + ) + }; + let lv95 = Crs::from_epsg(2056).unwrap(); + let mut s = Session::new(Project::default()); + for (path, name) in [("/plain", "Plain"), ("/turned", "Turned")] { + let text = caps(path, "urn:ogc:def:crs:EPSG::2056"); + s.run("service.add", &json!({"url": format!("{}{path}", server.base), "layer": "towns", "text": text, "name": name})).unwrap(); + assert_eq!(first_point(&s, name), (lv95, 2_600_000.0, 1_200_000.0), "{path}"); + } + assert!(notices(&s).is_empty(), "{:?}", notices(&s)); + // A server that answers in longitude/latitude whatever it is asked: read as such, and said. + let text = caps("/lonlat", "urn:ogc:def:crs:EPSG::2056"); + s.run("service.add", &json!({"url": format!("{}/lonlat", server.base), "layer": "towns", "text": text, "name": "Ignored"})).unwrap(); + assert_eq!(first_point(&s, "Ignored"), (Crs::LonLat, 7.44, 46.95)); + let said = notices(&s); + assert!( + said.len() == 1 && said[0].starts_with("1 service answer(s) named no coordinate system, and their positions are in degrees"), + "{said:?}" + ); + // A system RustGIS doesn't read: in CRS84, as before. + let text = caps("/lonlat", "urn:ogc:def:crs:EPSG::999999"); + s.run("service.add", &json!({"url": format!("{}/lonlat", server.base), "layer": "towns", "text": text, "name": "Unread"})).unwrap(); + assert_eq!(first_point(&s, "Unread"), (Crs::LonLat, 7.44, 46.95)); + let srs: Vec = server + .requests() + .iter() + .filter(|r| r.query.iter().any(|(k, v)| k == "REQUEST" && v == "GetFeature") && !r.query.iter().any(|(k, _)| k == "RESULTTYPE")) + .filter_map(|r| r.query.iter().find(|(k, _)| k == "SRSNAME").map(|(_, v)| v.clone())) + .collect(); + assert_eq!(srs, ["EPSG:2056", "EPSG:2056", "EPSG:2056", "urn:ogc:def:crs:OGC:1.3:CRS84"]); +} + +/// A server that lists a type's own system but refuses it (an exception report where features +/// were expected) is asked once more in EPSG:4326, as before, and that is said. +#[test] +fn a_wfs_type_whose_system_is_refused_is_asked_in_degrees() { + let refusal = + r#""#; + let caps = |base: &str| { + format!( + r#" +townsTownsurn:ogc:def:crs:EPSG::2056 +7.0 46.58.0 47.2"# + ) + }; + let server = Server::new(vec![Route::new("/refuses", refusal)]); + let text = caps(&server.base); + // The address the type is asked at, and the one in degrees, answered with its features. + let listed = rustgis_data::ogc::parse(&format!("{}/refuses", server.base), text.as_bytes()).unwrap(); + let rustgis_data::ogc::Offer::Features { url } = &listed.layers[0].offer else { panic!("{:?}", listed.layers[0].offer) }; + let lonlat = rustgis_data::ogc::wfs_lonlat_fallback(url).unwrap(); + let target = lonlat.strip_prefix(&server.base).unwrap(); + server.set( + target, + r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[7.44,46.95]}}]}"#, + ); + let mut s = Session::new(Project::default()); + s.run("service.add", &json!({"url": format!("{}/refuses", server.base), "layer": "towns", "text": text, "name": "Towns"})).unwrap(); + assert_eq!(first_point(&s, "Towns"), (Crs::LonLat, 7.44, 46.95)); + let said = notices(&s); + assert!( + said.iter() + .any(|n| n.starts_with("Towns: the server refused its own system (EPSG:2056") && n.ends_with("asked for in EPSG:4326 instead")), + "{said:?}" + ); +} + +/// An ArcGIS layer of a service in LV95 is asked for in it (`outSR=2056`) and held in it, its +/// GeoJSON answer naming no system; a service in Web Mercator by 3857; one in longitude/latitude +/// as before. +#[test] +fn an_arcgis_layer_is_asked_for_in_its_services_system() { + let page = |x: f64, y: f64| { + format!( + r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","id":1,"properties":{{"OBJECTID":1}},"geometry":{{"type":"Point","coordinates":[{x},{y}]}}}}]}}"# + ) + }; + let server = Server::new(vec![ + Route::new("/arcgis/rest/services/LV/FeatureServer/0/query", &page(2_600_000.0, 1_200_000.0)), + Route::new("/arcgis/rest/services/LV/FeatureServer/0", &arcgis_layer(1000, false)), + Route::new("/arcgis/rest/services/WM/FeatureServer/0/query", &page(828_000.0, 5_934_000.0)), + Route::new("/arcgis/rest/services/WM/FeatureServer/0", &arcgis_layer(1000, false)), + Route::new("/arcgis/rest/services/LL/FeatureServer/0/query", &page(7.44, 46.95)), + Route::new("/arcgis/rest/services/LL/FeatureServer/0", &arcgis_layer(1000, false)), + ]); + // Its full extent, in its own system, around the town. + let service = |sr: &str, x: f64, y: f64, d: f64| { + format!( + r#"{{"currentVersion": 11.5, "maxRecordCount": 1000, "spatialReference": {sr}, "fullExtent": {{"xmin": {}, "ymin": {}, "xmax": {}, "ymax": {}, "spatialReference": {sr}}}, "layers": [{{"id": 0, "name": "Towns"}}]}}"#, + x - d, + y - d, + x + d, + y + d + ) + }; + let mut s = Session::new(Project::default()); + for (folder, sr, crs, x, y, d) in [ + ("LV", r#"{"wkid": 2056, "latestWkid": 2056}"#, Crs::from_epsg(2056).unwrap(), 2_600_000.0, 1_200_000.0, 50_000.0), + ("WM", r#"{"wkid": 102100, "latestWkid": 3857}"#, Crs::WebMercator, 828_000.0, 5_934_000.0, 50_000.0), + ("LL", r#"{"wkid": 4326}"#, Crs::LonLat, 7.44, 46.95, 0.5), + ] { + let url = format!("{}/arcgis/rest/services/{folder}/FeatureServer", server.base); + s.run("service.add", &json!({"url": url, "layer": "Towns", "text": service(sr, x, y, d), "name": folder})).unwrap(); + assert_eq!(first_point(&s, folder), (crs, x, y), "{folder}"); + } + let out: Vec = server + .requests() + .iter() + .filter(|r| r.path.ends_with("/query")) + .filter_map(|r| r.query.iter().find(|(k, _)| k == "outSR").map(|(_, v)| v.clone())) + .collect(); + assert_eq!(out, ["2056", "3857", "4326"]); + assert!(notices(&s).is_empty(), "{:?}", notices(&s)); + // A service without a full extent: its answer, naming no system, can't be checked against + // bounds. It is read in the system asked for, and that is said, once. + let bare = + r#"{"currentVersion": 11.5, "maxRecordCount": 1000, "spatialReference": {"wkid": 2056}, "layers": [{"id": 0, "name": "Towns"}]}"#; + let url = format!("{}/arcgis/rest/services/LV/FeatureServer", server.base); + s.run("service.add", &json!({"url": url, "layer": "Towns", "text": bare, "name": "Unbounded"})).unwrap(); + assert_eq!(first_point(&s, "Unbounded"), (Crs::from_epsg(2056).unwrap(), 2_600_000.0, 1_200_000.0)); + let said = notices(&s); + assert!(said.len() == 1 && said[0].contains("1 service answer(s) named no coordinate system"), "{said:?}"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 636b15d960..bd704cf0e8 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -31,7 +31,7 @@ export names its feature. | GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | -| ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons converted to longitude/latitude from the answer's coordinate system. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | +| ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons held in the answer's coordinate system when RustGIS reads it. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | | TopoJSON | `.topojson`, or `.json` | Add Data, drop the file, or upload | Shared arcs (quantized or not) are rebuilt into geometries. A `.topojson` adds a layer per object, up to 64; a topology named `.json` adds its first object and names the others in a notice. Use `.topojson` to add them all. | | CityJSON | `.city.json`, or `.json` | Add Data, drop the file, upload, or From URL… | CityJSON 1.1 and 2.0, read in 2D: a layer per City Object type and geometry family (a name two layers would share, such as two long types cut to their first 64 characters, or two that differ only in ASCII case, gets ` (2)`, ` (3)`… on the later ones: the first number no other layer's name uses). Surfaces and solids become footprints (LoD 0, else the `GroundSurface` surfaces, else the union of the faces of the highest LoD, each tried when the one before gives no area, else the outline of the points; lines and points come from their highest level of detail that draws; a level passed over because its X or Y isn't a finite number, or is too large, is named in a notice; a geometry of more than 200,000 faces is the outline of its points (of its ground's, for a footprint from the ground), with a notice, unless its footprint is its ground and all of its ground faces are within the cap), with `z_min`, `z_max` and `height` fields, from every level of detail and the children's heights included, so Style › Extrusion stands them up, and `base_height`, how far an object's lowest point is above the lowest point of the topmost object it is part of (0 for a building; for a balcony part, its lowest point's height above the building's; a building's lowest point is its basement's when it has one, and a group's members aren't parts of the group). Also `id`, `type`, `parent`, `lod` and the object's attributes; one named as one of these fields, or as another attribute of its layer but for case, takes a number (`height_1`), the same in every row, and a notice lists them. A `.city.json`, or a model from an address, adds every layer, up to 64; a file named `.json` adds its first layer with something to draw and names the others in a notice. A file that names no coordinate system and isn't longitude/latitude is refused: for now the way to add it is the `"crs"` parameter of `layer.addData`, from the command line, Python or the AI Assistant. Geometry instances are their template placed by their matrix at their reference point, with its heights, and rings the matrix flattens are left out and said for each instance; one whose template is missing, can't be read or draws nothing, or whose matrix is missing or isn't 16 numbers ending in `0 0 0 1`, is drawn as a point at its reference point, with no height, as are those past what placing may cost (as many points, all instances together, as the file could write out), and a notice says how many. `TINRelief` objects aren't drawn; a notice says so, as it does for addresses. Appearance (materials and textures) isn't read, and a notice says how much is left out. Heights are kept in the file's unit: in a coordinate system that doesn't measure in metres, a notice says so, as Style › Extrusion reads metres. A compound URN (`urn:ogc:def:crs,crs:EPSG::25832,crs:EPSG::5783`) is read by its horizontal part, and its vertical part gives the heights' unit, said as in CityGML when it isn't a height in metres. In a zip, a `"crs"` applies only to a model that names no coordinate system RustGIS knows. In the browser a footprint that needs a union is the outline of the object's points; a notice says so. An extrusion raises each part when it is given a base, such as `base_height` as its base field, or a constant (see [Layer effects](cartography.md#layer-effects)); with no base, parts stand on the ground. Added, a model comes in standing: the polygon layers of its volumes (`Building`, `BuildingPart`, `BuildingInstallation`, `BuildingConstructiveElement`, `Bridge`, `BridgePart`, `BridgeInstallation`, `BridgeConstructiveElement`, `TunnelInstallation`, `CityFurniture`, `SolitaryVegetationObject`, `GenericCityObject`, `OtherConstruction`) are extruded by `height` on `base_height` when one of their objects has a height, with 0 where an object has none (`+GenericCityObject`, CityJSON 1.1's, counts as `GenericCityObject`). A layer whose objects all stand in their parts (a building's outline with its volume in its `BuildingPart`s, a bridge's in its `BridgePart`s) stays flat, so the tallest part doesn't cover the others. Surfaces on or below the ground (roads, railways, squares, waterways, water, land use, plant cover, tunnels and their parts and hollow spaces), what lies inside another object (rooms, storeys, units, and building, bridge and tunnel furniture), any other extension's type, and line and point layers stay flat. A saved project opens with the extrusion it was saved with. | | CityGML | `.gml`, or `.xml` | Add Data, drop the file, upload, or From URL… | CityGML 1.0, 2.0 and 3.0, read in 2D as CityJSON is (the same layers, fields, footprints, heights and notices). 3.0 is read by the names it keeps and by its own where they change (thematic surfaces in `boundary`, openings in `fillingSurface`, generic attributes named by `gen:name`, a group's member inside its `Role`), read only in 3.0's namespaces, so an extension of a 1.0 or 2.0 model that uses one of those names keeps its own meaning; its spaces (a `BuildingRoom`, a `Storey`) are objects like any other. The objects are the features of the model's members and those nested in them with a `gml:id` or a geometry (a `BuildingPart`, a `Room`), each with its parent's id in `parent`; thematic surfaces and their openings are their object's faces, and a `GroundSurface` its ground. A geometry's level of detail is the one its property names (`lod2Solid` is 2); one in another property (a group's) has none. Converted from the `srsName`, by its horizontal part for a compound system (the URN and URL forms of geographic systems are latitude first, CRS84 longitude first; heights are kept as they come, and a vertical part that isn't a height in metres, such as one in feet, a depth, or one RustGIS doesn't know, is said; when a vertical part is named, its unit is the heights', not the horizontal system's), or from the coordinate system given (`crs`), which takes the place of the one the file names; a file naming different systems (on its geometries or envelopes) is refused unless a system is given, which reads them all and says how many named another, and one system with its axes in different orders is refused either way. Picked by name (`layer`), a layer keeps the notices the file as a whole gives; zipped, a model keeps the system it names, and the one given applies only when it names none RustGIS knows. Generic attributes are typed by their element, `measuredHeight`, the storey counts, years and any property with a unit in metres are numbers (a measure in another unit than the metre is text with its unit), other simple properties are text (the code list a code names, `codeSpace`, a value's other attributes, such as its language, `xml:lang`, and a generic attribute set's members with no name and its own code list aren't kept, and notices say how many, generic attributes included), a property given twice is a list and a structured one its JSON. Each member of the model is parsed on its own, with the objects nested in it (each object of a `featureMembers` on its own), so no tree of the whole model is built; the file's text and the rows read stay in memory. On the desktop, Add Data reads a file added by its path in the background, with its progress counted a member at a time and Cancel (in a zip, from text, or listed, it is read as the command runs). A member nested too deep or too large to parse is left out whole, with a notice. A geometry given by a link (`xlink:href`) to one written in the file, in the same member or another, as a solid's faces are to its walls' and roof's polygons, is read where the link stands, once its object's own geometries are read, a ground surface's links first: one its object holds already at that level of detail isn't read again (a ground face stays its ground, and a face read as a wall that a ground surface links to is read as the ground too), through links each is read at most once per object and level, so links in a cycle end, and what a member's links read is bounded by the member's size, and what links copy and read from other members by four times the file's, past which the links left are said; a solid whose exterior is a link that is followed and reads something keeps its cavities; a link to a `gml:id` that several elements have reads the one in its member, else the first in the file, and a notice says how many geometries repeat one; a geometry whose coordinates can't be read is said once, whichever object or link reads it first. An implicit geometry is its prototype (`relativeGMLGeometry`, `relativeGeometry` in 3.0, written in place or given by a link, in its member or another) placed by its matrix at its reference point, in the file's axis order (latitude first where the system is), with its heights: the prototype is read once and placed for each instance, and rings its matrix flattens are left out and said for each instance; one whose prototype is in another file (`libraryObject`), can't be read or holds nothing to place, or whose matrix isn't 16 numbers ending in `0 0 0 1`, is drawn as a point at its reference point, with no height, as are those past what placing may cost (as many points, all instances together, as the file could write out), and a notice says how many. A part, a group's member or a group's parent given by a link (`consistsOfBuildingPart`, `buildingPart`, `bridgePart` and `tunnelPart` in 3.0, `groupMember`, a `CityObjectGroup`'s `parent`) makes the object it names a child of the other, as if written in it, so its heights go to it, wherever it is in the file (an object written in a group's `parent` is the group's parent too, not its child); the link stays an attribute too, a link naming no other object of the file is said, and a member's role in its group isn't kept, and is said. Not read, and said in a notice: geometries given by a link to another file, nothing or a member that can't be parsed, to what isn't a geometry, or to one where nothing is drawn (an appearance's, a terrain intersection's), a prototype's geometry linked from outside its implicit geometry, and links inside a prototype; thematic surfaces and openings given only by a link; rings given by one (a hole so given is left out, its face kept), lines and rings with a point or curve given by one, and an oriented curve whose base curve is, terrain intersection curves, appearances, addresses, and the properties of thematic surfaces and openings (a name, generic attributes: their faces are kept as their object's); arcs and splines are read as straight lines through their points (a curve given backwards, `orientation="-"`, in its direction, and one held in a ring counted like a standalone one); an arc given by its centre (`ArcByCenterPoint`, `CircleByCenterPoint`) isn't read as the curve's points, its centre is never a vertex, and an arc that is its curve's only segment leaves the geometry with nothing to read; a `gml:Point` written with more than one position keeps the first one, and is said; a solid with no exterior shell is left out, as is a solid whose exterior has nothing read (a link that isn't followed, an empty shell, or a shell whose surfaces are all links that lead nowhere), its cavities with it (read alone they would be drawn as a footprint), and one whose cavity can't be read is left out whole; a file cut short, even inside a tag, keeps completed members and completed direct children of the truncated member; a part nested inside an unfinished object is lost with that object; `TINRelief` objects aren't drawn; 3.0's relations between objects (`CityObjectRelation`) and the model's versions (`versionMember`, `versionTransitionMember`) aren't read. Added, a model comes in standing as a CityJSON one does, by the same types and by CityGML's own names for them: 2.0's `BridgeConstructionElement` and 3.0's `GenericOccupiedSpace` stand; 2.0's `Room`, `IntBuildingInstallation` and the other interior installations, and 3.0's `Storey`, `HollowSpace`, `GenericUnoccupiedSpace`, `GenericLogicalSpace` and `GenericThematicSurface` stay flat. | @@ -393,9 +393,28 @@ format and bounds; `service.coverage` gives the GetCoverage address alone). Movi ask for it again: add it again for another area. The server reprojects it to EPSG:4326 (WCS 2.0 through its CRS extension); one that can't answers with an error, which is shown. -A feature type is asked for in CRS84 when it offers it, else in `EPSG:4326`. Every server tried -answered those requests longitude first, but a server may answer latitude first (deegree does -when asked in the URN form, `urn:ogc:def:crs:EPSG::4326`). The `crs` a GeoJSON answer names +A feature type whose own system (its default one) is a projected system RustGIS reads is asked +for in it, as `EPSG:`, and the layer is held in it, without a conversion by the server or +RustGIS. A server that refuses it (an error, or an exception report where features were +expected) is asked once more in `EPSG:4326`, as before, and a notice says so. Likewise an +ArcGIS layer is asked for in its service's coordinate system (`outSR`, by its +EPSG code: 3857 for 102100). Positions within degrees' range are read as longitude/latitude (a +server that didn't convert), whatever the answer names. Others are checked against the layer's +longitude/latitude bounds (from the capabilities, or an ArcGIS service's full extent), +converted to that system: positions written north first are turned round, and an answer that +names no system is read in the one asked for. A notice says when a system is assumed: an answer +naming no system whose positions can't be checked against the bounds (there are no bounds, or +the positions fit neither way), one naming a system RustGIS doesn't read, one naming +longitude/latitude or the asked system against what its positions show, and one naming none +whose positions are in degrees (a server that didn't convert). A protocol-buffer page naming no +system is held in the system asked for (in longitude/latitude when its positions are in +degrees), and that is said too. Otherwise (a geographic +system, or one RustGIS can't ask a server for: a code it doesn't read, an `ESRI:` code, a +service's WKT without a code; the listing says which) the request is the one below. + +A feature type is otherwise asked for in CRS84 when it offers it, else in `EPSG:4326`. Every +server tried answered those requests longitude first, but a server may answer latitude first +(deegree does when asked in the URN form, `urn:ogc:def:crs:EPSG::4326`). The `crs` a GeoJSON answer names doesn't tell the order (GeoServer names its longitude-first answers `urn:ogc:def:crs:EPSG::4326`), so the features' positions are turned round only when they miss the layer's longitude/latitude bounds from the capabilities and fit them turned (give or take a tenth of the bounds' size, or @@ -411,7 +430,7 @@ the features that cross the area, whole, not clipped. `service.add` then zooms t (not to the whole layer's bounds), and leaves the view as it is for `"view"`. The box is asked in each service's own terms: -- **WFS 1.1 and 2.0:** `BBOX`, in CRS84 when the feature type offers it, else in +- **WFS 1.1 and 2.0:** `BBOX`, in CRS84 when the features are asked for in it, else in `urn:ogc:def:crs:EPSG::4326`, latitude first as that name fixes. - **OGC API Features:** `bbox`, longitude first; the `next` pages keep it. - **ArcGIS:** an envelope in EPSG:4326 the features intersect; the pages past the record limit From 8a08b7c060d9a730b5bbfa473570bb837f16bf07 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 08:22:01 +0100 Subject: [PATCH 02/11] Main's Notes: the message rewrite rebuilds the list --- crates/data/src/ogc.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 57a069246b..1014374697 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -4335,10 +4335,11 @@ impl Pages { } // One it names that RustGIS can't use (a code, a WKT): read as asked too (as a // GeoJSON answer's is), and its message says so. - for m in &mut report.messages { - if let Some(said) = m.strip_suffix("; coordinates are read as longitude/latitude") { - *m = format!("{said}; coordinates are read in {asked}, the system asked for"); + for mut note in std::mem::replace(&mut report.messages, crate::loss::Notes::new()) { + if let Some(said) = note.text.strip_suffix("; coordinates are read as longitude/latitude") { + note.text = format!("{said}; coordinates are read in {asked}, the system asked for"); } + report.messages.push(note); } } report.messages.extend(losses.messages()); From 6e2804ef84d40a73308fdf7603368e914b9ded72 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 09:24:16 +0100 Subject: [PATCH 03/11] WCS coverages asked in their own coordinate system (#2032 C2f-3c) A coverage whose own system is a projected one RustGIS reads (WCS 2.0's envelope with axis labels, WCS 1.0's native CRS with a spatial-domain envelope in it) is asked for in it: the area's box there, within its envelope, with no CRS conversion asked of the server, so the map resamples it once. Axis order: E/N labels, else EPSG's order of the system's axes, else x/y names. Its longitude/latitude bounds come from the envelope (reaching a pole within it), so "bbox": "full" works for it. Other coverages keep the EPSG:4326 request. --- crates/data/src/ogc.rs | 295 +++++++++++++++++++++++- crates/data/src/ogc_document_tests.rs | 8 +- crates/engine/src/tests/services_own.rs | 48 +++- docs/user-guide/data-formats.md | 14 +- 4 files changed, 352 insertions(+), 13 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 1014374697..dad634b4ae 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -1947,6 +1947,21 @@ pub struct CoverageInfo { pub format: String, pub axes: Option<(String, String)>, pub bbox: Option<[f64; 4]>, + /// The coverage's own system, when it is a projected one RustGIS reads: it is asked for in + /// it, and resampled once, by the map (#2032). + pub native: Option, +} + +/// A coverage's own projected system, as its description gives it. +#[derive(Clone, Debug, PartialEq)] +pub struct CoverageSystem { + pub crs: crate::raster::Crs, + /// The system as the description names it (WCS 1.0's `CRS`). + pub name: String, + /// The coverage's envelope in it, east first: `[min x, min y, max x, max y]`. + pub envelope: [f64; 4], + /// WCS 2.0's axis labels, the east-west one first. + pub axes: Option<(String, String)>, } fn wcs(url: &str, root: &Node) -> Service { @@ -2121,10 +2136,27 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result None } })(); + let own = projected_system(&srs).and_then(|(_, crs)| { + let (lo, hi) = (corner("lowerCorner")?, corner("upperCorner")?); + let (lo0, lo1, hi0, hi1) = (*lo.first()?, *lo.get(1)?, *hi.first()?, *hi.get(1)?); + let (a, b) = (labels.first()?.to_string(), labels.get(1)?.to_string()); + let ok = |s: &str| !s.is_empty() && s.len() <= 32 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'); + if !ok(&a) || !ok(&b) { + return None; + } + // Labels naming east and north (`E N`) say the order; `x` and `y` don't (LV03 calls its + // east axis Y, Gauss-Krüger its north axis X), so then EPSG's order of the system's + // axes decides, and the names only when that isn't known. + let north_first = + north_first_labels(&a, &b, false).or_else(|| epsg_north_first(crs)).or_else(|| north_first_labels(&a, &b, true))?; + let (envelope, axes) = if north_first { ([lo1, lo0, hi1, hi0], (b, a)) } else { ([lo0, lo1, hi0, hi1], (a, b)) }; + Some(CoverageSystem { crs, name: srs.clone(), envelope: ordered(envelope)?, axes: Some(axes) }) + }); + let bbox = bbox.or_else(|| own.as_ref().and_then(|o| lonlat_of(o.envelope, o.crs))); let native = root.descendants().find(|n| n.is_element() && local(n) == "nativeFormat").map(|n| text_of(&n)); let offered: Vec<&str> = native.iter().map(String::as_str).filter(|f| !f.is_empty()).chain(c.formats.iter().map(String::as_str)).collect(); - return Ok(CoverageInfo { format: tiff_format(offered), axes, bbox }); + return Ok(CoverageInfo { format: tiff_format(offered), axes, bbox, native: own }); } // WCS 1.0: the formats it answers in, and its longitude/latitude envelope. let formats: Vec = root @@ -2142,11 +2174,110 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result children(&e, "pos").flat_map(|p| text_of(&p).split_whitespace().filter_map(|t| t.parse().ok()).collect::>()).collect(); lonlat_box(*pos.first()?, *pos.get(1)?, *pos.get(2)?, *pos.get(3)?) }); - Ok(CoverageInfo { format: tiff_format(formats.iter().map(String::as_str)), axes: None, bbox }) + // Its own system: its `nativeCRSs` (else its spatial domain's), when the spatial domain's + // envelope is in it, written east first as WCS 1.0 has it. + let own = (|| { + let domain = root.descendants().find(|n| n.is_element() && local(n) == "spatialDomain")?; + let envelopes: Vec = domain.descendants().filter(|n| n.is_element() && local(n) == "Envelope").take(16).collect(); + let srs_of = |e: &Node| e.attribute("srsName").unwrap_or("").trim().to_string(); + let native = root + .descendants() + .find(|n| n.is_element() && local(n) == "nativeCRSs") + .map(|n| text_of(&n)) + .and_then(|t| t.split_whitespace().next().map(str::to_string)); + // The native system's envelope (MapServer writes one in EPSG:4326 first); without a + // native system named, the first envelope in a projected one. + let (env, (n, crs)) = match native { + Some(name) => { + let (n, crs) = projected_system(&name)?; + (envelopes.into_iter().find(|e| projected_system(&srs_of(e)).map(|(_, c)| c) == Some(crs))?, (n, crs)) + } + None => envelopes.into_iter().find_map(|e| projected_system(&srs_of(&e)).map(|found| (e, found)))?, + }; + let name = format!("EPSG:{n}"); + let pos: Vec = children(&env, "pos") + .flat_map(|p| text_of(&p).split_whitespace().filter_map(|t| t.parse().ok()).collect::>()) + .collect(); + let envelope = ordered([*pos.first()?, *pos.get(1)?, *pos.get(2)?, *pos.get(3)?])?; + Some(CoverageSystem { crs, name, envelope, axes: None }) + })(); + let bbox = bbox.or_else(|| own.as_ref().and_then(|o| lonlat_of(o.envelope, o.crs))); + Ok(CoverageInfo { format: tiff_format(formats.iter().map(String::as_str)), axes: None, bbox, native: own }) +} + +/// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one +/// first, or neither; with `xy`, `x` and `y` count as east and north too. +fn north_first_labels(a: &str, b: &str, xy: bool) -> Option { + let is_north = |s: &str| { + let s = s.to_ascii_lowercase(); + matches!(s.as_str(), "n" | "north" | "northing") || (xy && s == "y") + }; + let is_east = |s: &str| { + let s = s.to_ascii_lowercase(); + matches!(s.as_str(), "e" | "east" | "easting") || (xy && s == "x") + }; + if is_east(a) || is_north(b) { + Some(false) + } else if is_north(a) || is_east(b) { + Some(true) + } else { + None + } +} + +/// A box `[x0, y0, x1, y1]` of finite corners, lower first; `None` for one that isn't. +fn ordered(b: [f64; 4]) -> Option<[f64; 4]> { + let [x0, y0, x1, y1] = b; + (b.iter().all(|v| v.is_finite()) && x0 < x1 && y0 < y1).then_some(b) } -/// The pixel size of a coverage asked for over a longitude/latitude `area`: its longer side -/// [`COVERAGE_MAX_PIXELS`], square degrees. +/// A box in `crs` as a longitude/latitude one: its edges' places, sixteen along each; `None` +/// when one has no place in longitude/latitude. +fn lonlat_of(b: [f64; 4], crs: crate::raster::Crs) -> Option<[f64; 4]> { + let t = crs.transformer().ok()?; + let [x0, y0, x1, y1] = b; + let mut out = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + const STEPS: usize = 16; + for i in 0..=STEPS { + let f = i as f64 / STEPS as f64; + let (x, y) = (x0 + (x1 - x0) * f, y0 + (y1 - y0) * f); + for (px, py) in [(x, y0), (x, y1), (x0, y), (x1, y)] { + let c = t.to_lonlat(rustgis_geom::Coord::new(px, py)).filter(|c| c.x.is_finite() && c.y.is_finite())?; + out = [out[0].min(c.x), out[1].min(c.y), out[2].max(c.x), out[3].max(c.y)]; + } + } + // A pole within it (a polar coverage): its edges miss it, so the box reaches it, at every + // longitude. + for lat in [90.0, -90.0] { + if t.from_lonlat(rustgis_geom::Coord::new(0.0, lat)) + .is_some_and(|p| p.x.is_finite() && p.y.is_finite() && p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1) + { + out = [-180.0, out[1].min(lat), 180.0, out[3].max(lat)]; + } + } + lonlat_box(out[0], out[1], out[2], out[3]) +} + +/// A longitude/latitude `area` as a box in `crs` (its edges' places, sixteen along each), within +/// `envelope`; `None` when an edge has no place there or they don't meet. +fn area_in(area: [f64; 4], crs: crate::raster::Crs, envelope: [f64; 4]) -> Option<[f64; 4]> { + let t = crs.transformer().ok()?; + let [w, s, e, n] = area; + let mut out = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + const STEPS: usize = 16; + for i in 0..=STEPS { + let f = i as f64 / STEPS as f64; + let (x, y) = (w + (e - w) * f, s + (n - s) * f); + for (lon, lat) in [(x, s), (x, n), (w, y), (e, y)] { + let c = t.from_lonlat(rustgis_geom::Coord::new(lon, lat)).filter(|c| c.x.is_finite() && c.y.is_finite())?; + out = [out[0].min(c.x), out[1].min(c.y), out[2].max(c.x), out[3].max(c.y)]; + } + } + ordered([out[0].max(envelope[0]), out[1].max(envelope[1]), out[2].min(envelope[2]), out[3].min(envelope[3])]) +} + +/// The pixel size of a coverage asked for over an `area` (in longitude/latitude, or in the +/// coverage's own system): its longer side [`COVERAGE_MAX_PIXELS`], square pixels in its units. pub fn coverage_size(area: [f64; 4]) -> (u32, u32) { let (dx, dy) = ((area[2] - area[0]).abs().max(1e-9), (area[3] - area[1]).abs().max(1e-9)); let m = f64::from(COVERAGE_MAX_PIXELS); @@ -2154,10 +2285,40 @@ pub fn coverage_size(area: [f64; 4]) -> (u32, u32) { (w.clamp(1.0, m) as u32, h.clamp(1.0, m) as u32) } -/// The GetCoverage request of a coverage over a longitude/latitude `area`, as a GeoTIFF in -/// EPSG:4326 (the server reprojects; WCS 2.0 through its CRS extension), scaled to fit -/// [`COVERAGE_MAX_PIXELS`]. +/// The GetCoverage request of a coverage over a longitude/latitude `area`, as a GeoTIFF in the +/// coverage's own system when it is a projected one RustGIS reads ([`CoverageInfo::native`]): +/// the area's box there, within the coverage's envelope, and no conversion by the server (#2032). +/// Otherwise, or when the area has no place there, in EPSG:4326 (the server reprojects; WCS 2.0 +/// through its CRS extension). Scaled to fit [`COVERAGE_MAX_PIXELS`]. pub fn get_coverage_url(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> String { + // An area holding the whole coverage asks for its envelope, not for that converted there and + // back. + let whole = info.bbox.is_some_and(|b| area[0] <= b[0] && area[1] <= b[1] && area[2] >= b[2] && area[3] >= b[3]); + if let Some(own) = &info.native + && let Some(b) = if whole { Some(own.envelope) } else { area_in(area, own.crs, own.envelope) } + { + let [x0, y0, x1, y1] = b; + let (pw, ph) = coverage_size(b); + let q = match (&own.axes, c.version.starts_with('2')) { + // Without a CRS asked for, WCS 2.0 subsets and answers in the coverage's own. + (Some((e, n)), true) => Some(format!( + "SERVICE=WCS&VERSION={}&REQUEST=GetCoverage&COVERAGEID={}&FORMAT={}&SUBSET={e}({x0},{x1})&SUBSET={n}({y0},{y1})&SCALESIZE={e}({pw}),{n}({ph})", + c.version, + encode(&c.id), + encode(&info.format) + )), + (_, false) => Some(format!( + "SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE={}&CRS={}&BBOX={x0},{y0},{x1},{y1}&WIDTH={pw}&HEIGHT={ph}&FORMAT={}", + encode(&c.id), + encode(&own.name), + encode(&info.format) + )), + (None, true) => None, + }; + if let Some(q) = q { + return with_query(&c.endpoint, &q); + } + } let [w, s, e, n] = area; let (pw, ph) = coverage_size(area); let q = if c.version.starts_with('2') { @@ -8494,6 +8655,126 @@ mod tests { assert!(parse("x", &[0xff]).is_err()); } + /// A coverage in a projected system RustGIS reads is asked for in it (#2032): WCS 2.0 by its + /// axis labels in either order (or EPSG's order without names), with no CRS asked for, and + /// WCS 1.0 by its native CRS; the area's box there stays within its envelope. A geographic + /// coverage, one RustGIS doesn't read, or one without axis labels is asked in EPSG:4326 as before. + #[test] + fn wcs_coverages_are_asked_for_in_their_own_system() { + let c2 = Coverage { + endpoint: "https://x.org/wcs".into(), + version: "2.0.1".into(), + id: "dem".into(), + formats: std::sync::Arc::from(vec![]), + }; + let desc = |srs: &str, labels: &str, lo: &str, hi: &str| { + format!( + r#"{lo}{hi}image/tiff"# + ) + }; + let lv95 = crate::raster::Crs::from_epsg(2056).unwrap(); + let srs = "http://www.opengis.net/def/crs/EPSG/0/2056"; + let east_first = parse_describe(&c2, desc(srs, "E N", "2590000 1190000", "2610000 1210000").as_bytes()).unwrap(); + let north_first = parse_describe(&c2, desc(srs, "N E", "1190000 2590000", "1210000 2610000").as_bytes()).unwrap(); + let own = east_first.native.clone().unwrap(); + assert_eq!( + (own.crs, own.envelope, own.axes.clone()), + (lv95, [2_590_000.0, 1_190_000.0, 2_610_000.0, 1_210_000.0], Some(("E".into(), "N".into()))) + ); + assert_eq!(north_first.native.as_ref().unwrap().envelope, own.envelope); + assert_eq!(north_first.native.as_ref().unwrap().axes, own.axes); + // Its longitude/latitude bounds come from its envelope. + let [w, s, e, n] = east_first.bbox.unwrap(); + assert!( + (7.30..7.32).contains(&w) && (7.56..7.58).contains(&e) && (46.85..46.87).contains(&s) && (47.03..47.05).contains(&n), + "{:?}", + east_first.bbox + ); + // The whole coverage: its envelope, no conversion asked for. + let whole = get_coverage_url(&c2, &east_first, east_first.bbox.unwrap()); + assert_eq!( + whole, + "https://x.org/wcs?SERVICE=WCS&VERSION=2.0.1&REQUEST=GetCoverage&COVERAGEID=dem&FORMAT=image%2Ftiff&SUBSET=E(2590000,2610000)&SUBSET=N(1190000,1210000)&SCALESIZE=E(2048),N(2048)" + ); + assert_eq!(get_coverage_url(&c2, &north_first, north_first.bbox.unwrap()), whole); + // Part of it: the area's box in LV95, within the envelope. + let part = get_coverage_url(&c2, &east_first, [7.40, 46.90, 7.50, 47.10]); + let subset = |get: &str, axis: &str| -> (f64, f64) { + let v = get.split(&format!("SUBSET={axis}(")).nth(1).unwrap().split(')').next().unwrap(); + let (a, b) = v.split_once(',').unwrap(); + (a.parse().unwrap(), b.parse().unwrap()) + }; + let ((x0, x1), (y0, y1)) = (subset(&part, "E"), subset(&part, "N")); + assert!(x0 > 2_590_000.0 && x1 < 2_610_000.0 && (y0, y1).1 == 1_210_000.0 && y0 > 1_190_000.0, "{part}"); + assert!(!part.contains("OUTPUTCRS"), "{part}"); + // EPSG's axis order decides, not the labels' names: LV03 names its east axis Y, and + // Gauss-Krüger zone 3 its north axis X. + let lv03 = + parse_describe(&c2, desc("http://www.opengis.net/def/crs/EPSG/0/21781", "Y X", "590000 190000", "610000 210000").as_bytes()) + .unwrap(); + let lv03 = lv03.native.unwrap(); + assert_eq!((lv03.envelope, lv03.axes), ([590_000.0, 190_000.0, 610_000.0, 210_000.0], Some(("Y".into(), "X".into())))); + let gk = parse_describe( + &c2, + desc("http://www.opengis.net/def/crs/EPSG/0/31467", "X Y", "5420000 3480000", "5440000 3500000").as_bytes(), + ) + .unwrap(); + let gk = gk.native.unwrap(); + assert_eq!((gk.envelope, gk.axes), ([3_480_000.0, 5_420_000.0, 3_500_000.0, 5_440_000.0], Some(("Y".into(), "X".into())))); + // A polar coverage: its bounds reach the pole within it. + let polar = parse_describe( + &c2, + desc("http://www.opengis.net/def/crs/EPSG/0/3031", "x y", "-3000000 -3000000", "3000000 3000000").as_bytes(), + ) + .unwrap(); + let [w, s, e, _] = polar.bbox.unwrap(); + assert_eq!((w, s, e), (-180.0, -90.0, 180.0), "{:?}", polar.bbox); + // No axis names it knows: EPSG's order (LV95 is east first). + let unnamed = parse_describe(&c2, desc(srs, "i j", "2590000 1190000", "2610000 1210000").as_bytes()).unwrap(); + assert_eq!(unnamed.native.unwrap().axes, Some(("i".into(), "j".into()))); + // Geographic, unread, or no labels: EPSG:4326 as before. + for (srs, labels, lo, hi) in [ + ("http://www.opengis.net/def/crs/EPSG/0/4258", "Lat Long", "46 7", "47 8"), + ("http://www.opengis.net/def/crs/EPSG/0/999999", "E N", "2590000 1190000", "2610000 1210000"), + (srs, "", "2590000 1190000", "2610000 1210000"), + ] { + let d = desc(srs, labels, lo, hi).replace(r#" axisLabels="""#, ""); + let info = parse_describe(&c2, d.as_bytes()).unwrap(); + assert!(info.native.is_none(), "{srs} {labels}"); + assert!( + get_coverage_url(&c2, &info, [7.4, 46.9, 7.5, 47.0]).contains("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326"), + "{srs}" + ); + } + // WCS 1.0: its native CRS, the box east first in it. + let c1 = Coverage { version: "1.0.0".into(), ..c2.clone() }; + let v1 = r#"dem + 7.3 46.87.6 47.1 + 2590000 11900002610000 1210000 + EPSG:2056 EPSG:4326EPSG:2056 + GeoTIFF"#; + let info = parse_describe(&c1, v1.as_bytes()).unwrap(); + assert_eq!(info.native.as_ref().map(|o| (o.crs, o.envelope)), Some((lv95, [2_590_000.0, 1_190_000.0, 2_610_000.0, 1_210_000.0]))); + assert_eq!(info.bbox, Some([7.3, 46.8, 7.6, 47.1])); + assert_eq!( + get_coverage_url(&c1, &info, [7.0, 46.0, 8.0, 48.0]), + "https://x.org/wcs?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=dem&CRS=EPSG:2056&BBOX=2590000,1190000,2610000,1210000&WIDTH=2048&HEIGHT=2048&FORMAT=GeoTIFF" + ); + // MapServer: an envelope in EPSG:4326 before the native one; a native system named by URN + // is asked for as `EPSG:`. + let mapserver = v1 + .replace(r#""#, r#"7.3 46.87.6 47.1"#) + .replace("EPSG:2056", "urn:ogc:def:crs:EPSG::2056"); + let info2 = parse_describe(&c1, mapserver.as_bytes()).unwrap(); + assert_eq!( + info2.native.as_ref().map(|o| (o.name.as_str(), o.envelope)), + Some(("EPSG:2056", [2_590_000.0, 1_190_000.0, 2_610_000.0, 1_210_000.0])) + ); + // Its envelope in another system than its native one: EPSG:4326 as before. + let other = parse_describe(&c1, v1.replace(r#"srsName="EPSG:2056""#, r#"srsName="EPSG:21781""#).as_bytes()).unwrap(); + assert!(other.native.is_none()); + } + #[test] fn wcs_coverages() { let v2 = r#" diff --git a/crates/data/src/ogc_document_tests.rs b/crates/data/src/ogc_document_tests.rs index c0e6cdd3dc..49d5056c11 100644 --- a/crates/data/src/ogc_document_tests.rs +++ b/crates/data/src/ogc_document_tests.rs @@ -16,7 +16,7 @@ fn requests(service: &Service) -> Vec { Offer::Features { url } => vec![url.clone()], Offer::Coverage(c) => vec![ describe_coverage_url(c), - get_coverage_url(c, &CoverageInfo { format: "image/tiff".into(), axes: None, bbox: None }, [1.0, 2.0, 3.0, 4.0]), + get_coverage_url(c, &CoverageInfo { format: "image/tiff".into(), axes: None, bbox: None, native: None }, [1.0, 2.0, 3.0, 4.0]), ], other => panic!("unexpected offer: {other:?}"), }; @@ -146,7 +146,11 @@ fn oversized_same_origin_document_targets_fail_closed() { Offer::Features { url } => vec![url.clone()], Offer::Coverage(c) => vec![ describe_coverage_url(c), - get_coverage_url(c, &CoverageInfo { format: "image/tiff".into(), axes: None, bbox: None }, [1.0, 2.0, 3.0, 4.0]), + get_coverage_url( + c, + &CoverageInfo { format: "image/tiff".into(), axes: None, bbox: None, native: None }, + [1.0, 2.0, 3.0, 4.0], + ), ], other => panic!("unexpected offer: {other:?}"), }; diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index a52bc38139..d6a17054e2 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -1,4 +1,4 @@ -//! Services' features asked for in their own coordinate system (#2032 C2f-3b): a WFS type in its +//! Services asked for in their own coordinate system (#2032 C2f-3b, C2f-3c): a WFS type in its //! default system and an ArcGIS layer in its service's, held in it as they come, with the //! longitude/latitude request kept where the system isn't one RustGIS reads. @@ -162,3 +162,49 @@ fn an_arcgis_layer_is_asked_for_in_its_services_system() { let said = notices(&s); assert!(said.len() == 1 && said[0].contains("1 service answer(s) named no coordinate system"), "{said:?}"); } + +/// A WCS coverage in LV95 is asked for in it, with no conversion by the server, and comes in as a +/// raster in LV95 for the map to resample once; a geographic one is asked in EPSG:4326 as before. +#[test] +fn a_wcs_coverage_is_asked_for_in_its_own_system() { + let lv95 = Crs::from_epsg(2056).unwrap(); + let r = rustgis_data::raster::Raster::new( + "dem", + 10, + 10, + vec![vec![500.0; 100]], + rustgis_data::raster::GeoTransform { origin_x: 2_600_000.0, origin_y: 1_200_100.0, pixel_width: 10.0, pixel_height: -10.0 }, + lv95, + None, + rustgis_data::raster::ColorHint::Gray, + "Float32", + ) + .unwrap(); + let (base, _) = super::serve_file(rustgis_data::raster::geotiff::write(&r, 0).unwrap(), false); + let caps = r#" + demTerrain + 7.43 46.957.45 46.96 + "#; + let describe = r#" + 2600000 12000002600100 1200100"#; + let url = format!("{base}/wcs"); + let mut s = Session::new(Project::default()); + let p = json!({"url": url, "layer": "dem", "text": caps, "describe": describe, "bbox": "full"}); + let c = s.run("service.coverage", &p).unwrap(); + let get = c["url"].as_str().unwrap(); + assert!( + get.contains("&SUBSET=E(2600000,2600100)&SUBSET=N(1200000,1200100)&SCALESIZE=E(2048),N(2048)") && !get.contains("CRS="), + "{get}" + ); + let added = s.run("service.add", &p).unwrap(); + let l = s.map().layer(added["layer"].as_u64().unwrap() as u32).unwrap(); + assert_eq!(l.raster.as_ref().unwrap().data.as_ref().unwrap().crs, lv95); + // In EPSG:4326: asked so, as before. + let geographic = describe + .replace("EPSG/0/2056", "EPSG/0/4326") + .replace(r#"axisLabels="E N""#, r#"axisLabels="Lat Long""#) + .replace("2600000 1200000", "46.95 7.43") + .replace("2600100 1200100", "46.96 7.45"); + let c = s.run("service.coverage", &json!({"url": url, "layer": "dem", "text": caps, "describe": geographic, "bbox": "full"})).unwrap(); + assert!(c["url"].as_str().unwrap().contains("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326&SUBSET=Long(7.43,7.45)"), "{c}"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index bd704cf0e8..bb88ea3217 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -335,7 +335,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | WFS 1.1 / 2.0 | Feature types | Their features downloaded as GeoJSON, following next links. Without a next link, WFS 1.x reads only the first response (requested limit: 50,000) and gives an incomplete-read notice when the server's reported `totalFeatures` exceeds the features read or, without a total, when the requested limit is reached. A server may cap this response below the requested limit. WFS 2.0 verifies the hits total and uses offset requests when needed, up to 100,000 features or more on a computer with more memory; unknown totals, repeated offset pages, repeated feature ids across offset pages (ignored, and counted), possible overlap between pages of rows without ids, and interrupted reads produce a notice | | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | -| WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in EPSG:4326, at most 2048 pixels on a side | +| WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in the coverage's own projected system when RustGIS reads it, else in EPSG:4326, at most 2048 pixels on a side | | ArcGIS REST | FeatureServer and MapServer layers; a MapServer's map; an ImageServer; a VectorTileServer | Layers queried as GeoJSON, or in protocol buffers (`f=pbf`, smaller and quicker to read) when the layer's description lists them and names its record limit (the description read first, or given up on after 15 seconds; a first protocol buffer page that can't be fetched or read has the layer read in GeoJSON, with a notice saying why), page by page past the server's record limit (`resultOffset`) up to 100,000 features or more on a computer with more memory (in protocol buffers, also no more than a quarter of the computer's memory once read, from 512 MB, the web app's limit, up to 3 GB; a later page past it ends the read with a notice, and the first page is always kept, within the reader's own limits for a page) (a command such as `service.add` waits a minute at most for the features), where the layer supports paging (ArcGIS Server 10.3 and later; otherwise up to the record limit); a layer comes in drawn as its description's `drawingInfo` says when its renderer is a simple one (fill, line and marker symbols, dashes), by the unique values of one field (as Unique Values, with the service's labels and its default symbol for the rest) or by class breaks (as Graduated Colors with the service's bounds and labels), others keeping RustGIS's symbol with a notice; a picture marker draws its image at its width, its height following the image's own proportion (without a width, its height is taken as its width, with a notice), and one whose image isn't in its description, or isn't a PNG or JPEG of at most 2 MiB of base64 and 2048 × 2048 pixels that RustGIS can decode (within the pixels and memory of marker images it decodes until it restarts), is a circle, grey or, among classes, in a ramp's colours, with a notice; and with its transparency whatever its renderer (a description that can't be read, or a query asking for its own `resultOffset` or `resultRecordCount`, which skips it, keeps RustGIS's symbol with a notice saying why); a map as its tile cache when it is Web Mercator's pyramid, else exported images; an ImageServer as exported images; a VectorTileServer as its MapLibre style | A long list stops at its first 2,000 layers, and a note says how many the service has. An OGC @@ -390,8 +390,16 @@ still apply, and Cancel stops the read. A coverage is read once, for the view when it was added (its DescribeCoverage first, for its axes, format and bounds; `service.coverage` gives the GetCoverage address alone). Moving the map doesn't -ask for it again: add it again for another area. The server reprojects it to EPSG:4326 (WCS 2.0 -through its CRS extension); one that can't answers with an error, which is shown. +ask for it again: add it again for another area. A coverage whose own system is a projected +system RustGIS reads is asked for in it: the area's box there, within the coverage's envelope, +and no conversion by the server, so it is resampled once, by the map. Its own system is WCS 2.0's +envelope's, whose axis labels are needed (`E N` or `N E` say the order; otherwise EPSG's order of +the system's axes does, as `X` and `Y` mean either), or WCS 1.0's native CRS with an envelope of +the spatial domain in it. Its longitude/latitude bounds then come from that envelope, so +`"bbox": "full"` works for it too. Otherwise (a geographic system, or one RustGIS doesn't read) +the server reprojects it to EPSG:4326 (WCS 2.0 through its CRS extension); one that can't answers +with an error, which is shown. A GeoTIFF answer that doesn't name its system is read as +longitude/latitude, with a notice. A feature type whose own system (its default one) is a projected system RustGIS reads is asked for in it, as `EPSG:`, and the layer is held in it, without a conversion by the server or From a93ad1d9f0ea3ba82510d8a9d3a931783f81ecd1 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 10:19:35 +0100 Subject: [PATCH 04/11] Review fixes: a coverage answer without its system is read in the one asked for; scaling names the grid's axes (#2032 C2f-3c) A GeoTIFF answer that doesn't say its system, with coordinates that aren't degrees, was refused once the coverage was asked in its own system. It is now read in that system, with a notice: service.coverage gives it as "crs", the app and layer.addUrl/layer.addDownload take it as coverageCrs (EPSG:, with coverage), and service.add passes it directly. Read once, in that system. SCALESIZE in the coverage's own system names its RectifiedGrid's axes, matched to east and north by their offset vectors; the envelope's labels otherwise. --- crates/data/src/ogc.rs | 95 +++++++++++++++++++++---- crates/data/src/raster/geotiff.rs | 37 ++++++++-- crates/engine/command-surface.txt | 4 +- crates/engine/src/cmd/layer.rs | 11 +-- crates/engine/src/cmd/raster.rs | 38 +++++++++- crates/engine/src/cmd/service.rs | 50 ++++++++----- crates/engine/src/tests/services_own.rs | 79 ++++++++++++++++++++ crates/ui-egui/src/lib.rs | 25 +++++++ docs/user-guide/data-formats.md | 5 +- 9 files changed, 300 insertions(+), 44 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index dad634b4ae..6e6a234fcb 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -1962,6 +1962,9 @@ pub struct CoverageSystem { pub envelope: [f64; 4], /// WCS 2.0's axis labels, the east-west one first. pub axes: Option<(String, String)>, + /// WCS 2.0's grid axis labels for the same axes (`i j`), which scaling names: matched to the + /// system's axes by their offset vectors; the system's labels when the grid doesn't say. + pub grid_axes: Option<(String, String)>, } fn wcs(url: &str, root: &Node) -> Service { @@ -2149,8 +2152,13 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result // axes decides, and the names only when that isn't known. let north_first = north_first_labels(&a, &b, false).or_else(|| epsg_north_first(crs)).or_else(|| north_first_labels(&a, &b, true))?; - let (envelope, axes) = if north_first { ([lo1, lo0, hi1, hi0], (b, a)) } else { ([lo0, lo1, hi0, hi1], (a, b)) }; - Some(CoverageSystem { crs, name: srs.clone(), envelope: ordered(envelope)?, axes: Some(axes) }) + let grid = grid_labels(&root); + let (envelope, axes, grid_axes) = if north_first { + ([lo1, lo0, hi1, hi0], (b, a), grid.map(|[g0, g1]| (g1, g0))) + } else { + ([lo0, lo1, hi0, hi1], (a, b), grid.map(|[g0, g1]| (g0, g1))) + }; + Some(CoverageSystem { crs, name: srs.clone(), envelope: ordered(envelope)?, axes: Some(axes), grid_axes }) }); let bbox = bbox.or_else(|| own.as_ref().and_then(|o| lonlat_of(o.envelope, o.crs))); let native = root.descendants().find(|n| n.is_element() && local(n) == "nativeFormat").map(|n| text_of(&n)); @@ -2199,12 +2207,38 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result .flat_map(|p| text_of(&p).split_whitespace().filter_map(|t| t.parse().ok()).collect::>()) .collect(); let envelope = ordered([*pos.first()?, *pos.get(1)?, *pos.get(2)?, *pos.get(3)?])?; - Some(CoverageSystem { crs, name, envelope, axes: None }) + Some(CoverageSystem { crs, name, envelope, axes: None, grid_axes: None }) })(); let bbox = bbox.or_else(|| own.as_ref().and_then(|o| lonlat_of(o.envelope, o.crs))); Ok(CoverageInfo { format: tiff_format(formats.iter().map(String::as_str)), axes: None, bbox, native: own }) } +/// A WCS 2.0 coverage's grid axis labels (its `RectifiedGrid`'s), in the order of the axes of +/// its system as the envelope gives them: each grid axis goes with the system axis its offset +/// vector runs along. `None` when the grid doesn't say, or its labels or offsets don't fit. +fn grid_labels(root: &Node) -> Option<[String; 2]> { + let grid = root.descendants().find(|n| n.is_element() && local(n) == "RectifiedGrid")?; + let text = child_text(&grid, "axisLabels").or_else(|| grid.attribute("axisLabels").map(str::to_string))?; + let labels: Vec<&str> = text.split_whitespace().collect(); + let ok = |s: &str| !s.is_empty() && s.len() <= 32 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'); + let [l0, l1] = labels[..] else { return None }; + if !ok(l0) || !ok(l1) { + return None; + } + // The system axis each offset vector runs along: its larger component. + let along = |v: &Node| -> Option { + let c: Vec = text_of(v).split_whitespace().filter_map(|t| t.parse().ok()).collect(); + let (x, y) = (c.first()?.abs(), c.get(1)?.abs()); + (x != y).then_some(usize::from(y > x)) + }; + let offsets: Vec = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect::>()?; + match offsets[..] { + [0, 1] => Some([l0.to_string(), l1.to_string()]), + [1, 0] => Some([l1.to_string(), l0.to_string()]), + _ => None, + } +} + /// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one /// first, or neither; with `xy`, `x` and `y` count as east and north too. fn north_first_labels(a: &str, b: &str, xy: bool) -> Option { @@ -2291,6 +2325,12 @@ pub fn coverage_size(area: [f64; 4]) -> (u32, u32) { /// Otherwise, or when the area has no place there, in EPSG:4326 (the server reprojects; WCS 2.0 /// through its CRS extension). Scaled to fit [`COVERAGE_MAX_PIXELS`]. pub fn get_coverage_url(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> String { + get_coverage(c, info, area).0 +} + +/// [`get_coverage_url`], with the system it asks the coverage in when that is its own (not +/// EPSG:4326): an answer that doesn't say its system is read in it. +pub fn get_coverage(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> (String, Option) { // An area holding the whole coverage asks for its envelope, not for that converted there and // back. let whole = info.bbox.is_some_and(|b| area[0] <= b[0] && area[1] <= b[1] && area[2] >= b[2] && area[3] >= b[3]); @@ -2300,12 +2340,15 @@ pub fn get_coverage_url(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> St let [x0, y0, x1, y1] = b; let (pw, ph) = coverage_size(b); let q = match (&own.axes, c.version.starts_with('2')) { - // Without a CRS asked for, WCS 2.0 subsets and answers in the coverage's own. + // Without a CRS asked for, WCS 2.0 subsets and answers in the coverage's own; scaling + // names the grid's axes. (Some((e, n)), true) => Some(format!( - "SERVICE=WCS&VERSION={}&REQUEST=GetCoverage&COVERAGEID={}&FORMAT={}&SUBSET={e}({x0},{x1})&SUBSET={n}({y0},{y1})&SCALESIZE={e}({pw}),{n}({ph})", + "SERVICE=WCS&VERSION={}&REQUEST=GetCoverage&COVERAGEID={}&FORMAT={}&SUBSET={e}({x0},{x1})&SUBSET={n}({y0},{y1})&SCALESIZE={ge}({pw}),{gn}({ph})", c.version, encode(&c.id), - encode(&info.format) + encode(&info.format), + ge = own.grid_axes.as_ref().map_or(e, |g| &g.0), + gn = own.grid_axes.as_ref().map_or(n, |g| &g.1), )), (_, false) => Some(format!( "SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE={}&CRS={}&BBOX={x0},{y0},{x1},{y1}&WIDTH={pw}&HEIGHT={ph}&FORMAT={}", @@ -2316,7 +2359,7 @@ pub fn get_coverage_url(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> St (None, true) => None, }; if let Some(q) = q { - return with_query(&c.endpoint, &q); + return (with_query(&c.endpoint, &q), Some(own.crs)); } } let [w, s, e, n] = area; @@ -2337,7 +2380,7 @@ pub fn get_coverage_url(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> St encode(&info.format) ) }; - with_query(&c.endpoint, &q) + (with_query(&c.endpoint, &q), None) } /// The part of `area` a coverage covers (all of `area` when its bounds aren't known); `None` when @@ -8729,6 +8772,36 @@ mod tests { .unwrap(); let [w, s, e, _] = polar.bbox.unwrap(); assert_eq!((w, s, e), (-180.0, -90.0, 180.0), "{:?}", polar.bbox); + // Scaling names the grid's axes, matched by their offset vectors; the request says the + // system it asks in, which the EPSG:4326 one doesn't. + let gridded = |labels: &str, offsets: &str| { + desc(srs, "E N", "2590000 1190000", "2610000 1210000").replace( + "", + &format!( + r#"{labels}{offsets}"# + ), + ) + }; + let ij = + parse_describe(&c2, gridded("i j", "10 00 -10").as_bytes()).unwrap(); + let (get, asked) = get_coverage(&c2, &ij, ij.bbox.unwrap()); + assert!(get.contains("&SUBSET=E(2590000,2610000)&SUBSET=N(1190000,1210000)&SCALESIZE=i(2048),j(2048)"), "{get}"); + assert_eq!(asked, Some(lv95)); + let ji = + parse_describe(&c2, gridded("i j", "0 -1010 0").as_bytes()).unwrap(); + assert_eq!(ji.native.unwrap().grid_axes, Some(("j".into(), "i".into()))); + let unmatched = + parse_describe(&c2, gridded("i j", "10 100 -10").as_bytes()).unwrap(); + assert!(get_coverage_url(&c2, &unmatched, unmatched.bbox.unwrap()).contains("SCALESIZE=E(2048),N(2048)")); + // North first (Gauss-Krüger zone 3, `N E`): the grid's axes follow the file's order, then + // turn with the system's. + let gk = desc("http://www.opengis.net/def/crs/EPSG/0/31467", "N E", "5420000 3480000", "5440000 3500000").replace( + "", + "i j0 10-10 0", + ); + let gk = parse_describe(&c2, gk.as_bytes()).unwrap(); + let get = get_coverage_url(&c2, &gk, gk.bbox.unwrap()); + assert!(get.contains("&SUBSET=E(3480000,3500000)&SUBSET=N(5420000,5440000)&SCALESIZE=i(2048),j(2048)"), "{get}"); // No axis names it knows: EPSG's order (LV95 is east first). let unnamed = parse_describe(&c2, desc(srs, "i j", "2590000 1190000", "2610000 1210000").as_bytes()).unwrap(); assert_eq!(unnamed.native.unwrap().axes, Some(("i".into(), "j".into()))); @@ -8741,10 +8814,8 @@ mod tests { let d = desc(srs, labels, lo, hi).replace(r#" axisLabels="""#, ""); let info = parse_describe(&c2, d.as_bytes()).unwrap(); assert!(info.native.is_none(), "{srs} {labels}"); - assert!( - get_coverage_url(&c2, &info, [7.4, 46.9, 7.5, 47.0]).contains("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326"), - "{srs}" - ); + let (get, asked) = get_coverage(&c2, &info, [7.4, 46.9, 7.5, 47.0]); + assert!(get.contains("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326") && asked.is_none(), "{srs}"); } // WCS 1.0: its native CRS, the box east first in it. let c1 = Coverage { version: "1.0.0".into(), ..c2.clone() }; diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 13491401b5..98f73f1790 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1324,7 +1324,14 @@ pub fn read(r: R, name: &str) -> Result { /// [`read`], with the no-data value a sidecar gives (see [`read_limited_with_nodata`]). pub(super) fn read_with_nodata(r: R, name: &str, sidecar_nodata: Option) -> Result { - read_limited_with_nodata(reader(r).map_err(err)?, name, max_samples(), None, sidecar_nodata) + read_limited_with_nodata(reader(r).map_err(err)?, name, max_samples(), None, sidecar_nodata, None) +} + +/// [`read`] of a file asked for in `asked` (a WCS coverage requested in its own system, #2032): +/// a file that doesn't say its coordinate system, and whose coordinates aren't degrees, is read in +/// `asked`, and said. One that names a system is read in it, as [`read`] reads it. +pub fn read_asked_in(r: R, name: &str, asked: Crs) -> Result { + read_limited_with_nodata(reader(r).map_err(err)?, name, max_samples(), None, None, Some(asked)) } /// A single-band `UInt32` GeoTIFF of packed colour, each pixel `0xAABBGGRR` (alpha, blue, green @@ -1470,7 +1477,7 @@ fn read_file_with_revision( }; let decoded = reader(std::io::BufReader::new(file)) .map_err(err) - .and_then(|r| read_limited_with_nodata(r, name, max_samples(), Some(&open), sidecar_nodata)); + .and_then(|r| read_limited_with_nodata(r, name, max_samples(), Some(&open), sidecar_nodata, None)); // A file cut short while it is read fails to decode: the revision says whether that was a // change to wait out (Cancel is said as itself). if let Ok(original) = &revision @@ -1491,7 +1498,7 @@ fn read_file_with_revision( /// [`read`], holding at most `max` samples (the tests' small limit exercises the overviews), with /// `open` making more readers of the same file for decoding it on several threads. pub(super) fn read_limited(r: Reader<'_>, name: &str, max: usize, open: Option>) -> Result { - read_limited_with_nodata(r, name, max, open, None) + read_limited_with_nodata(r, name, max, open, None, None) } /// [`read_limited`], with the no-data value a sidecar gives (`.aux.xml`, applied after reading by @@ -1502,6 +1509,7 @@ pub(super) fn read_limited_with_nodata( max: usize, open: Option>, sidecar_nodata: Option, + asked: Option, ) -> Result { // The full image says whether it is read as a palette image, whichever image is read, as a // COG window has it: a grey full image's stray colour table colours nothing, nor do palette @@ -1834,7 +1842,10 @@ pub(super) fn read_limited_with_nodata( { return Err(DataError::Format(e.clone())); } - if geo.geographic_model || degrees { + if let Some(asked) = asked.filter(|_| geo.custom_error.is_none() && !geo.geographic_model && !degrees) { + assumed = Some(format!("it doesn't say its coordinate system: read in {}, the system it was asked for in", asked.label())); + asked + } else if geo.geographic_model || degrees { assumed = Some(match &geo.custom_error { // The file's own projection couldn't be read, but its coordinates fit in degrees: // why is said, not dropped. @@ -2665,6 +2676,24 @@ mod tests { out.into_inner() } + /// A file asked for in a system (a WCS coverage, #2032) that doesn't say its own is read in it + /// when its coordinates aren't degrees, and says so; one that names its system, or whose + /// coordinates are degrees, is read as [`read`] reads it. + #[test] + fn a_file_without_its_system_is_read_in_the_one_asked_for() { + let lv95 = Crs::from_epsg(2056).unwrap(); + let metres = placed_tiff((2_600_000.0, 1_200_100.0), 10.0, None); + assert!(read(std::io::Cursor::new(metres.clone()), "g").is_err()); + let r = read_asked_in(std::io::Cursor::new(metres), "g", lv95).unwrap(); + assert_eq!((r.crs, r.transform.origin_x), (lv95, 2_600_000.0)); + assert!(r.crs_assumed && r.lost.iter().any(|l| l.contains("read in EPSG:2056, the system it was asked for in")), "{:?}", r.lost); + let named = placed_tiff((600_000.0, 5_200_000.0), 10.0, Some(&[1, 1, 0, 1, 3072, 0, 1, 25832])); + let r = read_asked_in(std::io::Cursor::new(named), "g", lv95).unwrap(); + assert_eq!((r.crs, r.crs_assumed), (Crs::from_epsg(25832).unwrap(), false)); + let degrees = placed_tiff((7.4, 47.0), 0.01, None); + assert_eq!(read_asked_in(std::io::Cursor::new(degrees), "g", lv95).unwrap().crs, Crs::LonLat); + } + /// A grid whose file gives no usable coordinate system but whose coordinates fit in degrees is /// read as WGS 84 and says why, once. A file that gives its system says nothing of the kind, and /// metres of a projection that can't be read are still refused with the reason (AGENTS.md, Never diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 8e7148c2ed..2f99f709a9 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -216,13 +216,13 @@ layer.addData path name? layer? paperSpace? blocks? stream? as? crs? x? y? wkt? layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? layer.addDatabase database password? layer? crs? name? stream? -layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? service? bounds? coverage? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? +layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? layer.addEncodedPolyline polyline precision? name? layer.addLayerFile path? text? data? layer.addPhotos paths? folder? name? layer.addSample name layer.addSql sql name? database? password? crs? stream? ran? -layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? request? +layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? layer.aggregation layer? shape size? layer.blend layer? mode diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 63e0052a6e..57235c1bca 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,10 +51,10 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error), "coverageCrs"?: "EPSG: (with coverage: service.coverage's \"crs\", the system it was asked in, for an answer that doesn't say its own)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) - .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), + .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in ("crs"), for an answer that doesn't say its own), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), @@ -5330,7 +5330,9 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let name = url_file_name(url, &bytes).map_err(named)?; let left_out = parts_left_out(url, &bytes, p); let cut = url_name_cut("Add Data From URL", url, p, &bytes); - let r = super::raster::add_named_bytes(s, p, name, bytes, b(p, "zoom")).map_err(named)?; + // A WCS coverage's own system it was asked for in, for an answer that doesn't say it. + let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(p) } else { None }; + let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), None, asked).map_err(named)?; if let Some(n) = left_out { s.notify(n, false); } @@ -6797,7 +6799,8 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let drawn = s.landed_pages.iter().position(|(d, _)| *d == id).map(|i| s.landed_pages.remove(i).1); #[cfg(target_arch = "wasm32")] let drawn = None; - let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn)?; + let asked = if coverage { super::raster::coverage_system(p) } else { None }; + let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn, asked)?; if let Some(n) = left_out { s.notify(n, false); } diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c7a430b938..39aeb43d3a 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -746,12 +746,34 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { /// desktop app's downloads land with theirs drawn off the frame ([`download_page`]) and its file /// drops are read by path on the read queue, so a caller here is the command line, Python or a /// script, with no window to hold. +/// The system a WCS coverage was asked for in (`"coverageCrs"`, internal: the GetCoverage +/// request's, from `service.coverage`), for an answer that doesn't say its own. +pub(crate) fn coverage_system(p: &Value) -> Option { + // Only `EPSG:`: `Crs::parse` takes WKT and PROJ text too, and keeps a system for them. + let code: u32 = ps(p, "coverageCrs")?.strip_prefix("EPSG:")?.parse().ok()?; + rustgis_data::raster::Crs::from_epsg(code).filter(|c| !c.is_geographic()) +} + pub(crate) fn add_named_bytes(s: &mut Session, p: &Value, name: String, bytes: Vec, zoom: Option) -> CmdResult { - add_named_bytes_read(s, p, name, bytes, zoom, None) + add_named_bytes_read(s, p, name, bytes, zoom, None, None) +} + +/// [`add_named_bytes`] of a WCS coverage's answer asked for in `asked`, its own system: a GeoTIFF +/// that doesn't say its system is read in it (#2032). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn add_coverage_bytes( + s: &mut Session, + p: &Value, + name: String, + bytes: Vec, + asked: Option, +) -> CmdResult { + add_named_bytes_read(s, p, name, bytes, None, None, asked) } /// [`add_named_bytes`], with a PDF's page drawn already off the frame (a download's, -/// [`read_download_shared_page`]) instead of here. +/// [`read_download_shared_page`]) instead of here, and a WCS coverage's own system it was asked +/// for in (`asked`, for an answer that doesn't say it). pub(crate) fn add_named_bytes_read( s: &mut Session, p: &Value, @@ -759,6 +781,7 @@ pub(crate) fn add_named_bytes_read( bytes: Vec, zoom: Option, drawn: Option, + asked: Option, ) -> CmdResult { // A geotagged photo (an upload, a drop): a point in the photo layer, so several uploads // gather in one. @@ -780,7 +803,16 @@ pub(crate) fn add_named_bytes_read( let page = pdf_page(&name, p)?; let mut r = match drawn { Some(r) => r, - None => raster::read_shared_page(&name, bytes.clone(), page.as_deref(), !scan).map_err(|e| format!("{name}: {e}"))?, + // A WCS coverage asked for in its own system (#2032): an answer that doesn't say its + // system is read in that one; one that says it is read as any GeoTIFF. + None => match asked.filter(|_| !scan && [".tif", ".tiff"].iter().any(|x| name.to_ascii_lowercase().ends_with(x))) { + Some(asked) => { + let stem = std::path::Path::new(&name).file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); + rustgis_data::raster::geotiff::read_asked_in(std::io::Cursor::new(bytes.as_slice()), stem, asked) + .map_err(|e| format!("{name}: {e}"))? + } + None => raster::read_shared_page(&name, bytes.clone(), page.as_deref(), !scan).map_err(|e| format!("{name}: {e}"))?, + }, }; r.lost.extend(raster::elevation_ignores(&name, ps(p, "layer"), ps(p, "crs"))); if scan { diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 964f72f25c..98ee770f6c 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -38,7 +38,7 @@ pub fn commands() -> Vec { r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "where"?: "an ArcGIS feature layer's SQL where clause (1=1 when absent); combined with bbox and kept by every page; rejected clauses give an error", "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login"}"#, ), C::new("service.coverage", "WCS Coverage Request", "Home › Add", coverage).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it)"#, + r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it), its area in longitude/latitude, and "crs": the coverage's own system when it is asked in it (layer.addUrl's "coverageCrs", for an answer that doesn't say its system)"#, ), C::new("catalog.search", "Search Catalogue", "Home › Add", catalog_search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default), "start"?: "the first record's position (a page's next)", "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them)"#, @@ -1535,7 +1535,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis )), Offer::Coverage(c) => { let anonymous = capability_crossed || crosses_origin(source, &c.endpoint) || s.web_logins.is_anonymous(); - let (get, _, _) = match ps(p, "describe") { + let (get, _, _, asked) = match ps(p, "describe") { // A plugin's command: its description read off the frame, as its documents are. None if leaving => { let c = coverage_for(c, anonymous); @@ -1548,14 +1548,14 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis let info = rustgis_data::ogc::parse_describe(&c, &bytes)?; // Recorded by the read if it came from the internet, as in `coverage_request`. let public = public || cache::ceiling_for(&described) == Reach::Public; - let (get, area) = coverage_request_from(s, p, &c, &info, public)?; - (get, area, described) + let (get, area, asked) = coverage_request_from(s, p, &c, &info, public)?; + (get, area, described, asked) } _ => coverage_request(s, p, c, anonymous, public)?, }; #[cfg(target_arch = "wasm32")] { - let _ = get; + let _ = (get, asked); Err(crate::sources::message_with_address( &url, "in the web app, Home › Add › Add Data › From Service downloads the coverage", @@ -1563,17 +1563,20 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } #[cfg(not(target_arch = "wasm32"))] { + // The system it is asked in, when its own: an answer that doesn't say it is read in it. + let asked_code = asked.map(|c| c.code()); crate::service_logins::anonymously(s, anonymous, |s| { if leaving { // (Whole: a coverage's address may end in .tif, and it is read as a raster.) - return super::layer::add_url( - s, - &json!({"url": get, "name": name, "coverage": true, "whole": true, "fromDocument": public}), - ); + let mut q = json!({"url": get, "name": name, "coverage": true, "whole": true, "fromDocument": public}); + if let Some(code) = &asked_code { + q["coverageCrs"] = json!(code); + } + return super::layer::add_url(s, &q); } let bytes = crate::render::rustgis_tiles::cache::download_blocking(&get).map_err(|e| format!("{name}: {e}"))?; coverage_check(&name, &bytes)?; - let r = super::raster::add_named_bytes(s, &json!({"name": name}), format!("{name}.tif"), bytes, None)?; + let r = super::raster::add_coverage_bytes(s, &json!({"name": name}), format!("{name}.tif"), bytes, asked)?; mark_service_source(s, &r, &get); Ok(r) }) @@ -1696,7 +1699,14 @@ fn coverage_area(s: &Session, p: &Value, info: &rustgis_data::ogc::CoverageInfo, /// fetched (waiting for it). /// With `public` (a coverage a document read from the internet lists), its description and its /// GetCoverage address are fetched only from the internet, here or by the app. -fn coverage_request(s: &Session, p: &Value, c: &Coverage, anonymous: bool, public: bool) -> Result<(String, [f64; 4], String), String> { +/// The system it asks the coverage in comes with it when that is the coverage's own. +fn coverage_request( + s: &Session, + p: &Value, + c: &Coverage, + anonymous: bool, + public: bool, +) -> Result<(String, [f64; 4], String, Option), String> { let c = coverage_for(c, anonymous); let c = c.as_ref(); let describe = describe_address(c); @@ -1710,8 +1720,8 @@ fn coverage_request(s: &Session, p: &Value, c: &Coverage, anonymous: bool, publi // A description read from the internet (here, or by the app, which records it) holds the // GetCoverage request built from it there too, however the endpoint's name resolves then. let public = public || cache::ceiling_for(&describe) == Reach::Public; - let (get, area) = coverage_request_from(s, p, c, &info, public)?; - Ok((get, area, describe)) + let (get, area, asked) = coverage_request_from(s, p, c, &info, public)?; + Ok((get, area, describe, asked)) } /// A coverage as it is asked for: with no saved login when `anonymous`. @@ -1737,14 +1747,15 @@ fn coverage_request_from( c: &Coverage, info: &rustgis_data::ogc::CoverageInfo, public: bool, -) -> Result<(String, [f64; 4]), String> { +) -> Result<(String, [f64; 4], Option), String> { let area = coverage_area(s, p, info, &c.id)?; - let get = crate::render::rustgis_tiles::logins::inherit(&c.endpoint, &rustgis_data::ogc::get_coverage_url(c, info, area)); + let (get, asked) = rustgis_data::ogc::get_coverage(c, info, area); + let get = crate::render::rustgis_tiles::logins::inherit(&c.endpoint, &get); crate::render::rustgis_tiles::address::check(&get, Some(&c.endpoint))?; if public { cache::restrict_to_public(&get); } - Ok((get, area)) + Ok((get, area, asked)) } /// Reads a coverage's description, recording one that came from the internet @@ -1795,8 +1806,13 @@ fn coverage(s: &mut Session, p: &Value) -> CmdResult { || crosses_origin(&source.address, &c.endpoint) || s.web_logins.is_anonymous() || p.get("anonymous").and_then(Value::as_bool) == Some(true); - let (get, area, describe) = coverage_request(s, p, c, anonymous, source.public)?; + let (get, area, describe, asked) = coverage_request(s, p, c, anonymous, source.public)?; let mut out = json!({"url": get, "name": layer.title, "bbox": area, "describe": describe}); + // The system the request asks the coverage in, when its own: given to the add as + // `coverageCrs`, for an answer that doesn't say it. + if let Some(crs) = asked { + out["crs"] = json!(crs.code()); + } if anonymous { out["anonymous"] = json!(true); } diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index d6a17054e2..7600fcfb2a 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -208,3 +208,82 @@ fn a_wcs_coverage_is_asked_for_in_its_own_system() { let c = s.run("service.coverage", &json!({"url": url, "layer": "dem", "text": caps, "describe": geographic, "bbox": "full"})).unwrap(); assert!(c["url"].as_str().unwrap().contains("OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/4326&SUBSET=Long(7.43,7.45)"), "{c}"); } + +/// A 2 × 2 byte GeoTIFF placed at `corner`, `step` a pixel, that doesn't say its coordinate system +/// (no GeoKey directory), written by hand: little-endian, one strip. +fn untagged_tiff(corner: (f64, f64), step: f64) -> Vec { + let entries: [(u16, u16, u32, u32); 11] = [ + (256, 3, 1, 2), + (257, 3, 1, 2), + (258, 3, 1, 8), + (259, 3, 1, 1), + (262, 3, 1, 1), + (273, 4, 1, 218), + (277, 3, 1, 1), + (278, 3, 1, 2), + (279, 4, 1, 4), + (33550, 12, 3, 146), + (33922, 12, 6, 170), + ]; + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&8u32.to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, kind, count, value) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&kind.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(out.len(), 146); + for v in [step, step, 0.0, 0.0, 0.0, 0.0, corner.0, corner.1, 0.0] { + out.extend_from_slice(&v.to_le_bytes()); + } + assert_eq!(out.len(), 218); + out.extend_from_slice(&[1, 2, 3, 4]); + out +} + +/// A coverage asked for in LV95 whose answer doesn't say its system is read in LV95, and says so, +/// whether `service.add` downloads it or the app does (`service.coverage` gives the system, and +/// `layer.addDownload` takes it as `coverageCrs`). +#[test] +fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { + let lv95 = Crs::from_epsg(2056).unwrap(); + let tiff = untagged_tiff((2_600_000.0, 1_200_020.0), 10.0); + let (base, _) = super::serve_file(tiff.clone(), false); + let caps = r#" + demTerrain"#; + let describe = r#" + 2600000 12000002600020 1200020"#; + let url = format!("{base}/wcs"); + let p = json!({"url": url, "layer": "dem", "text": caps, "describe": describe, "bbox": "full"}); + let mut s = Session::new(Project::default()); + let c = s.run("service.coverage", &p).unwrap(); + assert_eq!(c["crs"], "EPSG:2056", "{c}"); + let crs_of = |s: &Session, id: &serde_json::Value| { + s.map().layer(id.as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().crs + }; + let added = s.run("service.add", &p).unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + assert!(notices(&s).iter().any(|n| n.contains("the system it was asked for in")), "{:?}", notices(&s)); + // As the app adds it. + let get = c["url"].as_str().unwrap(); + s.downloaded.push((7, tiff.clone())); + let added = + s.run("layer.addDownload", &json!({"id": 7, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + // Without the system asked for (or with one that isn't an EPSG code of a projected system), + // its metres can't be placed: refused, as before. + for (id, crs) in [(8, None), (9, Some("EPSG:4326")), (10, Some("2056")), (11, Some("EPSG:x")), (12, Some("+proj=somerc"))] { + s.downloaded.push((id, tiff.clone())); + let mut q = json!({"id": id, "url": get, "name": "Terrain", "coverage": true}); + if let Some(c) = crs { + q["coverageCrs"] = json!(c); + } + assert!(s.run("layer.addDownload", &q).is_err(), "{crs:?}"); + } + // Added by address, as the command line adds service.coverage's address. + let added = s.run("layer.addUrl", &json!({"url": get, "name": "By address", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ade5aebcfe..81349039ea 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5891,6 +5891,11 @@ impl RustGisApp { q[k] = json!(true); } } + // A coverage's own system it was asked for in (`service.coverage`'s "crs"), for an + // answer that doesn't say it. + if let Some(crs) = p.get("coverageCrs").filter(|v| v.is_string()) { + q["coverageCrs"] = crs.clone(); + } if let Some(from_document) = p.get("fromDocument").and_then(Value::as_bool) { q["fromDocument"] = json!(from_document); } @@ -6576,6 +6581,10 @@ impl RustGisApp { let connection = params.as_object_mut().and_then(|p| p.remove("connection")); let get = c.get("url").and_then(Value::as_str).unwrap_or("").to_string(); let mut p = json!({"url": get, "name": title, "coverage": true}); + // The system it was asked in, for an answer that doesn't say it. + if let Some(crs) = c.get("crs").and_then(Value::as_str) { + p["coverageCrs"] = json!(crs); + } // Its service's document came from the internet: so does the coverage. if cache::ceiling_for(&get) == Reach::Public { p["fromDocument"] = json!(true); @@ -7877,6 +7886,22 @@ mod record_tests { } } + /// A WCS coverage's download keeps the system it was asked for in (`coverageCrs`, from + /// `service.coverage`), for `layer.addDownload` to read an answer that doesn't say its own in + /// it (#2032); a value that isn't text isn't passed on. + #[test] + fn a_coverage_download_keeps_the_system_it_was_asked_in() { + let _turn = crate::fetching::turn(); + rustgis_engine::render::rustgis_tiles::cache::set_fetcher(|_, _| {}); + let mut app = RustGisApp::with_sample(); + let url = "https://wcs.invalid/wcs?SERVICE=WCS&VERSION=2.0.1&REQUEST=GetCoverage&COVERAGEID=dem"; + app.run("ui.addUrl", json!({"url": url, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); + app.run("ui.addUrl", json!({"url": url, "name": "Other", "coverage": true, "coverageCrs": 2056})).unwrap(); + let kept: Vec = app.ui.downloads.iter().map(|d| d.params["coverageCrs"].clone()).collect(); + assert_eq!(kept, [json!("EPSG:2056"), serde_json::Value::Null]); + assert!(app.ui.downloads.iter().all(|d| d.params["coverage"] == true)); + } + /// A window read off the frame is a step all the same: the command that reads it, with its box, /// not the download that can't be added again (#1330). #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index bb88ea3217..7b489f23fe 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -398,8 +398,9 @@ the system's axes does, as `X` and `Y` mean either), or WCS 1.0's native CRS wit the spatial domain in it. Its longitude/latitude bounds then come from that envelope, so `"bbox": "full"` works for it too. Otherwise (a geographic system, or one RustGIS doesn't read) the server reprojects it to EPSG:4326 (WCS 2.0 through its CRS extension); one that can't answers -with an error, which is shown. A GeoTIFF answer that doesn't name its system is read as -longitude/latitude, with a notice. +with an error, which is shown. A GeoTIFF answer that doesn't name its system is read in the +system it was asked for in, when its coordinates aren't degrees, with a notice; otherwise as +longitude/latitude when they are, with a notice, and refused when they aren't. A feature type whose own system (its default one) is a projected system RustGIS reads is asked for in it, as `EPSG:`, and the layer is held in it, without a conversion by the server or From 2643901df4178568d887fe8a918bc002ba7fe590 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 10:53:39 +0100 Subject: [PATCH 05/11] Review fixes: the coverage request names its system, read back from the address; scaling always names grid axes (#2032 C2f-3c) The WCS 2.0 request in a coverage's own system names it (SUBSETTINGCRS and OUTPUTCRS, as the EPSG:4326 request did), so layer.addUrl and layer.addDownload read an answer that doesn't say its system in the one its address asks for, without coverageCrs (which still comes first). SCALESIZE uses the grid's labels whenever it has two, in its own order when its offsets don't say. Docs name the geographic-model case; service.coverage's output key is coverageCrs. --- crates/data/src/ogc.rs | 63 ++++++++++++++++++++----- crates/engine/src/cmd/layer.rs | 8 ++-- crates/engine/src/cmd/raster.rs | 20 ++++---- crates/engine/src/cmd/service.rs | 4 +- crates/engine/src/tests/services_own.rs | 24 +++++++--- crates/ui-egui/src/lib.rs | 2 +- docs/user-guide/data-formats.md | 8 ++-- 7 files changed, 92 insertions(+), 37 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6e6a234fcb..22dc2d45b6 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2215,7 +2215,9 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result /// A WCS 2.0 coverage's grid axis labels (its `RectifiedGrid`'s), in the order of the axes of /// its system as the envelope gives them: each grid axis goes with the system axis its offset -/// vector runs along. `None` when the grid doesn't say, or its labels or offsets don't fit. +/// vector runs along, else (offsets that don't say) in the grid's own order, as grids are most +/// often laid out. Scaling must name grid axes, so the grid's labels are used whenever it has +/// two. `None` when it doesn't. fn grid_labels(root: &Node) -> Option<[String; 2]> { let grid = root.descendants().find(|n| n.is_element() && local(n) == "RectifiedGrid")?; let text = child_text(&grid, "axisLabels").or_else(|| grid.attribute("axisLabels").map(str::to_string))?; @@ -2231,12 +2233,25 @@ fn grid_labels(root: &Node) -> Option<[String; 2]> { let (x, y) = (c.first()?.abs(), c.get(1)?.abs()); (x != y).then_some(usize::from(y > x)) }; - let offsets: Vec = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect::>()?; - match offsets[..] { - [0, 1] => Some([l0.to_string(), l1.to_string()]), - [1, 0] => Some([l1.to_string(), l0.to_string()]), - _ => None, + let offsets: Option> = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect(); + match offsets.as_deref() { + Some([1, 0]) => Some([l1.to_string(), l0.to_string()]), + _ => Some([l0.to_string(), l1.to_string()]), + } +} + +/// The projected system a WCS GetCoverage address asks its coverage in, when the address says +/// one (WCS 2.0's `OUTPUTCRS`, WCS 1.0's `RESPONSE_CRS`, else its `CRS`): a GeoTIFF answer that +/// doesn't say its system is read in it. `None` for longitude/latitude, a system RustGIS doesn't +/// read, and any other address. +pub fn coverage_request_system(url: &str) -> Option { + let is = |key: &str, value: &str| query_value(url, key).is_some_and(|v| v.eq_ignore_ascii_case(value)); + if !(is("service", "wcs") && is("request", "getcoverage")) { + return None; } + let decoded = |v: &str| v.replace("%3A", ":").replace("%3a", ":").replace("%2F", "/").replace("%2f", "/"); + let named = ["outputcrs", "response_crs", "crs"].iter().find_map(|k| query_value(url, k)).map(decoded)?; + projected_system(&named).map(|(_, crs)| crs) } /// Whether a coverage's axis labels name the north-south axis first (`N E`), the east-west one @@ -2340,13 +2355,15 @@ pub fn get_coverage(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> (Strin let [x0, y0, x1, y1] = b; let (pw, ph) = coverage_size(b); let q = match (&own.axes, c.version.starts_with('2')) { - // Without a CRS asked for, WCS 2.0 subsets and answers in the coverage's own; scaling - // names the grid's axes. + // In the coverage's own system, named (as EPSG:4326 was: the CRS extension the + // servers answering that request have), so the address says which system its answer + // is in ([`coverage_request_system`]); scaling names the grid's axes. (Some((e, n)), true) => Some(format!( - "SERVICE=WCS&VERSION={}&REQUEST=GetCoverage&COVERAGEID={}&FORMAT={}&SUBSET={e}({x0},{x1})&SUBSET={n}({y0},{y1})&SCALESIZE={ge}({pw}),{gn}({ph})", + "SERVICE=WCS&VERSION={}&REQUEST=GetCoverage&COVERAGEID={}&FORMAT={}&SUBSETTINGCRS={crs}&OUTPUTCRS={crs}&SUBSET={e}({x0},{x1})&SUBSET={n}({y0},{y1})&SCALESIZE={ge}({pw}),{gn}({ph})", c.version, encode(&c.id), encode(&info.format), + crs = format!("http://www.opengis.net/def/crs/EPSG/0/{}", own.crs.epsg()), ge = own.grid_axes.as_ref().map_or(e, |g| &g.0), gn = own.grid_axes.as_ref().map_or(n, |g| &g.1), )), @@ -8737,7 +8754,7 @@ mod tests { let whole = get_coverage_url(&c2, &east_first, east_first.bbox.unwrap()); assert_eq!( whole, - "https://x.org/wcs?SERVICE=WCS&VERSION=2.0.1&REQUEST=GetCoverage&COVERAGEID=dem&FORMAT=image%2Ftiff&SUBSET=E(2590000,2610000)&SUBSET=N(1190000,1210000)&SCALESIZE=E(2048),N(2048)" + "https://x.org/wcs?SERVICE=WCS&VERSION=2.0.1&REQUEST=GetCoverage&COVERAGEID=dem&FORMAT=image%2Ftiff&SUBSETTINGCRS=http://www.opengis.net/def/crs/EPSG/0/2056&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056&SUBSET=E(2590000,2610000)&SUBSET=N(1190000,1210000)&SCALESIZE=E(2048),N(2048)" ); assert_eq!(get_coverage_url(&c2, &north_first, north_first.bbox.unwrap()), whole); // Part of it: the area's box in LV95, within the envelope. @@ -8749,7 +8766,25 @@ mod tests { }; let ((x0, x1), (y0, y1)) = (subset(&part, "E"), subset(&part, "N")); assert!(x0 > 2_590_000.0 && x1 < 2_610_000.0 && (y0, y1).1 == 1_210_000.0 && y0 > 1_190_000.0, "{part}"); - assert!(!part.contains("OUTPUTCRS"), "{part}"); + assert!(part.contains("&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056&"), "{part}"); + // The address says the system it asks in, for an answer that doesn't say its own. + assert_eq!(coverage_request_system(&part), Some(lv95)); + assert_eq!( + coverage_request_system(&part.replace( + "OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056", + "OUTPUTCRS=http%3A%2F%2Fwww.opengis.net%2Fdef%2Fcrs%2FEPSG%2F0%2F2056" + )), + Some(lv95) + ); + assert_eq!(coverage_request_system(&part.replace("EPSG/0/2056", "EPSG/0/4326")), None); + assert_eq!( + coverage_request_system( + "https://x.org/wcs?SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=dem&CRS=EPSG:2056&BBOX=1,2,3,4" + ), + Some(lv95) + ); + assert_eq!(coverage_request_system("https://x.org/wcs?SERVICE=WCS&REQUEST=GetCoverage&CRS=EPSG:2056&RESPONSE_CRS=EPSG:4326"), None); + assert_eq!(coverage_request_system("https://x.org/wms?SERVICE=WMS&REQUEST=GetMap&CRS=EPSG:2056"), None); // EPSG's axis order decides, not the labels' names: LV03 names its east axis Y, and // Gauss-Krüger zone 3 its north axis X. let lv03 = @@ -8792,7 +8827,11 @@ mod tests { assert_eq!(ji.native.unwrap().grid_axes, Some(("j".into(), "i".into()))); let unmatched = parse_describe(&c2, gridded("i j", "10 100 -10").as_bytes()).unwrap(); - assert!(get_coverage_url(&c2, &unmatched, unmatched.bbox.unwrap()).contains("SCALESIZE=E(2048),N(2048)")); + // Offsets that don't say: still the grid's labels (scaling must name grid axes), in its + // own order. + assert!(get_coverage_url(&c2, &unmatched, unmatched.bbox.unwrap()).contains("SCALESIZE=i(2048),j(2048)")); + let no_offsets = parse_describe(&c2, gridded("i j", "").as_bytes()).unwrap(); + assert_eq!(no_offsets.native.unwrap().grid_axes, Some(("i".into(), "j".into()))); // North first (Gauss-Krüger zone 3, `N E`): the grid's axes follow the file's order, then // turn with the system's. let gk = desc("http://www.opengis.net/def/crs/EPSG/0/31467", "N E", "5420000 3480000", "5440000 3500000").replace( diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 57235c1bca..91b84784e8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,10 +51,10 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error), "coverageCrs"?: "EPSG: (with coverage: service.coverage's \"crs\", the system it was asked in, for an answer that doesn't say its own)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands)", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) - .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in ("crs"), for an answer that doesn't say its own), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), + .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), @@ -5331,7 +5331,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let left_out = parts_left_out(url, &bytes, p); let cut = url_name_cut("Add Data From URL", url, p, &bytes); // A WCS coverage's own system it was asked for in, for an answer that doesn't say it. - let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(p) } else { None }; + let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(p, url) } else { None }; let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), None, asked).map_err(named)?; if let Some(n) = left_out { s.notify(n, false); @@ -6799,7 +6799,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let drawn = s.landed_pages.iter().position(|(d, _)| *d == id).map(|i| s.landed_pages.remove(i).1); #[cfg(target_arch = "wasm32")] let drawn = None; - let asked = if coverage { super::raster::coverage_system(p) } else { None }; + let asked = if coverage { super::raster::coverage_system(p, &url) } else { None }; let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn, asked)?; if let Some(n) = left_out { s.notify(n, false); diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 39aeb43d3a..21cee18f32 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -741,19 +741,23 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { add_named_bytes(s, p, name, bytes, b(p, "zoom")) } +/// The system a WCS coverage was asked for in, for an answer that doesn't say its own: +/// `"coverageCrs"` (`service.coverage`'s, `EPSG:`), else the one its GetCoverage address +/// `url` names ([`coverage_request_system`](rustgis_data::ogc::coverage_request_system)). +pub(crate) fn coverage_system(p: &Value, url: &str) -> Option { + // Only `EPSG:`: `Crs::parse` takes WKT and PROJ text too, and keeps a system for them. + let given = ps(p, "coverageCrs") + .and_then(|c| c.strip_prefix("EPSG:")?.parse::().ok()) + .and_then(rustgis_data::raster::Crs::from_epsg) + .filter(|c| !c.is_geographic()); + given.or_else(|| rustgis_data::ogc::coverage_request_system(url)) +} + /// Adds a file's contents (an upload, a download) as its name's extension says. A PDF's page is /// drawn here, on the caller's thread, unless it was drawn already ([`add_named_bytes_read`]): the /// desktop app's downloads land with theirs drawn off the frame ([`download_page`]) and its file /// drops are read by path on the read queue, so a caller here is the command line, Python or a /// script, with no window to hold. -/// The system a WCS coverage was asked for in (`"coverageCrs"`, internal: the GetCoverage -/// request's, from `service.coverage`), for an answer that doesn't say its own. -pub(crate) fn coverage_system(p: &Value) -> Option { - // Only `EPSG:`: `Crs::parse` takes WKT and PROJ text too, and keeps a system for them. - let code: u32 = ps(p, "coverageCrs")?.strip_prefix("EPSG:")?.parse().ok()?; - rustgis_data::raster::Crs::from_epsg(code).filter(|c| !c.is_geographic()) -} - pub(crate) fn add_named_bytes(s: &mut Session, p: &Value, name: String, bytes: Vec, zoom: Option) -> CmdResult { add_named_bytes_read(s, p, name, bytes, zoom, None, None) } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 98ee770f6c..0624097137 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -38,7 +38,7 @@ pub fn commands() -> Vec { r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "where"?: "an ArcGIS feature layer's SQL where clause (1=1 when absent); combined with bbox and kept by every page; rejected clauses give an error", "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login"}"#, ), C::new("service.coverage", "WCS Coverage Request", "Home › Add", coverage).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it), its area in longitude/latitude, and "crs": the coverage's own system when it is asked in it (layer.addUrl's "coverageCrs", for an answer that doesn't say its system)"#, + r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it), its area in longitude/latitude, and "coverageCrs": the coverage's own system when it is asked in it (as layer.addUrl takes it, for an answer that doesn't say its system)"#, ), C::new("catalog.search", "Search Catalogue", "Home › Add", catalog_search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default), "start"?: "the first record's position (a page's next)", "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them)"#, @@ -1811,7 +1811,7 @@ fn coverage(s: &mut Session, p: &Value) -> CmdResult { // The system the request asks the coverage in, when its own: given to the add as // `coverageCrs`, for an answer that doesn't say it. if let Some(crs) = asked { - out["crs"] = json!(crs.code()); + out["coverageCrs"] = json!(crs.code()); } if anonymous { out["anonymous"] = json!(true); diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index 7600fcfb2a..d34ac4af3d 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -193,7 +193,7 @@ fn a_wcs_coverage_is_asked_for_in_its_own_system() { let c = s.run("service.coverage", &p).unwrap(); let get = c["url"].as_str().unwrap(); assert!( - get.contains("&SUBSET=E(2600000,2600100)&SUBSET=N(1200000,1200100)&SCALESIZE=E(2048),N(2048)") && !get.contains("CRS="), + get.contains("&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056&SUBSET=E(2600000,2600100)&SUBSET=N(1200000,1200100)&SCALESIZE=E(2048),N(2048)"), "{get}" ); let added = s.run("service.add", &p).unwrap(); @@ -260,7 +260,7 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { let p = json!({"url": url, "layer": "dem", "text": caps, "describe": describe, "bbox": "full"}); let mut s = Session::new(Project::default()); let c = s.run("service.coverage", &p).unwrap(); - assert_eq!(c["crs"], "EPSG:2056", "{c}"); + assert_eq!(c["coverageCrs"], "EPSG:2056", "{c}"); let crs_of = |s: &Session, id: &serde_json::Value| { s.map().layer(id.as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.as_ref().unwrap().crs }; @@ -273,17 +273,27 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { let added = s.run("layer.addDownload", &json!({"id": 7, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); assert_eq!(crs_of(&s, &added["layer"]), lv95); - // Without the system asked for (or with one that isn't an EPSG code of a projected system), - // its metres can't be placed: refused, as before. + // The address says the system too: without coverageCrs, as a script adds it. + s.downloaded.push((13, tiff.clone())); + let added = s.run("layer.addDownload", &json!({"id": 13, "url": get, "name": "Terrain", "coverage": true})).unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + // An address that doesn't say it, without the system (or with one that isn't an EPSG code of + // a projected system): its metres can't be placed, refused as before. + let unsaid = + get.replace("&SUBSETTINGCRS=http://www.opengis.net/def/crs/EPSG/0/2056&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/2056", ""); + assert_ne!(unsaid, get); for (id, crs) in [(8, None), (9, Some("EPSG:4326")), (10, Some("2056")), (11, Some("EPSG:x")), (12, Some("+proj=somerc"))] { s.downloaded.push((id, tiff.clone())); - let mut q = json!({"id": id, "url": get, "name": "Terrain", "coverage": true}); + let mut q = json!({"id": id, "url": unsaid, "name": "Terrain", "coverage": true}); if let Some(c) = crs { q["coverageCrs"] = json!(c); } assert!(s.run("layer.addDownload", &q).is_err(), "{crs:?}"); } - // Added by address, as the command line adds service.coverage's address. - let added = s.run("layer.addUrl", &json!({"url": get, "name": "By address", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); + // Added by address, as the command line adds service.coverage's address: the address says + // the system, or coverageCrs does. + let added = s.run("layer.addUrl", &json!({"url": get, "name": "By address", "coverage": true})).unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + let added = s.run("layer.addUrl", &json!({"url": unsaid, "name": "Given", "coverage": true, "coverageCrs": "EPSG:2056"})).unwrap(); assert_eq!(crs_of(&s, &added["layer"]), lv95); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 81349039ea..409c667520 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -6582,7 +6582,7 @@ impl RustGisApp { let get = c.get("url").and_then(Value::as_str).unwrap_or("").to_string(); let mut p = json!({"url": get, "name": title, "coverage": true}); // The system it was asked in, for an answer that doesn't say it. - if let Some(crs) = c.get("crs").and_then(Value::as_str) { + if let Some(crs) = c.get("coverageCrs").and_then(Value::as_str) { p["coverageCrs"] = json!(crs); } // Its service's document came from the internet: so does the coverage. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 7b489f23fe..74aa01edac 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -398,9 +398,11 @@ the system's axes does, as `X` and `Y` mean either), or WCS 1.0's native CRS wit the spatial domain in it. Its longitude/latitude bounds then come from that envelope, so `"bbox": "full"` works for it too. Otherwise (a geographic system, or one RustGIS doesn't read) the server reprojects it to EPSG:4326 (WCS 2.0 through its CRS extension); one that can't answers -with an error, which is shown. A GeoTIFF answer that doesn't name its system is read in the -system it was asked for in, when its coordinates aren't degrees, with a notice; otherwise as -longitude/latitude when they are, with a notice, and refused when they aren't. +with an error, which is shown. The request names the system it asks in (WCS 2.0's `OUTPUTCRS`, +WCS 1.0's `CRS`). A GeoTIFF answer that doesn't name its system is read in that one, with a +notice, unless its coordinates are degrees or it declares a geographic model: then it is read as +longitude/latitude, with a notice. Without a system asked for, one whose coordinates aren't +degrees and that declares no geographic model is refused. A feature type whose own system (its default one) is a projected system RustGIS reads is asked for in it, as `EPSG:`, and the layer is held in it, without a conversion by the server or From cde1b53b716b5b0a1b11f7a7821047483fa9ef8c Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 11:02:06 +0100 Subject: [PATCH 06/11] Review fixes: grid axes paired by name, offsets, then columns; the system named by the code written (#2032 C2f-3c) --- crates/data/src/ogc.rs | 66 +++++++++++++++++-------- crates/engine/src/tests/services_own.rs | 11 +++++ 2 files changed, 57 insertions(+), 20 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 22dc2d45b6..6c1455d0bc 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -1962,8 +1962,8 @@ pub struct CoverageSystem { pub envelope: [f64; 4], /// WCS 2.0's axis labels, the east-west one first. pub axes: Option<(String, String)>, - /// WCS 2.0's grid axis labels for the same axes (`i j`), which scaling names: matched to the - /// system's axes by their offset vectors; the system's labels when the grid doesn't say. + /// WCS 2.0's grid axis labels for the same axes (`i j`), east-west first, which scaling names + /// ([`grid_labels`]); `None` when the grid gives no two labels, and the system's are used. pub grid_axes: Option<(String, String)>, } @@ -2152,12 +2152,8 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result // axes decides, and the names only when that isn't known. let north_first = north_first_labels(&a, &b, false).or_else(|| epsg_north_first(crs)).or_else(|| north_first_labels(&a, &b, true))?; - let grid = grid_labels(&root); - let (envelope, axes, grid_axes) = if north_first { - ([lo1, lo0, hi1, hi0], (b, a), grid.map(|[g0, g1]| (g1, g0))) - } else { - ([lo0, lo1, hi0, hi1], (a, b), grid.map(|[g0, g1]| (g0, g1))) - }; + let grid_axes = grid_labels(&root, [&a, &b], north_first); + let (envelope, axes) = if north_first { ([lo1, lo0, hi1, hi0], (b, a)) } else { ([lo0, lo1, hi0, hi1], (a, b)) }; Some(CoverageSystem { crs, name: srs.clone(), envelope: ordered(envelope)?, axes: Some(axes), grid_axes }) }); let bbox = bbox.or_else(|| own.as_ref().and_then(|o| lonlat_of(o.envelope, o.crs))); @@ -2213,12 +2209,13 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result Ok(CoverageInfo { format: tiff_format(formats.iter().map(String::as_str)), axes: None, bbox, native: own }) } -/// A WCS 2.0 coverage's grid axis labels (its `RectifiedGrid`'s), in the order of the axes of -/// its system as the envelope gives them: each grid axis goes with the system axis its offset -/// vector runs along, else (offsets that don't say) in the grid's own order, as grids are most -/// often laid out. Scaling must name grid axes, so the grid's labels are used whenever it has -/// two. `None` when it doesn't. -fn grid_labels(root: &Node) -> Option<[String; 2]> { +/// A WCS 2.0 coverage's grid axis labels (its `RectifiedGrid`'s), the east-west one first, for +/// the system axes the envelope labels `env` name in its order (`north_first` when its first is +/// the north one). A grid axis goes with the system axis of the same name (rasdaman repeats +/// them), else the one its offset vector runs along, else the grid's first axis is the east one +/// (its columns, as GeoServer's `i`). Scaling must name grid axes, so the grid's labels are used +/// whenever it has two; `None` when it doesn't. +fn grid_labels(root: &Node, env: [&str; 2], north_first: bool) -> Option<(String, String)> { let grid = root.descendants().find(|n| n.is_element() && local(n) == "RectifiedGrid")?; let text = child_text(&grid, "axisLabels").or_else(|| grid.attribute("axisLabels").map(str::to_string))?; let labels: Vec<&str> = text.split_whitespace().collect(); @@ -2233,11 +2230,20 @@ fn grid_labels(root: &Node) -> Option<[String; 2]> { let (x, y) = (c.first()?.abs(), c.get(1)?.abs()); (x != y).then_some(usize::from(y > x)) }; - let offsets: Option> = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect(); - match offsets.as_deref() { - Some([1, 0]) => Some([l1.to_string(), l0.to_string()]), - _ => Some([l0.to_string(), l1.to_string()]), - } + // The grid's labels in the envelope's axis order. + let in_order = if [l0, l1] == env || [l1, l0] == env { + if [l0, l1] == env { [l0, l1] } else { [l1, l0] } + } else { + let offsets: Option> = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect(); + match offsets.as_deref() { + Some([0, 1]) => [l0, l1], + Some([1, 0]) => [l1, l0], + // Unknown: the grid's first axis runs east-west. + _ => return Some((l0.to_string(), l1.to_string())), + } + }; + let [first, second] = in_order; + Some(if north_first { (second.to_string(), first.to_string()) } else { (first.to_string(), second.to_string()) }) } /// The projected system a WCS GetCoverage address asks its coverage in, when the address says @@ -2363,7 +2369,11 @@ pub fn get_coverage(c: &Coverage, info: &CoverageInfo, area: [f64; 4]) -> (Strin c.version, encode(&c.id), encode(&info.format), - crs = format!("http://www.opengis.net/def/crs/EPSG/0/{}", own.crs.epsg()), + // The code as the description writes it (a server lists its aliases, as 900913). + crs = format!( + "http://www.opengis.net/def/crs/EPSG/0/{}", + projected_system(&own.name).map_or(u32::from(own.crs.epsg()), |(n, _)| n) + ), ge = own.grid_axes.as_ref().map_or(e, |g| &g.0), gn = own.grid_axes.as_ref().map_or(n, |g| &g.1), )), @@ -8832,6 +8842,10 @@ mod tests { assert!(get_coverage_url(&c2, &unmatched, unmatched.bbox.unwrap()).contains("SCALESIZE=i(2048),j(2048)")); let no_offsets = parse_describe(&c2, gridded("i j", "").as_bytes()).unwrap(); assert_eq!(no_offsets.native.unwrap().grid_axes, Some(("i".into(), "j".into()))); + // Grid labels repeating the envelope's pair by name. + let named = + parse_describe(&c2, gridded("N E", "10 00 -10").as_bytes()).unwrap(); + assert_eq!(named.native.unwrap().grid_axes, Some(("E".into(), "N".into()))); // North first (Gauss-Krüger zone 3, `N E`): the grid's axes follow the file's order, then // turn with the system's. let gk = desc("http://www.opengis.net/def/crs/EPSG/0/31467", "N E", "5420000 3480000", "5440000 3500000").replace( @@ -8841,6 +8855,18 @@ mod tests { let gk = parse_describe(&c2, gk.as_bytes()).unwrap(); let get = get_coverage_url(&c2, &gk, gk.bbox.unwrap()); assert!(get.contains("&SUBSET=E(3480000,3500000)&SUBSET=N(5420000,5440000)&SCALESIZE=i(2048),j(2048)"), "{get}"); + // Without offsets, the grid's first axis is its columns, east-west, north first or not. + let gk = desc("http://www.opengis.net/def/crs/EPSG/0/31467", "N E", "5420000 3480000", "5440000 3500000") + .replace("", "i j"); + let gk = parse_describe(&c2, gk.as_bytes()).unwrap(); + assert_eq!(gk.native.unwrap().grid_axes, Some(("i".into(), "j".into()))); + // The system named by the code the description writes, an alias included. + let alias = + parse_describe(&c2, desc("http://www.opengis.net/def/crs/EPSG/0/900913", "x y", "800000 5900000", "850000 5950000").as_bytes()) + .unwrap(); + assert_eq!(alias.native.as_ref().map(|o| o.crs), Some(crate::raster::Crs::WebMercator)); + let get = get_coverage_url(&c2, &alias, alias.bbox.unwrap()); + assert!(get.contains("&OUTPUTCRS=http://www.opengis.net/def/crs/EPSG/0/900913&"), "{get}"); // No axis names it knows: EPSG's order (LV95 is east first). let unnamed = parse_describe(&c2, desc(srs, "i j", "2590000 1190000", "2610000 1210000").as_bytes()).unwrap(); assert_eq!(unnamed.native.unwrap().axes, Some(("i".into(), "j".into()))); diff --git a/crates/engine/src/tests/services_own.rs b/crates/engine/src/tests/services_own.rs index d34ac4af3d..d74bf18acf 100644 --- a/crates/engine/src/tests/services_own.rs +++ b/crates/engine/src/tests/services_own.rs @@ -290,6 +290,17 @@ fn a_coverage_answer_without_its_system_is_read_in_the_one_asked_for() { } assert!(s.run("layer.addDownload", &q).is_err(), "{crs:?}"); } + // A coverageCrs that isn't usable leaves it to the address; a usable one comes first. + s.downloaded.push((14, tiff.clone())); + let added = s + .run("layer.addDownload", &json!({"id": 14, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:4326"})) + .unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), lv95); + s.downloaded.push((15, tiff.clone())); + let added = s + .run("layer.addDownload", &json!({"id": 15, "url": get, "name": "Terrain", "coverage": true, "coverageCrs": "EPSG:21781"})) + .unwrap(); + assert_eq!(crs_of(&s, &added["layer"]), Crs::from_epsg(21781).unwrap()); // Added by address, as the command line adds service.coverage's address: the address says // the system, or coverageCrs does. let added = s.run("layer.addUrl", &json!({"url": get, "name": "By address", "coverage": true})).unwrap(); From 49ff4d5e910de7a1e3abec8049a2598a78325d24 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 11:59:57 +0100 Subject: [PATCH 07/11] Review fixes: no bounds across the antimeridian, WCS 1.0 native system only when requestable, offsets before names for grid axes (#2032 C2f-3c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A projected coverage whose envelope edge crosses ±180° (a jump of more than half the globe between neighbouring samples) gets no longitude/latitude bounds, so the view is asked for unclipped as before; world-wide ones keep theirs. A WCS 1.0 native CRS is asked for only when requestResponseCRSs (or both requestCRSs and responseCRSs) lists it, or there is no list. A grid axis is paired with an envelope axis by its offset vector first, then by name, then as columns. --- crates/data/src/ogc.rs | 116 ++++++++++++++++++++++++++------ docs/user-guide/data-formats.md | 6 +- 2 files changed, 98 insertions(+), 24 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index 6c1455d0bc..bd7afa4f1e 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -2191,6 +2191,22 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result .and_then(|t| t.split_whitespace().next().map(str::to_string)); // The native system's envelope (MapServer writes one in EPSG:4326 first); without a // native system named, the first envelope in a projected one. + // A system the server takes in requests and answers: listed among `requestResponseCRSs`, + // or both `requestCRSs` and `responseCRSs`, when it lists any. + // (Each list's codes as written, looked through until one names the system.) + let listed = |kind: &str| -> Option> { + let lists: Vec = + root.descendants().filter(|n| n.is_element() && local(n) == kind).take(4096).map(|n| text_of(&n)).collect(); + (!lists.is_empty()).then(|| lists.iter().flat_map(|t| t.split_whitespace().take(4096)).map(str::to_string).collect()) + }; + let (both, request, response) = (listed("requestResponseCRSs"), listed("requestCRSs"), listed("responseCRSs")); + let names = |list: &Option>, crs: crate::raster::Crs| { + list.as_ref().is_some_and(|l| l.iter().any(|c| projected_system(c).is_some_and(|(_, found)| found == crs))) + }; + let takes = |crs: crate::raster::Crs| match (&both, &request, &response) { + (None, None, None) => true, + _ => names(&both, crs) || (names(&request, crs) && names(&response, crs)), + }; let (env, (n, crs)) = match native { Some(name) => { let (n, crs) = projected_system(&name)?; @@ -2198,6 +2214,9 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result } None => envelopes.into_iter().find_map(|e| projected_system(&srs_of(&e)).map(|found| (e, found)))?, }; + if !takes(crs) { + return None; + } let name = format!("EPSG:{n}"); let pos: Vec = children(&env, "pos") .flat_map(|p| text_of(&p).split_whitespace().filter_map(|t| t.parse().ok()).collect::>()) @@ -2211,9 +2230,9 @@ pub fn parse_describe(c: &Coverage, body: &[u8]) -> Result /// A WCS 2.0 coverage's grid axis labels (its `RectifiedGrid`'s), the east-west one first, for /// the system axes the envelope labels `env` name in its order (`north_first` when its first is -/// the north one). A grid axis goes with the system axis of the same name (rasdaman repeats -/// them), else the one its offset vector runs along, else the grid's first axis is the east one -/// (its columns, as GeoServer's `i`). Scaling must name grid axes, so the grid's labels are used +/// the north one). A grid axis goes with the system axis its offset vector runs along, else the +/// one of the same name (rasdaman repeats them), else the grid's first axis is the east one (its +/// columns, as GeoServer's `i`). Scaling must name grid axes, so the grid's labels are used /// whenever it has two; `None` when it doesn't. fn grid_labels(root: &Node, env: [&str; 2], north_first: bool) -> Option<(String, String)> { let grid = root.descendants().find(|n| n.is_element() && local(n) == "RectifiedGrid")?; @@ -2230,17 +2249,15 @@ fn grid_labels(root: &Node, env: [&str; 2], north_first: bool) -> Option<(String let (x, y) = (c.first()?.abs(), c.get(1)?.abs()); (x != y).then_some(usize::from(y > x)) }; - // The grid's labels in the envelope's axis order. - let in_order = if [l0, l1] == env || [l1, l0] == env { - if [l0, l1] == env { [l0, l1] } else { [l1, l0] } - } else { - let offsets: Option> = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect(); - match offsets.as_deref() { - Some([0, 1]) => [l0, l1], - Some([1, 0]) => [l1, l0], - // Unknown: the grid's first axis runs east-west. - _ => return Some((l0.to_string(), l1.to_string())), - } + // The grid's labels in the envelope's axis order: by the direction each offset vector runs + // (what places the grid), else by name, else the grid's first axis runs east-west. + let offsets: Option> = children(&grid, "offsetVector").take(3).map(|v| along(&v)).collect(); + let in_order = match offsets.as_deref() { + Some([0, 1]) => [l0, l1], + Some([1, 0]) => [l1, l0], + _ if [l0, l1] == env => [l0, l1], + _ if [l1, l0] == env => [l1, l0], + _ => return Some((l0.to_string(), l1.to_string())), }; let [first, second] = in_order; Some(if north_first { (second.to_string(), first.to_string()) } else { (first.to_string(), second.to_string()) }) @@ -2293,23 +2310,37 @@ fn lonlat_of(b: [f64; 4], crs: crate::raster::Crs) -> Option<[f64; 4]> { let [x0, y0, x1, y1] = b; let mut out = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; const STEPS: usize = 16; - for i in 0..=STEPS { - let f = i as f64 / STEPS as f64; - let (x, y) = (x0 + (x1 - x0) * f, y0 + (y1 - y0) * f); - for (px, py) in [(x, y0), (x, y1), (x0, y), (x1, y)] { + // Along each edge in turn, so a jump of more than half the globe between neighbouring places + // says the edge crosses the antimeridian (a world-wide one changes by a sixteenth of it). + let mut crosses = false; + for edge in 0..4 { + let mut last: Option = None; + for i in 0..=STEPS { + let f = i as f64 / STEPS as f64; + let (x, y) = (x0 + (x1 - x0) * f, y0 + (y1 - y0) * f); + let (px, py) = [(x, y0), (x, y1), (x0, y), (x1, y)][edge]; let c = t.to_lonlat(rustgis_geom::Coord::new(px, py)).filter(|c| c.x.is_finite() && c.y.is_finite())?; + crosses |= last.is_some_and(|l| (c.x - l).abs() > 180.0); + last = Some(c.x); out = [out[0].min(c.x), out[1].min(c.y), out[2].max(c.x), out[3].max(c.y)]; } } // A pole within it (a polar coverage): its edges miss it, so the box reaches it, at every // longitude. + let mut polar = false; for lat in [90.0, -90.0] { if t.from_lonlat(rustgis_geom::Coord::new(0.0, lat)) .is_some_and(|p| p.x.is_finite() && p.y.is_finite() && p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1) { out = [-180.0, out[1].min(lat), 180.0, out[3].max(lat)]; + polar = true; } } + // An edge across the antimeridian, without a pole within: a west-east box can't hold it, so + // its bounds aren't known (the view is asked for as it is, unclipped). + if !polar && crosses { + return None; + } lonlat_box(out[0], out[1], out[2], out[3]) } @@ -8842,10 +8873,39 @@ mod tests { assert!(get_coverage_url(&c2, &unmatched, unmatched.bbox.unwrap()).contains("SCALESIZE=i(2048),j(2048)")); let no_offsets = parse_describe(&c2, gridded("i j", "").as_bytes()).unwrap(); assert_eq!(no_offsets.native.unwrap().grid_axes, Some(("i".into(), "j".into()))); - // Grid labels repeating the envelope's pair by name. - let named = - parse_describe(&c2, gridded("N E", "10 00 -10").as_bytes()).unwrap(); - assert_eq!(named.native.unwrap().grid_axes, Some(("E".into(), "N".into()))); + // The offsets say where a grid axis runs, whatever its name: a grid whose axis `N` runs + // east-west (offsets 10 0, then 0 -10) scales it by the width, on a coverage twice as wide + // as it is high. + let wide = |labels: &str, offsets: &str| { + desc(srs, "E N", "2590000 1190000", "2610000 1200000").replace( + "", + &format!( + r#"{labels}{offsets}"# + ), + ) + }; + let crossed = + parse_describe(&c2, wide("N E", "10 00 -10").as_bytes()).unwrap(); + let get = get_coverage_url(&c2, &crossed, crossed.bbox.unwrap()); + assert!(get.contains("&SCALESIZE=N(2048),E(1024)"), "{get}"); + // Without offsets, grid labels repeating the envelope's pair by name. + let named = parse_describe(&c2, wide("N E", "").as_bytes()).unwrap(); + let get = get_coverage_url(&c2, &named, named.bbox.unwrap()); + assert!(get.contains("&SCALESIZE=E(2048),N(1024)"), "{get}"); + // A coverage across the antimeridian (UTM zone 60, about 174° to 182° east): a west-east box + // can't hold its bounds, so they aren't known, and the view is asked for unclipped. + let utm60 = + parse_describe(&c2, desc("http://www.opengis.net/def/crs/EPSG/0/32660", "E N", "300000 5000000", "900000 5100000").as_bytes()) + .unwrap(); + assert!(utm60.native.is_some()); + assert_eq!(utm60.bbox, None); + // A world-wide one keeps its bounds: Web Mercator as WCS 2.0 names it, and an equal-area one. + for (code, lo, hi) in [("3857", "-20037508 -20037508", "20037508 20037508"), ("6933", "-17367530 -7314540", "17367530 7314540")] { + let world = + parse_describe(&c2, desc(&format!("http://www.opengis.net/def/crs/EPSG/0/{code}"), "x y", lo, hi).as_bytes()).unwrap(); + let [w, _, e, _] = world.bbox.unwrap_or_else(|| panic!("{code}: no bounds")); + assert!(w <= -179.9 && e >= 179.9, "{code}: {:?}", world.bbox); + } // North first (Gauss-Krüger zone 3, `N E`): the grid's axes follow the file's order, then // turn with the system's. let gk = desc("http://www.opengis.net/def/crs/EPSG/0/31467", "N E", "5420000 3480000", "5440000 3500000").replace( @@ -8909,6 +8969,18 @@ mod tests { // Its envelope in another system than its native one: EPSG:4326 as before. let other = parse_describe(&c1, v1.replace(r#"srsName="EPSG:2056""#, r#"srsName="EPSG:21781""#).as_bytes()).unwrap(); assert!(other.native.is_none()); + // Its native system asked for only when the server takes it in requests and answers: listed + // in requestResponseCRSs, or in both requestCRSs and responseCRSs, or with no list at all. + let lists = "EPSG:2056 EPSG:4326"; + for (with, native) in [ + ("EPSG:4326", false), + ("EPSG:2056EPSG:2056", true), + ("EPSG:2056EPSG:4326", false), + ("", true), + ] { + let info = parse_describe(&c1, v1.replace(lists, with).as_bytes()).unwrap(); + assert_eq!(info.native.is_some(), native, "{with}"); + } } #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 74aa01edac..d2aac138ef 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -395,8 +395,10 @@ system RustGIS reads is asked for in it: the area's box there, within the covera and no conversion by the server, so it is resampled once, by the map. Its own system is WCS 2.0's envelope's, whose axis labels are needed (`E N` or `N E` say the order; otherwise EPSG's order of the system's axes does, as `X` and `Y` mean either), or WCS 1.0's native CRS with an envelope of -the spatial domain in it. Its longitude/latitude bounds then come from that envelope, so -`"bbox": "full"` works for it too. Otherwise (a geographic system, or one RustGIS doesn't read) +the spatial domain in it, when the server lists it among the systems it takes in requests and +answers (or lists none). Its longitude/latitude bounds then come from that envelope, so +`"bbox": "full"` works for it too; a coverage across the antimeridian has none, and the view is +asked for unclipped. Otherwise (a geographic system, or one RustGIS doesn't read) the server reprojects it to EPSG:4326 (WCS 2.0 through its CRS extension); one that can't answers with an error, which is shown. The request names the system it asks in (WCS 2.0's `OUTPUTCRS`, WCS 1.0's `CRS`). A GeoTIFF answer that doesn't name its system is read in that one, with a From bb05153f051a65daa394eb1e4efc82e6733b24f9 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 13:11:31 +0100 Subject: [PATCH 08/11] Streamed reads in the source's own system: a map in it reads its window in map units, each feature's own box tested there (#2032 C2f-4a) --- crates/data/src/export/tests.rs | 5 +- crates/data/src/source/arcgis/tests.rs | 51 ++-- crates/data/src/source/duckdb.rs | 14 +- crates/data/src/source/fgb.rs | 20 +- crates/data/src/source/gdal.rs | 18 +- crates/data/src/source/geojson.rs | 20 +- crates/data/src/source/gpkg.rs | 8 +- crates/data/src/source/gpkg/edit.rs | 2 +- crates/data/src/source/gpkg_mem.rs | 12 +- crates/data/src/source/mod.rs | 50 +++- crates/data/src/source/mysql.rs | 10 +- crates/data/src/source/own_box_tests.rs | 140 +++++++++++ crates/data/src/source/parquet.rs | 12 +- crates/data/src/source/postgis.rs | 17 +- crates/data/src/source/shp.rs | 12 +- crates/data/src/source/shp/cache/tests.rs | 3 +- crates/data/src/source/shp/tests.rs | 16 +- crates/data/src/source/sqlserver.rs | 16 +- crates/data/src/source/tests.rs | 85 +++---- .../integration/extent_query_properties.rs | 2 +- .../tests/integration/shapefile_encoding.rs | 2 +- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/layout.rs | 7 +- crates/engine/src/tests.rs | 2 +- .../integration/portable_projects/reload.rs | 4 +- crates/map/src/lib.rs | 61 ++++- crates/map/src/source.rs | 141 +++++++++-- crates/map/src/source/own_tests.rs | 230 ++++++++++++++++++ crates/map/src/source/window.rs | 7 +- crates/render/src/layout.rs | 3 +- crates/render/src/lib.rs | 11 +- crates/tiles/src/embeddings.rs | 2 +- docs/user-guide/data.md | 6 +- 33 files changed, 789 insertions(+), 202 deletions(-) create mode 100644 crates/data/src/source/own_box_tests.rs create mode 100644 crates/map/src/source/own_tests.rs diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 5e44f7f763..f6d515b490 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -481,8 +481,9 @@ fn a_streamed_export_into_an_existing_geopackage_starts_again_inside_its_transac assert_eq!((e.written, table), (20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![] }))); let whole = d.join("whole.gpkg"); crate::io::write_path(&both, &whole).unwrap(); - let read = - |p: &Path, t: &str| crate::source::open_path(p, Some(t)).unwrap().read(&Request { extent: None, limit: 100 }).unwrap().features; + let read = |p: &Path, t: &str| { + crate::source::open_path(p, Some(t)).unwrap().read(&Request { extent: None, limit: 100, own: None }).unwrap().features + }; assert_eq!(read(&county, "both"), read(&whole, "both")); assert_eq!(read(&county, "parcels").len(), 1); let c = rusqlite::Connection::open(&county).unwrap(); diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index 06b014f609..88c499d8d9 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -246,7 +246,7 @@ fn a_view_is_read_whole_over_several_pages_with_object_ids_as_ids() { let src = open_blocking(&query).unwrap(); assert_eq!((src.info.format, src.info.count, src.info.crs.as_str()), (FORMAT, Some(FEATURES), "EPSG:4326")); assert_eq!(src.info.extent, Extent::new(-100.0, 40.0, -99.05, 40.95)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); let want: Vec = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect(); assert_eq!(ids(&b), want); assert!(b.complete && b.matched == 16); @@ -256,7 +256,7 @@ fn a_view_is_read_whole_over_several_pages_with_object_ids_as_ids() { fn a_view_holding_more_than_the_limit_reads_every_kth_feature_spread_over_it() { let (query, _) = service("live-sample.test", 30, true, None); let src = open_blocking(&query).unwrap(); - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50, own: None }).unwrap(); assert!(!b.complete && b.matched == FEATURES); // 400 over 50 is 8: every 8th object id, across the whole grid. assert!(b.features.len() == 50 && b.features.iter().all(|f| f.id % 8 == 0), "{:?}", ids(&b)); @@ -271,7 +271,7 @@ fn a_view_holding_more_than_the_limit_reads_every_kth_feature_spread_over_it() { fn a_view_read_again_asks_the_service_nothing() { let (query, asked) = service("live-again.test", 5, true, None); let src: Arc = Arc::new(open_blocking(&query).unwrap()); - let req = Request { extent: Some(small_view()), limit: 1000 }; + let req = Request { extent: Some(small_view()), limit: 1000, own: None }; let first = super::super::read_blocking(&src, &req).unwrap(); let before = asked.count.load(Ordering::Relaxed); let again = super::super::read_blocking(&src, &req).unwrap(); @@ -284,10 +284,10 @@ fn a_service_that_cant_sample_gives_its_first_features_and_says_so() { let (query, _) = service("live-nosql.test", 30, false, None); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.iter().any(|n| n.contains("standardized SQL")), "{:?}", src.info.notes); - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50, own: None }).unwrap(); assert!(!b.complete && b.matched == FEATURES && !b.features.is_empty() && b.features.len() <= 50); // A view within the limit is read whole, whatever its cells hold. - let all = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let all = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(all.complete && all.features.len() == FEATURES as usize, "{}", all.features.len()); } @@ -360,7 +360,7 @@ fn views_anywhere_never_panic_and_ask_for_a_few_cells() { ]; for v in views { let before = asked.count.load(Ordering::Relaxed); - let b = super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100 }); + let b = super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100, own: None }); assert!(b.is_ok(), "{v:?}: {b:?}"); assert!(asked.count.load(Ordering::Relaxed) - before <= 64, "{v:?}"); } @@ -368,12 +368,13 @@ fn views_anywhere_never_panic_and_ask_for_a_few_cells() { assert!(cells(&v).len() <= 25, "{v:?}"); } // Outside the world: nothing, said to be all of it. - let outside = super::super::read_blocking(&src, &Request { extent: Some(Extent::new(200.0, 0.0, 210.0, 10.0)), limit: 100 }).unwrap(); + let outside = + super::super::read_blocking(&src, &Request { extent: Some(Extent::new(200.0, 0.0, 210.0, 10.0)), limit: 100, own: None }).unwrap(); assert!(outside.complete && outside.features.is_empty()); // No view at all: an error, never an empty answer, and nothing asked. let before = asked.count.load(Ordering::Relaxed); for v in [Extent::new(f64::NAN, 0.0, 1.0, 1.0), Extent::new(0.0, f64::INFINITY, 1.0, 1.0), Extent::new(5.0, 5.0, -5.0, -5.0)] { - assert!(super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100 }).is_err(), "{v:?}"); + assert!(super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100, own: None }).is_err(), "{v:?}"); let mut visit = |_: Vec| Ok(()); assert!(src.visit_chunks(Some(v), 4 << 10, &mut visit).is_err(), "{v:?}"); } @@ -386,12 +387,12 @@ fn what_pages_lose_is_said_by_each_read_and_none_when_nothing_is() { let (query, _) = service_with("live-z.test", Opts { z: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.info.zm_dropped && src.info.notes == vec![crate::zm_note(None)], "{:?}", src.info.notes); - assert!(read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap().notes.is_empty()); + assert!(read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap().notes.is_empty()); // Values each page loses: said by each read, a view's counted in its pages. let (query, _) = service_with("live-utf8.test", Opts { bad_text: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.is_empty(), "{:?}", src.info.notes); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!( b.notes.len() == 1 && b.notes[0].contains("UTF-8") && b.notes[0].ends_with("counted in the pages read for the view"), "{:?}", @@ -404,7 +405,7 @@ fn what_pages_lose_is_said_by_each_read_and_none_when_nothing_is() { let (query, _) = service("live-clean.test", 30, true, None); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.is_empty(), "{:?}", src.info.notes); - assert!(read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap().notes.is_empty()); + assert!(read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap().notes.is_empty()); } #[test] @@ -432,7 +433,7 @@ fn sampling_steps_are_powers_of_two() { fn a_query_without_geometry_still_reads_its_views() { let (query, _) = service("live-nogeometry.test", 30, true, None); let src = open_blocking(&format!("{query}&returnGeometry=false")).unwrap(); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.len() == 16 && b.features.iter().all(|f| f.geometry.is_some())); } @@ -441,7 +442,7 @@ fn empty_pages_naming_no_fields_are_read_as_empty() { let (query, _) = service_with("live-emptypages.test", Opts { empty_without_fields: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); // Every 256th: one feature (256) in all, so most cells' sampled pages are empty. - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 2 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 2, own: None }).unwrap(); assert_eq!(ids(&b), vec![256]); assert!(!b.complete); } @@ -450,8 +451,8 @@ fn empty_pages_naming_no_fields_are_read_as_empty() { fn a_budgeted_view_stays_within_its_bytes_as_it_is_read_and_spread_over_it() { let (query, _) = service("live-budget.test", 30, true, None); let src = open_blocking(&query).unwrap(); - let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }; - let all = read(&src, Request { extent: whole.extent, limit: 1000 }).unwrap(); + let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }; + let all = read(&src, Request { extent: whole.extent, limit: 1000, own: None }).unwrap(); let bytes = super::super::memory::features_bytes(&all.features) / 5; let shared: Arc = Arc::new(open_blocking(&query).unwrap()); // Fetched first, as the map's reads are, then read within the budget. @@ -476,7 +477,7 @@ fn a_layer_matching_nothing_opens_and_reads_empty() { let src = open_blocking(&query.replace("where=1%3D1", "where=1%3D0")).unwrap(); // Its geometry from the layer's description, as no feature says it. assert_eq!((src.info.count, src.info.geometry_type), (Some(0), crate::GeometryType::Point)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.is_empty() && b.matched == 0); let mut visited = 0; let all = src @@ -498,14 +499,14 @@ fn a_view_larger_than_the_answers_kept_is_read_in_part_without_running_out_of_ro let (query, _) = service_with(host, Opts { page: 30, padded: true, sql, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.page() < 30 && src.page() * 10_600 < remote::MAX_ANSWER as usize, "{}", src.page()); - let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }; + let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }; let b = read(&src, whole).unwrap(); assert!(!b.complete && b.matched == FEATURES && !b.features.is_empty() && b.features.len() < FEATURES as usize, "{host}"); assert_eq!(b.features.iter().map(|f| f.id).collect::>().len(), b.features.len()); // Read again, it asks for what it read before. assert_eq!(ids(&read(&src, whole).unwrap()), ids(&b), "{host}"); // A view whose answers fit (its cells hold a few of the large features) is read whole. - let fits = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let fits = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(fits.complete && fits.features.len() == 16, "{host}: {}", fits.features.len()); } } @@ -537,7 +538,7 @@ fn pages_whose_answers_are_too_large_are_asked_for_again_shorter() { assert_eq!(src.page(), 30); // The whole grid: cells of many features, whose pages of 30 are too large (read by a source // of its own, which shortens its own pages). - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(!b.features.is_empty()); let mut visited = Vec::new(); src.visit_chunks(None, 64 << 10, &mut |c| { @@ -594,7 +595,7 @@ fn counts_past_any_layer_never_overflow() { let src = open_blocking(&query).unwrap(); assert_eq!(src.info.count, Some(u64::MAX)); // An answer, read or refused, whatever it is: never a panic. - let _ = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }); + let _ = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }); let _ = src.visit_chunks(None, 4 << 10, &mut |_| Ok(())); } @@ -612,7 +613,7 @@ fn features_counted_but_not_sent_are_said_and_leave_the_read_incomplete() { assert!(!all.complete && visited == 390, "{visited}"); assert!(all.notes.iter().any(|n| n.contains("10 features more than it sent")), "{:?}", all.notes); // A view read whole, but for what the service didn't send. - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(!b.complete && b.features.len() == 390, "{}", b.features.len()); assert!(b.notes.iter().any(|n| n.contains("more than it sent")), "{:?}", b.notes); } @@ -636,7 +637,7 @@ fn a_layer_matching_nothing_may_answer_with_no_bytes() { let (query, _) = service_with("live-nobytes.test", Opts { empty_body: true, ..Opts::default() }); let src = open_blocking(&query.replace("where=1%3D1", "where=1%3D0")).unwrap(); assert_eq!(src.info.count, Some(0)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.is_empty()); } @@ -649,7 +650,7 @@ fn a_layer_is_read_in_its_own_system() { let src = open_blocking(&query).unwrap(); assert_eq!((src.coord_crs(), src.info.crs.as_str()), (crate::raster::Crs::WebMercator, "EPSG:3857")); let before = asked.count.load(Ordering::Relaxed); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); let want: Vec = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect(); assert_eq!(ids(&b), want); let pages: Vec = asked.since(before).into_iter().filter(|u| u.contains("resultOffset")).collect(); @@ -678,7 +679,7 @@ fn a_layer_is_read_in_its_own_system() { let (query, _) = service_with(host, opts); let src = open_blocking(&query).unwrap(); assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat, "{host}"); - assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap()), want, "{host}"); + assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap()), want, "{host}"); } // A code RustGIS doesn't read: longitude/latitude, as before. let description = r#"{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":30,"supportedQueryFormats":"PBF","geometryType":"esriGeometryPoint", @@ -686,7 +687,7 @@ fn a_layer_is_read_in_its_own_system() { let (query, asked) = service("unknown-system.test", 30, true, Some(description)); let src = open_blocking(&query).unwrap(); assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert_eq!(ids(&b), want); assert!(asked.since(0).iter().filter(|u| u.contains("resultOffset")).all(|u| u.contains("outSR=4326"))); } diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index 64084a4add..dc8e3b92c8 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -1672,7 +1672,7 @@ mod tests { let dropped = |f: Family| zm.parts.iter().find(|p| p.family == f).map(|p| (p.count, p.zm_dropped)); assert_eq!((dropped(Family::Points), dropped(Family::Lines)), (Some((3, 2)), Some((1, 1)))); let line_source = open(&lines.path); - let line_batch = line_source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let line_batch = line_source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(line_batch.features.len(), 1); assert_eq!(line_batch.features[0].geometry.as_ref().unwrap().kind(), crate::GeometryType::Polyline); assert_eq!(line_batch.features[0].geometry.as_ref().unwrap().extent(), rustgis_geom::Extent::new(0.0, 0.0, 1.0, 1.0)); @@ -1683,10 +1683,12 @@ mod tests { assert_eq!(info.fields.iter().map(|f| f.name.as_str()).collect::>(), vec!["id", "name", "day", "seen"]); assert_eq!(info.fields[2].ty, crate::FieldType::Date); assert_eq!(info.fields[3].ty, crate::FieldType::DateTime); - let b = pts.read(&crate::source::Request { extent: Some(rustgis_geom::Extent::new(10.5, 20.5, 12.0, 22.0)), limit: 10 }).unwrap(); + let b = pts + .read(&crate::source::Request { extent: Some(rustgis_geom::Extent::new(10.5, 20.5, 12.0, 22.0)), limit: 10, own: None }) + .unwrap(); assert_eq!(b.features.len(), 1, "the extent query reads the covering"); assert_eq!(b.features[0].geometry.as_ref().unwrap().extent(), rustgis_geom::Extent::new(11.0, 21.0, 11.0, 21.0)); - let all_points = pts.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let all_points = pts.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(all_points.features.len(), 2); assert!(all_points.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == crate::GeometryType::Point)); let days: Vec = all_points.features.iter().map(|f| f.attrs[2].to_string()).collect(); @@ -1697,7 +1699,7 @@ mod tests { let sql = "SELECT 1 AS id, DATE 'infinity' AS d, TIMESTAMP 'infinity' AS t, TIMESTAMP_S '-infinity' AS s, \ TIMESTAMP_MS 'infinity' AS ms, TIMESTAMPTZ 'infinity' AS tz, ST_Point(1, 2) AS geom"; let out = run_in(&cache, &Query { sql, ..Query::default() }, false).unwrap(); - let infinite = open(&out.parts[0].path).read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let infinite = open(&out.parts[0].path).read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(infinite.features.len(), 1); assert_eq!(infinite.unread_dates, [0, 1, 1, 1, 1, 1]); // A nanosecond timestamp is a timestamp, rounded to the microsecond and counted. @@ -1709,7 +1711,7 @@ mod tests { nanos.info().fields.iter().map(|f| f.ty).collect::>(), [crate::FieldType::Integer, crate::FieldType::DateTime, crate::FieldType::DateTime] ); - let batch = nanos.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = nanos.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert!(batch.unread_dates.is_empty()); assert_eq!(batch.rounded_dates, [0, 1]); assert_eq!(batch.features[0].attrs[1].to_string(), "2026-03-05T12:34:56.123457"); @@ -1723,7 +1725,7 @@ mod tests { // placed where it is in longitude/latitude… let first = |path: &Path| { let source = open(path); - let batch = source.read(&crate::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 1, own: None }).unwrap(); let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; (source.coord_crs(), c, source.info().extent) }; diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 1684fe934b..8a078203ee 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -354,7 +354,7 @@ impl FgbSource { /// counts features and checks Cancel between them. fn read_with(&self, open: &impl Fn() -> Result, req: &Request, scan: bool) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -398,12 +398,12 @@ impl FgbSource { if !late && !sample.wants() { continue; } - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(req) || (late && !sample.wants()) { + if !geometry.inside || (late && !sample.wants()) { continue; } let geometry = geometry.geometry; @@ -438,7 +438,7 @@ impl FgbSource { extent: Option, chunks: &mut super::chunk_memory::Chunker<'_>, ) -> Result { - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let reader = open_reader(open()?)?; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let indexed = native.filter(|_| self.info.indexed); @@ -464,12 +464,13 @@ impl FgbSource { crate::progress::step(1)?; n += 1; let id = numbers.as_ref().and_then(|v| v.get(usize::try_from(n - 1).unwrap_or(usize::MAX)).copied()).unwrap_or(n); - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = + f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, &req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(&req) { + if !geometry.inside { continue; } let geometry = geometry.geometry; @@ -682,7 +683,7 @@ impl FgbSource { /// spatial read scans every candidate within the budget, counting features and checking Cancel. fn read_remote(&self, f: &Arc, req: &Request) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -777,12 +778,13 @@ impl FgbSource { continue; } let id = hits.items.get(this).map(|(_, i)| i + 1).unwrap_or(this as u64 + 1); - let geometry = feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = + feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(req) || (late && !sample.wants()) { + if !geometry.inside || (late && !sample.wants()) { continue; } let geometry = geometry.geometry; diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index b6e956cff8..b3d7517082 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -631,12 +631,12 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques // A read failure is not an empty dataset. Never install a corrupt or partially readable // conversion as a successful replacement. let source = super::open_path(&tmp, None)?; - Ok::<_, DataError>(!source.read(&super::Request { extent: None, limit: 1 })?.features.is_empty()) + Ok::<_, DataError>(!source.read(&super::Request { extent: None, limit: 1, own: None })?.features.is_empty()) } else { Ok(tmp.exists() && super::open_path(&tmp, None) .ok() - .is_some_and(|s| s.read(&super::Request { extent: None, limit: 1 }).is_ok_and(|b| !b.features.is_empty()))) + .is_some_and(|s| s.read(&super::Request { extent: None, limit: 1, own: None }).is_ok_and(|b| !b.features.is_empty()))) } })?; // The entry is replaced in an order that never leaves it naming a missing file: the new state @@ -922,7 +922,7 @@ mod tests { }; let first = |path: &Path| { let source = super::super::open_path(path, None).unwrap(); - let batch = source.read(&super::super::Request { extent: None, limit: 1 }).unwrap(); + let batch = source.read(&super::super::Request { extent: None, limit: 1, own: None }).unwrap(); let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; (source.coord_crs(), c) }; @@ -1130,7 +1130,7 @@ mod tests { for (path, workspace) in [(&again[0].path, None), (&fresh.path, Some(fresh.workspace.clone()))] { let source = super::super::fgb::FgbSource::open_converted_path(path, "mixed", &kml, workspace).unwrap(); let captured = crate::provenance::Capture::start(); - source.read(&super::super::Request { extent: None, limit: 1 }).unwrap(); + source.read(&super::super::Request { extent: None, limit: 1, own: None }).unwrap(); source.visit_chunks(None, 1024, &mut |_| Ok(())).unwrap(); assert_eq!(captured.inputs().iter().map(|i| &i.path).collect::>(), vec![&kml.display().to_string()]); } @@ -1168,7 +1168,7 @@ mod tests { let (converted, notes) = convert_in(&dir.path().join("cache"), &path, None, None).unwrap(); assert_eq!(converted.len(), 1); let source = super::super::open_path(&converted[0].path, None).unwrap(); - let batch = source.read(&super::super::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&super::super::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 1); assert_eq!(batch.skipped, 0, "GDAL dropped the feature before RustGIS read it"); if lossy { @@ -1271,7 +1271,7 @@ mod tests { assert_eq!(fresh.notes.iter().any(|n| n.contains("Z or M coordinates on 1 source feature")), lossy); assert_eq!(fresh.zm_dropped, lossy); let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features[0].geometry.as_ref().unwrap().extent().center().x, if lossy { 2.0 } else { 8.0 }); } // A layer of points with Z, two of its three features with only XY: the one with Z is @@ -1308,7 +1308,7 @@ mod tests { assert!(fresh.notes.is_empty(), "{:?}", fresh.notes); } let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 3); assert_eq!(batch.skipped, 0, "diagnostic occurrences are not skipped-feature counts"); assert!(batch.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == GeometryType::Point)); @@ -1348,7 +1348,7 @@ mod tests { assert!(fresh.notes.is_empty(), "single-family input has no conversion losses: {:?}", fresh.notes); } let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 1); assert_eq!(batch.features[0].geometry.as_ref().unwrap().kind(), GeometryType::Point); } @@ -1445,7 +1445,7 @@ mod tests { } assert_eq!(fresh.zm_dropped, lossy); let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 2); assert!(batch.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == GeometryType::Point)); } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 932b1b7dba..7bf789306c 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -337,7 +337,7 @@ impl FeatureSource for GeoJsonSource { /// A changed file invalidates the saved bounds and offsets, even for records the bounds /// would skip. A successful visit uses the same file version as the index. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(&self.path)?); @@ -372,7 +372,7 @@ impl FeatureSource for GeoJsonSource { fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); // Counted first, then sampled, unless the native box is refused: no list of every match. - let extent = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let extent = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && extent.is_none() { return Err(super::unbounded_count()); @@ -445,17 +445,19 @@ impl GeoJsonSource { let place = self.places.get(i as usize).ok_or(())?; let json = read_place(f, pos, buf, place).ok_or(())?; let geometry = geojson_geometry(&json).map_err(|_| ())?; - // Kept as the file holds it, in its own system; its box in longitude/latitude answers the - // request. - let lonlat = match (self.reproject.transformer(), &geometry) { - (Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), - (_, g) => g.as_ref().map(crate::Geometry::extent), + // Kept as the file holds it, in its own system; its own box answers a request given in + // that system ([`Request::own`]), else its box in longitude/latitude. + let own = self.reproject.own_box(req); + let placed = match (own, self.reproject.transformer(), &geometry) { + (Some(_), _, g) => g.as_ref().map(crate::Geometry::extent), + (None, Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), + (None, _, g) => g.as_ref().map(crate::Geometry::extent), }; // One without geometry doesn't match an extent. - let outside = match (&lonlat, &req.extent) { + let outside = match (&placed, own.or(req.extent)) { (_, None) => false, (None, Some(_)) => true, - (Some(e), Some(r)) => !e.intersects(r), + (Some(e), Some(r)) => !e.intersects(&r), }; if outside || !wanted() { return Ok(None); diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index e7b1706127..3ef9b52d0d 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -412,8 +412,8 @@ impl GpkgSource { { return Ok(Row::Skip); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { return Ok(Row::Bad) }; - if !placed.in_request(req) { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, req)) else { return Ok(Row::Bad) }; + if !placed.inside { return Ok(Row::Skip); } Ok(Row::Feature(Feature { id, geometry: Some(placed.geometry), attrs: attrs() })) @@ -450,7 +450,7 @@ impl FeatureSource for GpkgSource { let limit = clamp_limit(req.limit); let guard = self.conn.lock().map_err(|_| DataError::Format("GeoPackage connection poisoned".into()))?; let conn = guard.as_ref().ok_or_else(|| DataError::Format("GeoPackage connection closed".into()))?; - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -566,7 +566,7 @@ impl FeatureSource for GpkgSource { // An upload's SQLite copy is generated; its bytes were supplied by the caller. let conn = if self.temp.is_some() { crate::provenance::without(|| open_db(path)) } else { open_db(path) }?; same_file()?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table)); let mut st = conn.prepare(&sql).map_err(err)?; diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 1f4a61e8fd..3b82085fd6 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -1244,7 +1244,7 @@ mod tests { assert_eq!(saved.changes.deleted, 0, "trigger-only deletion is not a submitted deletion"); let source = GpkgSource::open(&path, Some("roads")).unwrap(); for (x, expected) in [(30.5, vec![2]), (60.5, vec![7]), (4.5, vec![])] { - let batch = source.read(&Request { extent: Some(Extent::new(x, 1.0, x + 0.1, 4.0)), limit: 100 }).unwrap(); + let batch = source.read(&Request { extent: Some(Extent::new(x, 1.0, x + 0.1, 4.0)), limit: 100, own: None }).unwrap(); assert_eq!(batch.features.iter().map(|f| f.id).collect::>(), expected, "indexed={indexed}"); } let bounds: (f64, f64, f64, f64) = conn diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index ad1721491e..d1611f26d2 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -344,7 +344,7 @@ impl FeatureSource for GpkgMemSource { /// Counts scanned records and checks Cancel between them. fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -394,11 +394,11 @@ impl FeatureSource for GpkgMemSource { if known && !sample.wants() { return ControlFlow::Continue(()); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, req)) else { skipped += 1; return ControlFlow::Continue(()); }; - if !placed.in_request(req) || (!known && !sample.wants()) { + if !placed.inside || (!known && !sample.wants()) { return ControlFlow::Continue(()); } let geometry = placed.geometry; @@ -436,7 +436,7 @@ impl FeatureSource for GpkgMemSource { /// and a Cancel check between records. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut out = Batch { complete: true, ..Batch::default() }; // The visitor's error, which stops the scan. @@ -459,11 +459,11 @@ impl FeatureSource for GpkgMemSource { { return ControlFlow::Continue(()); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, &req)) else { out.skipped += 1; return ControlFlow::Continue(()); }; - if !placed.in_request(&req) { + if !placed.inside { return ControlFlow::Continue(()); } Some(placed.geometry) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 28ee0adae2..10d144bc0d 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -219,12 +219,17 @@ impl SourceInfo { pub struct Request { pub extent: Option, pub limit: usize, + /// The same box in a projected system, when the asker has it there exactly (a map in that + /// system gives its view in map units), with `extent` its longitude/latitude bounds. A source + /// whose own system ([`FeatureSource::coord_crs`]) it is tests each feature's own box against + /// it, converting nothing; any other source reads `extent`, as without it. + pub own: Option<(Crs, Extent)>, } impl Request { /// Every feature, up to [`MAX_LIMIT`]. pub fn all() -> Self { - Request { extent: None, limit: MAX_LIMIT } + Request { extent: None, limit: MAX_LIMIT, own: None } } } @@ -812,7 +817,7 @@ fn read_chunks(src: &dyn FeatureSource, budget: u64) -> Result { /// The geometry type of a source that doesn't declare one, from its first feature. pub(crate) fn peek_kind(src: &dyn FeatureSource) -> GeometryType { - src.read(&Request { extent: None, limit: 1 }) + src.read(&Request { extent: None, limit: 1, own: None }) .ok() .and_then(|b| b.features.into_iter().find_map(|f| f.geometry)) .map(|g| g.kind()) @@ -970,6 +975,34 @@ impl Reproject { ok.then_some(Placed { geometry: g, lonlat }) } + /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is + /// within `req`. Given the request's box in those coordinates ([`Request::own`]), its own box + /// is tested against it, converting nothing, so a geometry with no place in + /// longitude/latitude is kept too. Otherwise as [`Reproject::read`]: `None` when a coordinate + /// can't be converted to longitude/latitude, and its box there tested against the extent. + pub(crate) fn place(&self, g: Geometry, req: &Request) -> Option { + if let Some(own) = self.own_box(req) { + let inside = g.extent().intersects(&own); + return Some(Fitted { geometry: g, inside }); + } + let Placed { geometry, lonlat } = self.read(g)?; + let inside = req.extent.is_none_or(|e| lonlat.intersects(&e)); + Some(Fitted { geometry, inside }) + } + + /// The request's box in the source's own coordinates, when the asker gave it there + /// ([`Request::own`]) and they are projected. + pub(crate) fn own_box(&self, req: &Request) -> Option { + req.own.filter(|(crs, _)| self.t.is_some() && *crs == self.crs).map(|(_, e)| e) + } + + /// The request's box in the source's own coordinates, for an index to narrow by: the one the + /// asker gave there ([`Request::own`]), else its extent converted + /// ([`Reproject::extent_from_lonlat`]); `None` for none, or one that can't be bounded there. + pub(crate) fn request_box(&self, req: &Request) -> Option { + self.own_box(req).or_else(|| req.extent.and_then(|e| self.extent_from_lonlat(&e))) + } + /// A longitude/latitude geometry in the source's coordinates. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_native(&self, g: &Geometry) -> Option { @@ -1315,12 +1348,11 @@ pub(crate) struct Placed { pub(crate) lonlat: Extent, } -impl Placed { - /// Whether it is within a request's extent (in longitude/latitude), as [`in_request`] asks - /// of a geometry there. - pub(crate) fn in_request(&self, req: &Request) -> bool { - req.extent.is_none_or(|e| self.lonlat.intersects(&e)) - } +/// A geometry a source read for a request, in its own coordinates, and whether it is within the +/// request ([`Reproject::place`]). +pub(crate) struct Fitted { + pub(crate) geometry: Geometry, + pub(crate) inside: bool, } /// Makes ring rustls's process-wide crypto provider. SQL Server's client also builds aws-lc-rs @@ -1397,6 +1429,8 @@ pub(crate) fn read_ca_roots(label: &str, file: &Path, der: CaDer) -> Result Extent { - let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE }, Some(PROBE_TIMEOUT)) else { + let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE, own: None }, Some(PROBE_TIMEOUT)) else { return Extent::EMPTY; }; // Read in the table's own system: each placed in longitude/latitude, vertex by vertex. @@ -1314,10 +1314,10 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { let r = Reproject::from_crs(crate::raster::Crs::from_epsg(32617).unwrap(), &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r).unwrap_err().to_string().contains("can't be bounded")); - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10, own: None }; assert!(native_window(&clean, Extent::EMPTY, &r).unwrap().is_some()); assert!(native_window(&Request::all(), all, &r).unwrap().is_none()); } @@ -1368,12 +1368,12 @@ mod tests { let src = MysqlSource::open(conn.clone(), t.clone(), Some(f), None).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let opened = start.elapsed(); let i = src.info(); - let whole = src.read(&Request { extent: None, limit: 250_000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let whole = src.read(&Request { extent: None, limit: 250_000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let read = start.elapsed() - opened; let e = i.extent; let q = Extent::new(e.min_x, e.min_y, e.min_x + e.width() / 2.0, e.min_y + e.height() / 2.0); let started = std::time::Instant::now(); - let part = src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let part = src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let quarter = started.elapsed(); // In the table's own system: compared in longitude/latitude, as the request is. let to = src.coord_crs().to(crate::raster::Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs new file mode 100644 index 0000000000..a7e5eab478 --- /dev/null +++ b/crates/data/src/source/own_box_tests.rs @@ -0,0 +1,140 @@ +//! A read given its box in the source's own system ([`Request::own`]) tests each feature's own box +//! against it, converting nothing; without one, or with one in another system, it reads as before. + +use super::*; +use crate::raster::Crs; +use crate::{Dataset, Field, FieldType, Geometry, Value}; +use rustgis_geom::Coord; +use std::path::PathBuf; + +fn dir() -> PathBuf { + let d = std::env::temp_dir().join(format!("rustgis-own-box-tests-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn utm31() -> Crs { + Crs::from_epsg(32631).unwrap() +} + +/// Lines in UTM zone 31N: one at Paris, one from Paris to 1e9 m east (which has no place in +/// longitude/latitude), and one 400 km south. +fn lines() -> Dataset { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((451_500.0, 5_411_500.0), (1e9, 5_411_500.0)), vec![Value::Text("far east".into())]); + ds.push(line((451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), vec![Value::Text("south".into())]); + ds.held_in = utm31(); + ds +} + +fn names(b: &Batch) -> Vec { + let mut out: Vec = b + .features + .iter() + .filter_map(|f| match f.attrs.first() { + Some(Value::Text(t)) => Some(t.clone()), + _ => None, + }) + .collect(); + out.sort(); + out +} + +/// Around Paris: in longitude/latitude, and the same place in UTM 31N. +fn around_paris() -> (Extent, Extent) { + (Extent::new(2.2, 48.75, 2.5, 48.95), Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0)) +} + +fn read_three_ways(src: &dyn FeatureSource, what: &str) { + let (lonlat, utm) = around_paris(); + assert_eq!(src.coord_crs(), utm31(), "{what}"); + // In longitude/latitude, as before: the line with no place there is left out. + let plain = src.read(&Request { extent: Some(lonlat), limit: 100, own: None }).unwrap(); + assert_eq!(names(&plain), ["paris"], "{what}"); + // In its own system: the line reaching past where longitude/latitude goes is kept, as its box + // meets the view's; the one to the south still isn't. + let own = src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((utm31(), utm)) }).unwrap(); + assert_eq!(names(&own), ["far east", "paris"], "{what}"); + assert!(own.complete, "{what}"); + let line = own.features.iter().find(|f| matches!(f.attrs.first(), Some(Value::Text(t)) if t == "paris")).unwrap(); + assert_eq!(line.geometry.as_ref().map(Geometry::extent), Some(Extent::new(451_000.0, 5_411_000.0, 452_000.0, 5_412_000.0)), "{what}"); + // A box in another system is one this source can't take: read as without it. + let swiss = Extent::new(2_600_000.0, 1_200_000.0, 2_700_000.0, 1_300_000.0); + let other = src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((Crs::from_epsg(2056).unwrap(), swiss)) }).unwrap(); + assert_eq!(names(&other), ["paris"], "{what}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_read_given_its_box_in_the_files_own_system_tests_features_there() { + let d = dir(); + for ext in ["shp", "fgb", "gpkg", "parquet"] { + let p = d.join(format!("lines.{ext}")); + crate::io::write_path_in(&lines(), &p, utm31()).unwrap(); + let read = || { + let src = open_path(&p, None).unwrap(); + read_three_ways(src.as_ref(), ext); + }; + if ext == "shp" { + shp::with_test_cache(d.join("indexes"), read); + } else { + read(); + } + // The browser's GeoPackage reader too. + if ext == "gpkg" { + let bytes = Shared(std::sync::Arc::new(std::fs::read(&p).unwrap())); + let src = gpkg_mem::GpkgMemSource::open_shared(bytes, None).unwrap(); + read_three_ways(&src, "gpkg in memory"); + } + } +} + +#[test] +fn a_geojson_read_in_place_given_its_box_in_its_own_system_tests_features_there() { + let p = dir().join("lines.geojson"); + let feature = |name: &str, a: (f64, f64), b: (f64, f64)| { + format!( + r#"{{"type":"Feature","properties":{{"name":"{name}"}},"geometry":{{"type":"LineString","coordinates":[[{},{}],[{},{}]]}}}}"#, + a.0, a.1, b.0, b.1 + ) + }; + let text = format!( + r#"{{"type":"FeatureCollection","crs":{{"type":"name","properties":{{"name":"urn:ogc:def:crs:EPSG::32631"}}}},"features":[{},{}]}}"#, + feature("paris", (451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), + feature("south", (451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), + ); + std::fs::write(&p, text).unwrap(); + let src = geojson::GeoJsonSource::open_path(&p, "lines").unwrap(); + assert_eq!(src.coord_crs(), utm31()); + let (lonlat, utm) = around_paris(); + for own in [None, Some((utm31(), utm)), Some((Crs::from_epsg(2056).unwrap(), utm))] { + let b = src.read(&Request { extent: Some(lonlat), limit: 100, own }).unwrap(); + assert_eq!(names(&b), ["paris"], "{own:?}"); + } + // A box in its own system that misses Paris, though the longitude/latitude extent holds it: + // the box decides. + let elsewhere = Extent::new(600_000.0, 5_400_000.0, 620_000.0, 5_420_000.0); + assert!(src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((utm31(), elsewhere)) }).unwrap().features.is_empty()); +} + +#[test] +fn a_box_in_its_own_system_is_tested_without_converting() { + let mut notes = Vec::new(); + let r = Reproject::from_crs(utm31(), &mut notes); + let (lonlat, utm) = around_paris(); + let far = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(1e9, 5_411_500.0)]]); + // No place in longitude/latitude: left out as before without the box, kept with it. + assert!(r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: None }).is_none()); + let fitted = r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }).unwrap(); + assert!(fitted.inside); + assert_eq!(fitted.geometry, far); + assert_eq!(r.request_box(&Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }), Some(utm)); + // A source in longitude/latitude reads by the extent, whatever box comes with it. + let lonlat_source = Reproject::from_crs(Crs::LonLat, &mut notes); + let req = Request { extent: Some(lonlat), limit: 1, own: Some((Crs::LonLat, Extent::new(0.0, 0.0, 1.0, 1.0))) }; + assert_eq!(lonlat_source.request_box(&req), Some(lonlat)); + assert!(lonlat_source.place(Geometry::Point(Coord::new(2.3, 48.85)), &req).unwrap().inside); + assert!(notes.is_empty(), "{notes:?}"); +} diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 06bd3dd13b..3bdf676a65 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -499,7 +499,7 @@ impl FeatureSource for ParquetSource { self.attribute(); let limit = clamp_limit(req.limit); let md = self.reader.metadata(); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -665,7 +665,7 @@ impl FeatureSource for ParquetSource { // Null geometry is valid; malformed non-null WKB is skipped and counted. let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.read(g)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.place(g, req)) else { skipped += 1; continue; }; @@ -673,7 +673,7 @@ impl FeatureSource for ParquetSource { } None => None, }; - let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(req)); + let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside); if !matches_extent || (late && !sample.wants()) { continue; } @@ -718,7 +718,7 @@ impl FeatureSource for ParquetSource { if self.remote.is_some() { return Err(DataError::Unsupported("a whole GeoParquet by its web address read a chunk at a time".into())); } - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let md = self.reader.metadata(); let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut out = Batch { complete: true, ..Batch::default() }; @@ -774,7 +774,7 @@ impl FeatureSource for ParquetSource { crate::progress::step(1)?; let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.read(geom)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.place(geom, &req)) else { out.skipped += 1; continue; }; @@ -782,7 +782,7 @@ impl FeatureSource for ParquetSource { } None => None, }; - if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(&req)) { + if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside) { continue; } let geometry = geometry.map(|p| p.geometry); diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 9c7c762f4a..7cc20742e7 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1739,14 +1739,15 @@ impl FeatureSource for PostgisSource { }; // The index matched the request's box in the table's coordinates, which holds more // than the request when they are projected. Held in its own system, a geometry is - // placed in longitude/latitude to be compared, and kept as the table holds it. + // compared in the request's box there when it gives one, else placed in + // longitude/latitude to be compared, and kept as the table holds it. if self.held != Crs::LonLat { - let placed = feature.geometry.take().and_then(|g| self.reproject.as_ref().and_then(|r| r.read(g))); + let placed = feature.geometry.take().and_then(|g| self.reproject.as_ref().and_then(|r| r.place(g, req))); let Some(placed) = placed else { out.skipped += 1; continue; }; - if !placed.in_request(req) { + if !placed.inside { continue; } feature.geometry = Some(placed.geometry); @@ -1827,13 +1828,13 @@ mod tests { let mut source = source("POINT"); source.reproject = Some(Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new())); for limit in [0, 10] { - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("can't be bounded in the database"), "{error}"); } - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 0 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 0, own: None }; assert!(source.read(&clean).unwrap().features.is_empty()); - assert!(source.read(&Request { extent: None, limit: 0 }).is_ok()); + assert!(source.read(&Request { extent: None, limit: 0, own: None }).is_ok()); } /// A table in a system RustGIS converts itself is written as the layer holds it, in that @@ -2182,12 +2183,12 @@ mod tests { }; let opened = start.elapsed(); let i = src.info(); - let all = src.read(&Request { extent: None, limit: 250_000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let all = src.read(&Request { extent: None, limit: 250_000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let read = start.elapsed() - opened; // A view of a quarter of the extent. let e = i.extent; let q = Extent::new(e.min_x, e.min_y, e.min_x + e.width() / 2.0, e.min_y + e.height() / 2.0); - let part = src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let part = src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); // Features come in the table's own system when RustGIS converts it: their boxes // are compared in longitude/latitude, as the request is. let to = src.coord_crs().to(Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index da2b7e3416..1dc89300ea 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -229,7 +229,7 @@ impl FeatureSource for ShpSource { fn read(&self, req: &Request) -> Result { let encoding = self.encoding.decoder(); let limit = clamp_limit(req.limit); - let extent = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let extent = self.reproject.request_box(req); // Keep indexed zero-limit counts; a refused view has no cheap candidate count. if limit == 0 && req.extent.is_some() && extent.is_none() { return Err(super::unbounded_count()); @@ -275,7 +275,7 @@ impl FeatureSource for ShpSource { boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); return Ok(()); } - Ok(Some(g)) => match self.reproject.read(g) { + Ok(Some(g)) => match self.reproject.place(g, req) { Some(placed) => Some(placed), None => { skipped += 1; @@ -290,7 +290,7 @@ impl FeatureSource for ShpSource { }; // The index's boxes are rounded outward to f32, so it can match a shape just outside. A // shape without geometry doesn't match an extent, bounded natively or not. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.inside) { return Ok(()); } let geometry = geometry.map(|p| p.geometry); @@ -355,7 +355,7 @@ impl FeatureSource for ShpSource { fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let encoding = self.encoding.decoder(); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let extent = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); if extent.is_some_and(|e| e.is_empty()) { return Ok(Batch { complete: true, ..Batch::default() }); @@ -396,7 +396,7 @@ impl FeatureSource for ShpSource { boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); return Ok(()); } - Ok(Some(g)) => match self.reproject.read(g) { + Ok(Some(g)) => match self.reproject.place(g, &req) { Some(placed) => Some(placed), None => { skipped += 1; @@ -410,7 +410,7 @@ impl FeatureSource for ShpSource { } }; // As in `read`, the shape itself is checked. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(&req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.inside) { return Ok(()); } let geometry = geometry.map(|p| p.geometry); diff --git a/crates/data/src/source/shp/cache/tests.rs b/crates/data/src/source/shp/cache/tests.rs index 74b146ad16..f6c83eb886 100644 --- a/crates/data/src/source/shp/cache/tests.rs +++ b/crates/data/src/source/shp/cache/tests.rs @@ -503,7 +503,8 @@ fn cache_child_fixture() { assert!(!source.info().indexed); assert!(source.info().notes.iter().any(|n| n.contains("scanning record headers"))); for limit in [0, 1, 100] { - let batch = source.read(&crate::source::Request { extent: Some(crate::Extent::new(0.0, 0.0, 3.0, 3.0)), limit }).unwrap(); + let batch = + source.read(&crate::source::Request { extent: Some(crate::Extent::new(0.0, 0.0, 3.0, 3.0)), limit, own: None }).unwrap(); assert_eq!(batch.matched, 1); assert_eq!(batch.features.len(), limit.min(1)); } diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 1147c71ffe..db2537c7d9 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -333,7 +333,7 @@ fn shapefile_disk_index_reopens_and_invalidates_without_changing_source() { let p = fixture.join("indexed-grid.shp"); points_shapefile(&p); let original = std::fs::read(&p).unwrap(); - let req = Request { extent: Some(Extent::new(10.0, 10.0, 40.0, 30.0)), limit: 1000 }; + let req = Request { extent: Some(Extent::new(10.0, 10.0, 40.0, 30.0)), limit: 1000, own: None }; let src = open_path(&p, None).unwrap(); let expected = src.read(&req).unwrap(); let reopened = open_path(&p, None).unwrap(); @@ -371,14 +371,14 @@ fn shapefile_disk_index_keeps_file_order_and_query_boundaries() { } std::fs::write(&p, bytes).unwrap(); let src = open_path(&p, None).unwrap(); - let batch = src.read(&Request { extent: Some(Extent::new(1.0, -1.0, 2.0, 1.0)), limit: 1000 }).unwrap(); + let batch = src.read(&Request { extent: Some(Extent::new(1.0, -1.0, 2.0, 1.0)), limit: 1000, own: None }).unwrap(); assert_eq!(batch.matched, 101); assert_eq!(batch.features.len(), 101); assert!(batch.complete); assert!(batch.features.windows(2).all(|p| p[0].id < p[1].id)); assert_eq!(batch.features.first().unwrap().geometry, Some(Geometry::Point(Coord::new(2.0, 0.0)))); assert_eq!(batch.features.last().unwrap().geometry, Some(Geometry::Point(Coord::new(1.0, 0.0)))); - let sample = src.read(&Request { extent: None, limit: 10 }).unwrap(); + let sample = src.read(&Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(sample.matched, 1000); assert_eq!(sample.features.len(), 10); assert!(!sample.complete); @@ -404,7 +404,7 @@ fn shapefile_overview_index_shortcut_does_not_include_null_shapes() { std::fs::write(&p, bytes).unwrap(); let src = open_path(&p, None).unwrap(); assert_eq!(src.read(&Request::all()).unwrap().features.len(), 2); - let view = src.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 100 }).unwrap(); + let view = src.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 100, own: None }).unwrap(); assert_eq!(view.matched, 1); assert_eq!(view.features.len(), 1); assert!(view.features.iter().all(|f| f.geometry.is_some())); @@ -506,7 +506,7 @@ fn disk_queries_match_legacy_scan_sampling_and_edges() { for limit in [0, 1, 7, 29, 1000] { let step = crate::source::stride(ids.len() as u64, limit).max(1) as usize; let expected: Vec<_> = ids.iter().copied().step_by(step).take(limit).collect(); - let batch = src.read(&Request { extent, limit }).unwrap(); + let batch = src.read(&Request { extent, limit, own: None }).unwrap(); assert_eq!(batch.matched, ids.len() as u64); assert_eq!(batch.complete, step == 1); assert_eq!(batch.features.iter().map(|f| f.id).collect::>(), expected); @@ -534,7 +534,7 @@ fn shapefile_disk_index_benchmark() { let clock = std::time::Instant::now(); let source = ShpSource::open_path(&path, "benchmark").unwrap(); let warm = clock.elapsed(); - let request = Request { extent: Some(Extent::new(-1.0, -1.0, 1.0, 1.0)), limit: 1000 }; + let request = Request { extent: Some(Extent::new(-1.0, -1.0, 1.0, 1.0)), limit: 1000, own: None }; let clock = std::time::Instant::now(); let indexed = source.read(&request).unwrap(); let query = clock.elapsed(); @@ -564,7 +564,7 @@ fn shapefile_disk_index_complete_chunks_preserve_full_reads_and_file_order() { points_shapefile(&path); let source = open_path(&path, None).unwrap(); assert!(source.info().indexed); - assert_eq!(source.read(&Request { extent: None, limit: 1 }).unwrap().features.len(), 1); + assert_eq!(source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.len(), 1); for extent in [None, Some(Extent::new(10.0, 5.0, 15.0, 10.0)), Some(Extent::EMPTY)] { let expected = source.read(&Request { extent, ..Request::all() }).unwrap(); for budget in [1, 256, 8192] { @@ -590,7 +590,7 @@ fn shapefile_disk_index_complete_chunks_preserve_full_reads_and_file_order() { source .visit_chunks(None, 256, &mut |_| { if !reentrant { - assert_eq!(source.read(&Request { extent: None, limit: 1 })?.features.len(), 1); + assert_eq!(source.read(&Request { extent: None, limit: 1, own: None })?.features.len(), 1); reentrant = true; } Ok(()) diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 46a6c915d0..8aea2a6fa1 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -956,7 +956,7 @@ impl SqlServerSource { } fn measure(&self) -> Extent { - let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE }, Some(PROBE_TIMEOUT)) else { + let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE, own: None }, Some(PROBE_TIMEOUT)) else { return Extent::EMPTY; }; // Read in the table's own system: each placed in longitude/latitude, vertex by vertex. @@ -1328,17 +1328,17 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r, false, 160).unwrap_err().to_string().contains("can't be bounded")); - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10, own: None }; assert!(native_window(&clean, Extent::EMPTY, &r, false, 160).unwrap().is_some()); } #[test] fn native_windows_respect_database_compatibility() { let reproject = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 100 }; + let req = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 100, own: None }; for compatibility in [0, 80, 90, 100] { assert_eq!(native_window(&req, Extent::EMPTY, &reproject, true, compatibility).unwrap(), None); } @@ -1354,7 +1354,7 @@ mod tests { ); } assert_eq!(native_window(&req, Extent::new(-10.0, -10.0, 10.0, 10.0), &reproject, true, 110).unwrap(), None); - assert_eq!(native_window(&Request { extent: None, limit: 100 }, Extent::EMPTY, &reproject, true, 110).unwrap(), None); + assert_eq!(native_window(&Request { extent: None, limit: 100, own: None }, Extent::EMPTY, &reproject, true, 110).unwrap(), None); } #[test] @@ -1493,7 +1493,7 @@ mod tests { Err(e) => panic!("{}: {e}", t.label()), }; let i = src.info(); - let whole = match src.read(&Request { extent: None, limit: 250_000 }) { + let whole = match src.read(&Request { extent: None, limit: 250_000, own: None }) { Ok(whole) => whole, // A table too large to count and sample whole in the statement timeout says so; // its reads by extent are what a map asks for. @@ -1516,7 +1516,7 @@ mod tests { let part = if e.is_empty() { Batch::default() } else { - src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())) + src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())) }; // In the table's own system: compared in longitude/latitude, as the request is. let to = src.coord_crs().to(crate::raster::Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); @@ -1528,7 +1528,7 @@ mod tests { ids.sort_unstable(); ids.dedup(); assert_eq!(ids.len(), whole.features.len(), "{}: ids repeat", t.label()); - let sample = src.read(&Request { extent: None, limit: 1 }).unwrap_or_else(|e| panic!("{e}")); + let sample = src.read(&Request { extent: None, limit: 1, own: None }).unwrap_or_else(|e| panic!("{e}")); assert!(sample.features.len() <= 1); assert_eq!(sample.matched, whole.matched); println!( diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 1fd2d08b02..953dc09a34 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -398,13 +398,13 @@ fn geopackage_provenance_excludes_temporary_copies() { let upload = gpkg::GpkgUpload::new(&bytes).unwrap(); assert!(upload.unsupported_table_counts().unwrap().is_empty()); let source = upload.open(None).unwrap(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); assert_eq!(captured.inputs().len(), 1); assert_eq!(captured.inputs()[0].path, path.display().to_string()); assert!(captured.inputs()[0].sha256.is_some()); drop(captured); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); let mut count = 0; source .visit_chunks(None, 1 << 20, &mut |features| { @@ -425,13 +425,13 @@ fn geopackage_provenance_skips_a_replaced_path() { write_gpkg(&path, true); let source = open_path(&path, None).unwrap(); let captured = crate::provenance::Capture::start(); - source.read(&Request { extent: None, limit: 1 }).unwrap(); + source.read(&Request { extent: None, limit: 1, own: None }).unwrap(); assert!(captured.inputs().iter().any(|i| i.path == path.display().to_string())); drop(captured); std::fs::rename(&path, folder.path().join("retained.gpkg")).unwrap(); std::fs::write(&path, b"replacement").unwrap(); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); assert!(captured.inputs().is_empty()); } @@ -450,7 +450,7 @@ fn geopackage_provenance_keeps_a_linked_path() { let inputs = |path: &Path| { let source = open_path(path, None).unwrap(); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs().into_iter().map(|i| i.path).collect::>() }; let resolved = std::fs::canonicalize(&target).unwrap(); @@ -482,7 +482,7 @@ fn a_conversion_names_its_original_as_it_was_when_opened() { let source = super::fgb::FgbSource::open_converted_path(&converted, "grid", &original, None).unwrap(); let inputs = || { let captured = Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs() }; let before = inputs(); @@ -498,7 +498,7 @@ fn a_conversion_names_its_original_as_it_was_when_opened() { let source = super::parquet::ParquetSource::open_converted_path(&parquet, "grid", Some(&db), None).unwrap(); let inputs = || { let captured = Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs() }; let before: Vec = inputs(); @@ -670,13 +670,14 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!((c.x - (-138.0)).abs() < 1e-4 && (c.y - (-44.0)).abs() < 1e-4, "{c:?} in {}", info.format); assert_eq!(f.attrs[vi], Value::Int(64)); // Ids stay put between reads. - let near = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100 }).unwrap()); + let near = + in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100, own: None }).unwrap()); let g = near.features.iter().find(|g| g.attrs.contains(&Value::Text("p3_4".into()))).unwrap(); assert_eq!(g.id, f.id, "{}", info.format); // An extent: exactly the points in it. let e = Extent::new(-60.0, -10.0, 40.0, 50.0); - let got = in_lonlat(src, src.read(&Request { extent: Some(e), limit: 10_000 }).unwrap()); + let got = in_lonlat(src, src.read(&Request { extent: Some(e), limit: 10_000, own: None }).unwrap()); assert_eq!(got.features.len(), in_box(&e), "{}", info.format); assert!(got.complete); assert!(got.features.iter().all(|f| f.geometry.as_ref().is_some_and(|g| e.contains(g.extent().center())))); @@ -688,7 +689,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { } // A limit: a sample spread over the whole extent, not the first rows. - let s = in_lonlat(src, src.read(&Request { extent: None, limit: 60 }).unwrap()); + let s = in_lonlat(src, src.read(&Request { extent: None, limit: 60, own: None }).unwrap()); assert!(!s.complete); assert!(s.features.len() <= 60 && s.features.len() >= 50, "{} of {}", s.features.len(), info.format); let xs: Vec = s.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.extent().min_x).collect(); @@ -696,7 +697,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!(s.matched >= 600); // An extent outside the data. - let none = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100 }).unwrap()); + let none = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100, own: None }).unwrap()); assert!(none.features.is_empty()); // A whole read into a dataset. @@ -1711,7 +1712,7 @@ fn hostile_files_are_errors_not_panics() { for name in ["x.parquet", "x.fgb", "x.gpkg"] { if let Ok(s) = open_bytes(name, bytes.clone(), None) { let _ = s.read(&Request::all()); - let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 3 }); + let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 3, own: None }); } } } @@ -1755,7 +1756,7 @@ fn vector_samples() { e.center().y + e.height() / 8.0, ); let t2 = std::time::Instant::now(); - let b = match src.read(&Request { extent: Some(view), limit: 200_000 }) { + let b = match src.read(&Request { extent: Some(view), limit: 200_000, own: None }) { Ok(b) => b, Err(e) => { println!("{} [{layer}]: {e}", p.display()); @@ -1853,7 +1854,7 @@ fn writes_geopackage_geoparquet_and_shapefile() { for ext in ["gpkg", "parquet"] { let s = open_path(&d.join(format!("parcels.{ext}")), None).unwrap(); assert_eq!(s.info().count, Some(3), "{ext}"); - let b = s.read(&Request { extent: Some(Extent::new(15.0, 15.0, 25.0, 25.0)), limit: 100 }).unwrap(); + let b = s.read(&Request { extent: Some(Extent::new(15.0, 15.0, 25.0, 25.0)), limit: 100, own: None }).unwrap(); assert_eq!(b.features.len(), 1, "{ext}"); if ext == "gpkg" { assert_eq!(b.features[0].id, 2); @@ -1908,7 +1909,7 @@ fn geoparquet_exports_keep_exact_values_and_remote_extent_reads() { // Null rows must not consume a sample slot, whether the group is partly or wholly inside. for (extent, matched) in [(Extent::new(-90.0, 36.0, -89.0, 37.0), 1), (Extent::new(-180.0, -90.0, 180.0, 90.0), 2)] { for limit in [1, 10] { - let req = Request { extent: Some(extent), limit }; + let req = Request { extent: Some(extent), limit, own: None }; let remote = source.read(&req).unwrap(); let local_batch = local.read(&req).unwrap(); assert_eq!(remote.features.len(), matched.min(limit)); @@ -1959,7 +1960,7 @@ fn geoparquet_inferred_covering_nulls_fall_back_to_geometry() { let remote = open_driven(url); for extent in [Extent::new(-90.0, 36.0, -89.0, 37.0), Extent::new(-180.0, -90.0, 180.0, 90.0)] { for limit in [1, 10] { - let req = Request { extent: Some(extent), limit }; + let req = Request { extent: Some(extent), limit, own: None }; let expected = local.read(&req).unwrap(); assert_eq!(expected.features.len(), 1); assert_eq!((expected.matched, expected.complete, expected.skipped), (1, true, 0)); @@ -2320,7 +2321,7 @@ fn flatgeobuf_and_geoparquet_by_address() { let src = open_driven(&url); assert_eq!(src.info().count, Some(160_000), "{name}"); let e = Extent::new(10.0, 10.0, 12.0, 12.0); - let req = Request { extent: Some(e), limit: 10_000 }; + let req = Request { extent: Some(e), limit: 10_000, own: None }; let got = src.read(&req).unwrap(); let local = open_bytes(name, bytes, None).unwrap().read(&req).unwrap(); let ids = |b: &Batch| b.features.iter().map(|f| f.id).collect::>(); @@ -2332,7 +2333,7 @@ fn flatgeobuf_and_geoparquet_by_address() { let fetched = sent.load(std::sync::atomic::Ordering::Relaxed); assert!(fetched < total / 4, "{name}: fetched {fetched} of {total} bytes"); // A sample of the whole file, spread over it. - let s = src.read(&Request { extent: None, limit: 500 }).unwrap(); + let s = src.read(&Request { extent: None, limit: 500, own: None }).unwrap(); assert!(!s.complete && s.features.len() <= 500 && s.features.len() >= 250, "{name}: {}", s.features.len()); } @@ -2508,10 +2509,11 @@ fn shapefile_in_place_reprojects_from_its_prj() { assert!((e.min_x - 2.335).abs() < 1e-6 && (e.min_y - 48.855).abs() < 1e-6, "{e:?}"); assert!(src.info().notes.is_empty(), "{:?}", src.info().notes); // A longitude/latitude extent finds it; one beside it doesn't. - let near = in_lonlat(src.as_ref(), src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10 }).unwrap()); + let near = + in_lonlat(src.as_ref(), src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10, own: None }).unwrap()); let c = near.features.first().and_then(|f| f.geometry.as_ref()).and_then(Geometry::label_point).unwrap(); assert!((c.x - 2.335).abs() < 1e-6 && (c.y - 48.855).abs() < 1e-6, "{c:?}"); - assert!(src.read(&Request { extent: Some(Extent::new(3.0, 48.5, 3.5, 49.0)), limit: 10 }).unwrap().features.is_empty()); + assert!(src.read(&Request { extent: Some(Extent::new(3.0, 48.5, 3.5, 49.0)), limit: 10, own: None }).unwrap().features.is_empty()); // Without the .prj the coordinates are taken as they are, and that's said. std::fs::remove_file(p.with_extension("prj")).unwrap(); let src = open_path(&p, None).unwrap(); @@ -2530,7 +2532,7 @@ fn damaged_shapefiles_are_errors_or_skips_not_panics() { let read = || { if let Ok(s) = open_path(p, None) { let _ = s.read(&Request::all()); - let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 1 }); + let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 1, own: None }); } }; #[cfg(not(target_arch = "wasm32"))] @@ -2710,7 +2712,7 @@ fn geojson_in_place_matches_one_read_whole() { assert_eq!(inplace.features, whole.features, "{file}"); assert_eq!(report.messages.len(), whole_report.messages.len(), "{file}: {:?}", report.messages); // Extent reads skip features without geometry, and find each by its box. - let b = src.read(&Request { extent: Some(Extent::new(0.5, 0.5, 1.5, 2.5)), limit: 100 }).unwrap(); + let b = src.read(&Request { extent: Some(Extent::new(0.5, 0.5, 1.5, 2.5)), limit: 100, own: None }).unwrap(); assert!(b.features.iter().all(|f| f.geometry.is_some()), "{file}"); } // Not a FeatureCollection, or not GeoJSON: not read in place. @@ -2800,7 +2802,7 @@ fn geojson_legacy_crs_is_honoured_by_both_paths() { let p = dir().join("geojson-crs").join("rd.geojson"); for in_memory in [crate::io::BYTES_FLOOR, 0] { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); - let at = |e: Extent| src.read(&Request { extent: Some(e), limit: 100 }).unwrap().features.len(); + let at = |e: Extent| src.read(&Request { extent: Some(e), limit: 100, own: None }).unwrap().features.len(); assert_eq!(at(Extent::new(5.85, 51.95, 5.86, 51.96)), 1, "the polygon only"); assert_eq!(at(Extent::new(5.95, 52.02, 5.96, 52.03)), 1, "the polygon only"); assert_eq!(at(Extent::new(5.8, 51.9, 6.0, 52.1)), 2); @@ -2990,9 +2992,9 @@ fn geojson_sampling_skips_dropped_features() { for in_memory in [crate::io::BYTES_FLOOR, 0] { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); assert_eq!(src.info().count, Some(3)); - let all = src.read(&Request { extent: None, limit: 100 }).unwrap(); + let all = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); assert_eq!((all.features.len(), all.matched, all.skipped, all.complete), (3, 3, 0, true)); - let some = src.read(&Request { extent: None, limit: 2 }).unwrap(); + let some = src.read(&Request { extent: None, limit: 2, own: None }).unwrap(); assert_eq!((some.features.len(), some.matched, some.skipped, some.complete), (2, 3, 0, false)); assert!(some.features.iter().all(|f| f.geometry.is_some())); let ids: Vec = all.features.iter().map(|f| f.id).collect(); @@ -3332,7 +3334,8 @@ fn nested_columns_and_vectors_by_address() { let e = Extent::new(10.0, 10.0, 40.0, 30.0); // The rows in the extent, with the nested column as a field. let (fields, batch) = - query_url_blocking(url, vec!["assets.data.href".into(), "no.such".into()], Request { extent: Some(e), limit: 1000 }).unwrap(); + query_url_blocking(url, vec!["assets.data.href".into(), "no.such".into()], Request { extent: Some(e), limit: 1000, own: None }) + .unwrap(); let k = fields.iter().position(|f| f.name == "assets.data.href").unwrap(); assert!(!fields.iter().any(|f| f.name == "no.such")); assert_eq!(batch.features.len(), in_box(&e)); @@ -3427,7 +3430,7 @@ fn shapefile_complete_chunks_keep_all_rows_order_attributes_and_budget() { let empty = shp::ShpSource::open_path(&empty_path, "empty").unwrap(); assert!(empty.visit_chunks(None, 0, &mut |_| panic!("zero budget must not emit")).is_err()); let extent = Some(Extent::new(0.02, 0.0, 0.1, 2.0)); - let expected = source.read(&Request { extent, limit: 1000 }).unwrap(); + let expected = source.read(&Request { extent, limit: 1000, own: None }).unwrap(); let mut rows = Vec::new(); source .visit_chunks(extent, 256, &mut |chunk| { @@ -3474,7 +3477,7 @@ fn geopackage_keeps_rows_without_geometry() { let (rows, summary, _) = visit_all(src.as_ref(), None, 1024); assert_eq!((rows, summary.matched, summary.skipped), (whole.features, 602, 4), "{format}"); let world = Extent::new(-180.0, -85.0, 180.0, 85.0); - let part = src.read(&Request { extent: Some(world), limit: 10_000 }).unwrap(); + let part = src.read(&Request { extent: Some(world), limit: 10_000, own: None }).unwrap(); assert_eq!(part.features.len(), 600, "{format}"); assert_eq!(visit_all(src.as_ref(), Some(world), 1024).0.len(), 600, "{format}"); } @@ -3541,7 +3544,7 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { // Each row alone when none fits the budget. assert_eq!(visit_all(src.as_ref(), None, 1).0, whole.features, "{format}"); // An extent: the features a complete read of it gives (the R-tree's order may differ). - let part = src.read(&Request { extent: Some(extent), limit: 10_000 }).unwrap(); + let part = src.read(&Request { extent: Some(extent), limit: 10_000, own: None }).unwrap(); assert!(part.complete && part.features.len() == in_box(&extent), "{format}"); let (rows, summary, _) = visit_all(src.as_ref(), Some(extent), 1024); assert!(summary.complete && summary.features.is_empty() && summary.matched == rows.len() as u64, "{format}"); @@ -3561,7 +3564,7 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { assert!(src.visit_chunks(None, 0, &mut |_| panic!("a zero budget must not emit")).is_err(), "{format}"); // The map's reads of the layer go on while a traversal waits on its visitor. src.visit_chunks(None, 256, &mut |_| { - assert_eq!(src.read(&Request { extent: None, limit: 1 }).unwrap().features.len(), 1, "{format}"); + assert_eq!(src.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.len(), 1, "{format}"); Ok(()) }) .unwrap(); @@ -3940,7 +3943,7 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { let owners = |p: &Path| rusqlite::Connection::open(p).unwrap().query_row("SELECT count(*) FROM owners", [], |r| r.get::<_, i64>(0)).unwrap(); assert_eq!(owners(&path), 1); - let read = |t: &str, extent| open_path(&path, Some(t)).unwrap().read(&Request { extent, limit: 100 }).unwrap().features; + let read = |t: &str, extent| open_path(&path, Some(t)).unwrap().read(&Request { extent, limit: 100, own: None }).unwrap().features; assert_eq!(read("permits", None).len(), 3); // Its spatial index answers an extent query. assert_eq!(read("permits", Some(Extent::new(10.5, 19.0, 11.5, 21.0))).len(), 1); @@ -4482,7 +4485,7 @@ fn parquet_date_units_invalid_values_and_nulls() { assert_eq!(batch.features[1].attrs[3].to_string(), "1970-01-01T00:00:00.000001"); assert!(batch.features[2].attrs.iter().all(Value::is_null)); let extent = Extent::new(-0.1, -0.1, 0.1, 0.1); - let filtered = source.read(&Request { extent: Some(extent), limit: usize::MAX }).unwrap(); + let filtered = source.read(&Request { extent: Some(extent), limit: usize::MAX, own: None }).unwrap(); assert_eq!(filtered.features.len(), 1); assert!(filtered.unread_dates.is_empty(), "invalid dates in filtered-out rows aren't read losses"); let filtered = source.visit_chunks(Some(extent), 256, &mut |_| Ok(())).unwrap(); @@ -4564,7 +4567,7 @@ fn a_feature_just_outside_an_extent_is_left_out_of_its_read() { let mut ds = Dataset::new("edge", GeometryType::Point, vec![]); ds.push(Some(Geometry::Point(Coord::new(0.0, 0.999_999_999))), vec![]); let extent = Some(Extent::new(-1.0, 1.0, 1.0, 2.0)); - let req = Request { extent, limit: 1000 }; + let req = Request { extent, limit: 1000, own: None }; let (shp_path, geojson_path) = (d.join("edge.shp"), d.join("edge.geojson")); crate::io::write_path(&ds, &shp_path).unwrap(); crate::io::write_path(&ds, &geojson_path).unwrap(); @@ -4687,12 +4690,12 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { // A zero limit cannot give a count for a view requiring a complete geometry scan. let probe = crate::progress::tests::Counted::cancelling_after(0); let _guard = crate::progress::install(Some(probe.clone())); - let error = source.read(&Request { extent: Some(view), limit: 0 }).unwrap_err().to_string(); + let error = source.read(&Request { extent: Some(view), limit: 0, own: None }).unwrap_err().to_string(); assert!(error.contains("zero-limit") && error.contains("count"), "{ext}: {error}"); assert_eq!(probe.done.load(std::sync::atomic::Ordering::Relaxed), 0, "{ext}"); } for limit in [10, 2201] { - let read = in_lonlat(source, source.read(&Request { extent: Some(view), limit }).unwrap()); + let read = in_lonlat(source, source.read(&Request { extent: Some(view), limit, own: None }).unwrap()); assert_eq!(read.matched, 200, "{ext}: count only view matches before sampling"); if limit == 10 { // Adaptive sampling keeps between half the limit and the limit. @@ -4711,7 +4714,7 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { // Cancel while scanning, not before the read starts; the view needs a complete scan. let probe = crate::progress::tests::Counted::cancelling_after(3); let _guard = crate::progress::install(Some(probe.clone())); - assert!(matches!(source.read(&Request { extent: Some(view), limit: 10 }), Err(DataError::Cancelled)), "{ext}"); + assert!(matches!(source.read(&Request { extent: Some(view), limit: 10, own: None }), Err(DataError::Cancelled)), "{ext}"); assert_eq!(probe.done.load(std::sync::atomic::Ordering::Relaxed), 3, "{ext}"); } if source.visits_chunks() { @@ -4733,7 +4736,7 @@ fn unbounded_parquet_view_refuses_a_capped_group() { ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Int(1)]); write_unbounded_view_fixture(&ds, &p); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_group_rows(1); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("more than the 1 read from one"), "{error}"); } @@ -4748,12 +4751,12 @@ fn unbounded_parquet_view_refuses_decoded_columns_over_budget() { } write_unbounded_view_fixture(&ds, &p); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_scan_bytes(16 << 10); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 1 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 1, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); let error = source.visit_chunks(req.extent, 4096, &mut |_| Ok(())).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); - let clean = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 1 }; + let clean = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 1, own: None }; assert_eq!(source.read(&clean).unwrap().features.len(), 1); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); let batch = source.read(&req).unwrap(); @@ -4771,7 +4774,7 @@ fn unbounded_parquet_scan_accepts_two_thousand_distinct_points() { } write_projected_parquet_fixture(&ds, &p, 2000, true); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let batch = source.read(&req).unwrap(); assert_eq!(batch.matched, 2000); assert!((5..=10).contains(&batch.features.len())); @@ -4825,7 +4828,7 @@ fn unbounded_parquet_view_bounds_aggregate_row_masks() { (0..40_000).map(|id| crate::Feature { id, geometry: Some(Geometry::Point(Coord::new(-81.0, 0.0))), attrs: vec![] }).collect(); write_projected_parquet_fixture(&ds, &p, 100, true); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_scan_bytes(32 << 10); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("row-mask budget"), "{error}"); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); diff --git a/crates/data/tests/integration/extent_query_properties.rs b/crates/data/tests/integration/extent_query_properties.rs index 894cda1ac9..080c3b2621 100644 --- a/crates/data/tests/integration/extent_query_properties.rs +++ b/crates/data/tests/integration/extent_query_properties.rs @@ -145,7 +145,7 @@ fn differences(all: &[rustgis_data::Feature], got: &[u64], q: &Extent, how: &str /// What `src` does differently for `q`, besides the limits. fn check(src: &dyn FeatureSource, q: &Extent) -> Result<(Vec, usize, usize), String> { let all = src.read(&Request::all()).map_err(|e| format!("whole read: {e}"))?; - let read = src.read(&Request { extent: Some(*q), limit: MAX_LIMIT }).map_err(|e| format!("read: {e}"))?; + let read = src.read(&Request { extent: Some(*q), limit: MAX_LIMIT, own: None }).map_err(|e| format!("read: {e}"))?; let mut found = differences(&all.features, &ids(read.features.iter().map(|f| f.id)), q, "read"); if !read.complete { found.push("read was incomplete".into()); diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 60f5c3a345..48e0bc03f8 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -654,7 +654,7 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(rustgis_data::source::materialize(&src).unwrap().1.messages, whole, "LDID {ldid:02X} whole read in place"); - for (request, rows, complete) in [(Request { extent: None, limit: 1 }, 1, false), (Request::all(), 3, true)] { + for (request, rows, complete) in [(Request { extent: None, limit: 1, own: None }, 1, false), (Request::all(), 3, true)] { let batch = src.read(&request).unwrap(); assert_eq!(batch.matched, 3); assert_eq!(batch.complete, complete); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 91b84784e8..e0b3078269 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3504,7 +3504,7 @@ const ASPRS: [(i64, [u8; 3]); 13] = [ /// sample of its points. fn lidar_renderer(src: &dyn rustgis_data::source::FeatureSource, seed: u32) -> Option { let info = src.info(); - let sample = src.read(&rustgis_data::source::Request { extent: None, limit: 100_000 }).ok()?; + let sample = src.read(&rustgis_data::source::Request { extent: None, limit: 100_000, own: None }).ok()?; let mut ds = rustgis_data::Dataset::new(info.name.clone(), GeometryType::Point, info.fields.clone()); ds.features = sample.features.into(); let mut base = rustgis_map::Symbol::default_for(GeometryType::Point, seed); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 116ce9232c..acd60c9902 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2135,7 +2135,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sky: false, }; let lonlat = crate::render::view_lonlat(s.map(), &view); - let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let own = crate::render::view_own(s.map(), &view); + let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); // Context around the data (neighbouring borders, the states around in one colour), which the // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). // It is judged again at each other scale the search below draws the map at, as the placement @@ -2409,7 +2410,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sky: false, }; let lonlat = crate::render::view_lonlat(s.map(), &view); - let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let own = crate::render::view_own(s.map(), &view); + let reading = + s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); let here_context = if tried == asked_scale { context.clone() } else { context_at(s, centred, tried) }; let here = if reading || (tried != asked_scale && crate::render::layout::tile_legends_pending(s.map(), render_scale, &[])) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a5946e99a1..98cb0b1027 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44516,7 +44516,7 @@ fn postgis_dates_live() { let conn = postgis::connect(&url, false).unwrap(); let t = postgis::find_table(&conn, &format!("public.{table}")).unwrap(); let src = postgis::PostgisSource::open(conn, t, None, None).unwrap(); - let b = src.read(&Request { extent: None, limit: 100 }).unwrap(); + let b = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); let note = rustgis_data::source::unread_dates_note(&src.info().fields, &b.unread_dates); assert_eq!(note.as_deref(), Some("2 values aren't dates and were read as empty, in 'd', 'ts'")); let f = b.features.iter().find(|f| f.id == 1).unwrap(); diff --git a/crates/engine/tests/integration/portable_projects/reload.rs b/crates/engine/tests/integration/portable_projects/reload.rs index f88cb6a6ce..92eb7d1f04 100644 --- a/crates/engine/tests/integration/portable_projects/reload.rs +++ b/crates/engine/tests/integration/portable_projects/reload.rs @@ -696,7 +696,7 @@ fn reload_reconverts_original_gdal_folder_and_accepts_its_declared_empty_table() assert!(loaded(&reopened, id).features.is_empty()); drop(reopened); assert!(restored_workspace.exists(), "an escaped restored reader pins its fresh workspace"); - let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1, own: None }).unwrap(); assert!(batch.complete && batch.features.is_empty() && batch.skipped == 0); drop(restored_reader); assert!(!restored_workspace.exists(), "the last restored reader releases all conversion artifacts"); @@ -806,7 +806,7 @@ fn reload_reconverts_duckdb_table_and_keeps_only_its_original_geometry_branch() assert!(loaded(&reopened, id).features.is_empty()); drop(reopened); assert!(restored_workspace.exists(), "an escaped restored reader pins its fresh workspace"); - let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1, own: None }).unwrap(); assert!(batch.complete && batch.features.is_empty() && batch.skipped == 0); drop(restored_reader); assert!(!restored_workspace.exists(), "the last restored reader releases all conversion artifacts"); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6068463f82..513e9ea915 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -640,11 +640,18 @@ impl Layer { /// read, and starts one when the view has moved beyond what was read. With `block`, reads in /// place and waits (for exports). Returns whether a read is still running. pub fn sync_source(&mut self, view: &Extent, block: bool) -> bool { - self.sync_source_with(view, block, &rustgis_data::query::Env::default()) + self.sync_source_with(view, None, block, &rustgis_data::query::Env::default()) } - /// Updates the source window, using the page when its definition query depends on it. - fn sync_source_with(&mut self, view: &Extent, block: bool, env: &rustgis_data::query::Env) -> bool { + /// Updates the source window, using the page when its definition query depends on it; `own` + /// is the view in map units, given when the map is in the source's own system. + fn sync_source_with( + &mut self, + view: &Extent, + own: Option<(&projection::Flat, Extent)>, + block: bool, + env: &rustgis_data::query::Env, + ) -> bool { let Some(src) = &mut self.source else { return false }; if !src.is_open() { // Opened once after a project loads; a failure is kept, not retried every frame. @@ -701,8 +708,8 @@ impl Layer { source::Polled::Idle | source::Polled::Waiting => {} } let Some(src) = &mut self.source else { return false }; - if let Some(e) = src.wanted(view) { - src.start(e, block); + if let Some(wanted) = src.wanted_in(view, own) { + src.start_wanted(wanted, block); match src.poll(block) { source::Polled::Done(window, batch) => { src.saw_unread_dates(&window.extent, &batch.unread_dates, &batch.rounded_dates); @@ -3049,6 +3056,21 @@ impl Map { /// Syncs drawing windows with the current page for source-side definition queries. pub fn sync_sources_with(&mut self, view: &Extent, scale: f64, block: bool, env: &rustgis_data::query::Env) -> bool { + self.sync_sources_in(view, None, scale, block, env) + } + + /// [`Map::sync_sources_with`], given the view in map units too (`own`, for an upright flat + /// view): a layer whose source is in the map's own system ([`Map::own_system`]) reads its + /// window in map units, which the source tests its features' own boxes against + /// ([`rustgis_data::source::Request::own`]), converting none. + pub fn sync_sources_in( + &mut self, + view: &Extent, + own: Option<&Extent>, + scale: f64, + block: bool, + env: &rustgis_data::query::Env, + ) -> bool { let mut pending = false; let held = self.held_by_group(scale); // Hidden resident layers share the budget too; toggling visibility cannot multiply it. @@ -3059,8 +3081,8 @@ impl Map { pending |= raster.poll_reload(); } if let Some(src) = &mut layer.source { - // Its features are held in longitude/latitude: a datum grid that arrived since - // they were read places them otherwise. + // A datum grid that arrived since its features were read places them otherwise in + // longitude/latitude, where a read finds them and the map draws them from. let grids = rustgis_data::raster::crs::grid_generation(); let new_grids = src.grids.is_some_and(|g| g != grids); src.grids = Some(grids); @@ -3089,12 +3111,33 @@ impl Map { } } } + let flat = self.flat(); + let system = own.and(Self::own_system_of(&flat, &self.projection)); for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) { - pending |= l.sync_source_with(view, block, env); + let in_own = own.filter(|_| system.is_some() && l.source.as_ref().map(|s| s.coord_crs()) == system); + pending |= l.sync_source_with(view, in_own.map(|o| (&flat, *o)), block, env); } pending } + /// The system the map's coordinates are in, when geometry there is drawn as it is + /// ([`projection::Flat::held`]): Web Mercator's on its map, and the one a map in a projected + /// system names ([`projection::Flat::direct_system`]). `None` for the globe and every other + /// map. + pub fn own_system(&self) -> Option { + Self::own_system_of(&self.flat(), &self.projection) + } + + fn own_system_of(flat: &projection::Flat, projection: &Projection) -> Option { + if projection.is_globe() { + return None; + } + match flat { + projection::Flat::Mercator => Some(rustgis_data::raster::Crs::WebMercator), + _ => flat.direct_system(), + } + } + /// Adds a raster layer; returns its id. pub fn add_raster(&mut self, name: impl Into, raster: RasterLayer) -> u32 { let id = self.next_id(); @@ -4434,7 +4477,7 @@ mod tests { page: Some(std::sync::Arc::new(rustgis_data::query::SeriesPage { feature_id: 1, name: number.to_string(), number })), ..Default::default() }; - l.sync_source_with(&view, true, &env); + l.sync_source_with(&view, None, true, &env); assert_eq!(l.dataset.features.len(), 1); assert_eq!(l.dataset.value(0, 0), &Value::Int(number as i64 - 1)); assert_eq!(l.drawn_rows_with(1e6, &env), [true]); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index a952b4f266..ec3a971bc6 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -14,10 +14,13 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; +use crate::projection::Flat; use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; -use rustgis_geom::Extent; +use rustgis_geom::{Coord, Extent}; use serde::{Deserialize, Serialize}; +#[cfg(test)] +mod own_tests; mod render_lod; mod window; pub(crate) use window::Query; @@ -704,11 +707,15 @@ pub struct Window { pub kept: usize, /// The read kept the definition query's matches: `matched` counts them. pub filtered: bool, + /// The same box in map units, when it was read in the map's own system, which is the + /// source's ([`SourceLayer::wanted_in`]): a later view is tested against it there. + pub own: Option, } /// A read in flight. struct Pending { extent: Extent, + own: Option, result: Mutex>>, still: Option, } @@ -825,7 +832,7 @@ pub enum Polled { /// A read is still running. Waiting, /// A read finished: install its features. - Done(Window, Batch), + Done(Window, Box), /// A read failed. Failed(String), } @@ -1132,7 +1139,7 @@ impl SourceLayer { // Opening a header alone doesn't establish that its payload is readable. Probe the // candidate, never the live source, before the caller commits the replacement. let handle = new.handle.as_deref().ok_or_else(|| named("the replacement source didn't open"))?; - let probe = handle.read(&Request { extent: None, limit: 1 }).map_err(|e| named(&e.to_string()))?; + let probe = handle.read(&Request { extent: None, limit: 1, own: None }).map_err(|e| named(&e.to_string()))?; if probe.features.is_empty() && probe.skipped > 0 { return Err(named(&format!( "no readable features found while checking the replacement ({} rows could not be read)", @@ -1796,19 +1803,61 @@ impl SourceLayer { /// The extent to read for a view (longitude/latitude), or `None` when the window serves it. pub fn wanted(&self, view: &Extent) -> Option { + self.wanted_in(view, None).map(|w| w.extent) + } + + /// The extent to read for a view, or `None` when the window serves it. `own` is the view in + /// map units with the map's projection, given when the map is in the source's own system: the + /// window is then read and kept in map units too, its longitude/latitude extent the place of + /// that box there. + pub fn wanted_in(&self, view: &Extent, own: Option<(&Flat, Extent)>) -> Option { let v = clamp_world(view); if v.is_empty() { return None; } + let own = own.filter(|(_, o)| !o.is_empty() && [o.min_x, o.min_y, o.max_x, o.max_y].iter().all(|n| n.is_finite())); + // A view past the world (zoomed out) reads the world, as in longitude/latitude: clamped to + // the world's box in map units, or read in longitude/latitude where the map can't place + // the world (a system for an area). + let whole = contains(&v, &Extent::WORLD_LONLAT); + let own = own.and_then(|(flat, o)| { + if !whole { + return Some((flat, o)); + } + let world = map_around(flat, &Extent::WORLD_LONLAT)?; + let clamped = + Extent::new(o.min_x.max(world.min_x), o.min_y.max(world.min_y), o.max_x.min(world.max_x), o.max_y.min(world.max_y)); + (!clamped.is_empty()).then_some((flat, clamped)) + }); + let all = self.info().map(|i| i.extent).filter(|e| !e.is_empty()); + // In map units, where the source says its features lie, with a margin for the curve + // between the places its edges are taken at. + let all_own = own.and_then(|(flat, _)| all.and_then(|a| map_around(flat, &a))).map(|a| a.padded(0.05, 0.0)); if let Some(w) = &self.window { - let all = self.info().map(|i| i.extent).filter(|e| !e.is_empty()); - // Everything has been read: nothing more to fetch, wherever the view goes. - if w.complete && all.is_some_and(|a| contains(&w.extent, &a)) { + // Everything has been read: nothing more to fetch, wherever the view goes. A window + // read in map units is compared there, as its longitude/latitude extent holds more + // than was read. + let everything = match w.own { + Some(read) => all_own.is_some_and(|a| contains(&read, &a)), + None => all.is_some_and(|a| contains(&w.extent, &a)), + }; + if w.complete && everything { return None; } // The window covers the view, and is complete or not much larger (a view zoomed well - // inside a sampled window reads again, for the detail the sample left out). - if contains(&w.extent, &v) && (w.complete || area(&v) * 6.0 > area(&w.extent)) { + // inside a sampled window reads again, for the detail the sample left out): in map + // units when the window and the view are both there, else in longitude/latitude. A + // window read in map units isn't compared in longitude/latitude, where its extent + // holds more than was read. + let compared = match (own, w.own) { + (Some((_, o)), Some(read)) => Some((o, read)), + (_, None) => Some((v, w.extent)), + (None, Some(_)) => None, + }; + if let Some((view, read)) = compared + && contains(&read, &view) + && (w.complete || area(&view) * 6.0 > area(&read)) + { return None; } } @@ -1818,15 +1867,32 @@ impl SourceLayer { if self.pending.is_some() { return None; } - Some(clamp_world(&v.padded(0.5, 0.0))) + // In map units, the read's longitude/latitude extent is the place of its box there, for + // a source that reads by that; a box the map can't take back is read as without one. + if let Some((flat, o)) = own { + let padded = o.padded(0.5, 0.0); + if let Some(lonlat) = lonlat_around(flat, &padded).map(|e| clamp_world(&e)).filter(|e| !e.is_empty()) { + return Some(Wanted { extent: lonlat, own: Some(padded) }); + } + } + Some(Wanted { extent: clamp_world(&v.padded(0.5, 0.0)), own: None }) } /// Starts reading an extent: on a background thread unless `block` (or in the browser). pub fn start(&mut self, extent: Extent, block: bool) { + self.start_wanted(Wanted { extent, own: None }, block); + } + + /// Starts reading what [`SourceLayer::wanted_in`] asked for: on a background thread unless + /// `block` (or in the browser). A box in map units goes to the source as one in its own + /// system ([`Request::own`]). + pub fn start_wanted(&mut self, wanted: Wanted, block: bool) { + let Wanted { extent, own } = wanted; self.ready_cache = None; let Some(h) = self.handle.clone() else { return }; let most = if h.remote().is_some() { REMOTE_VIEW_LIMIT } else { VIEW_LIMIT }; - let req = Request { extent: Some(extent), limit: if self.limit == 0 { most } else { self.limit } }; + let own_box = own.map(|o| (h.coord_crs(), o)); + let req = Request { extent: Some(extent), limit: if self.limit == 0 { most } else { self.limit }, own: own_box }; let budget = self.budget(); let projection = self.projection.clone().unwrap_or(crate::Projection::WebMercator); let estimate = self.estimated_row_bytes; @@ -1834,7 +1900,7 @@ impl SourceLayer { let fields = self.window_fields; let query = self.query.clone(); let still = rustgis_data::source::remote::current_still(); - let pending = Arc::new(Pending { extent, result: Mutex::new(None), still: still.clone() }); + let pending = Arc::new(Pending { extent, own, result: Mutex::new(None), still: still.clone() }); let p = pending.clone(); // A source by its web address: the read runs as its bytes land (on the desktop and in // the browser alike), fetching what it needs in rounds. @@ -1895,7 +1961,7 @@ impl SourceLayer { Err(e) => { self.saved_selection.clear(); self.error = Some(format!("couldn't start reading the layer: {e}")); - self.window = Some(Window { extent, complete: true, matched: 0, kept: 0, filtered: false }); + self.window = Some(Window { extent, complete: true, matched: 0, kept: 0, filtered: false, own }); } } return; @@ -1917,10 +1983,11 @@ impl SourceLayer { self.estimated_row_bytes = cache.mean_bytes; let filtered = cache.filtered; self.ready_cache = Some(cache); - let w = Window { extent: p.extent, complete: b.complete, matched: b.matched, kept: b.features.len(), filtered }; + let w = + Window { extent: p.extent, complete: b.complete, matched: b.matched, kept: b.features.len(), filtered, own: p.own }; self.window = Some(w); self.clear_error(); - return Polled::Done(w, b); + return Polled::Done(w, Box::new(b)); } Some(Err(e)) => { self.pending = None; @@ -1928,7 +1995,7 @@ impl SourceLayer { self.saved_selection.clear(); self.error = Some(e.clone()); // Not read again until the view moves past it. - self.window = Some(Window { extent: p.extent, complete: true, matched: 0, kept: 0, filtered: false }); + self.window = Some(Window { extent: p.extent, complete: true, matched: 0, kept: 0, filtered: false, own: p.own }); return Polled::Failed(e); } None if block && cfg!(not(target_arch = "wasm32")) && start.elapsed() < web_time::Duration::from_secs(60) => { @@ -1972,6 +2039,50 @@ fn contains(outer: &Extent, inner: &Extent) -> bool { && outer.max_y >= inner.max_y } +/// What a view wants read ([`SourceLayer::wanted_in`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Wanted { + /// Longitude/latitude. + pub extent: Extent, + /// The same box in map units, when the map is in the source's own system. + pub own: Option, +} + +/// Where a box in map units lies in longitude/latitude: its edges taken back, 16 places each, +/// reaching a pole inside it (a polar system); `None` when the map can't take a place back. +fn lonlat_around(flat: &Flat, e: &Extent) -> Option { + let mut out = Extent::EMPTY; + const N: usize = 16; + for i in 0..=N { + let t = i as f64 / N as f64; + let (x, y) = (e.min_x + t * e.width(), e.min_y + t * e.height()); + for c in [Coord::new(x, e.min_y), Coord::new(x, e.max_y), Coord::new(e.min_x, y), Coord::new(e.max_x, y)] { + out.expand(flat.inverse(c).filter(|p| p.is_finite())?); + } + } + for pole in [Coord::new(0.0, 90.0), Coord::new(0.0, -90.0)] { + if flat.forward(pole).is_some_and(|p| p.is_finite() && e.contains(p)) { + out = Extent::new(-180.0, out.min_y.min(pole.y), 180.0, out.max_y.max(pole.y)); + } + } + (!out.is_empty()).then_some(out) +} + +/// Where a longitude/latitude box lies in map units: its edges taken there, 16 places each; +/// `None` when the map can't place one of them. +fn map_around(flat: &Flat, e: &Extent) -> Option { + let mut out = Extent::EMPTY; + const N: usize = 16; + for i in 0..=N { + let t = i as f64 / N as f64; + let (x, y) = (e.min_x + t * e.width(), e.min_y + t * e.height()); + for c in [Coord::new(x, e.min_y), Coord::new(x, e.max_y), Coord::new(e.min_x, y), Coord::new(e.max_x, y)] { + out.expand(flat.forward(c).filter(|p| p.is_finite())?); + } + } + (!out.is_empty()).then_some(out) +} + fn clamp_world(e: &Extent) -> Extent { if e.is_empty() { return *e; diff --git a/crates/map/src/source/own_tests.rs b/crates/map/src/source/own_tests.rs new file mode 100644 index 0000000000..5ca1d92a3d --- /dev/null +++ b/crates/map/src/source/own_tests.rs @@ -0,0 +1,230 @@ +//! A map in a streamed source's own system reads its window in map units, which the source tests +//! its features' own boxes against ([`Request::own`]); every other map reads in +//! longitude/latitude, as before. + +use super::*; +use rustgis_data::raster::Crs; +use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + +/// A source that keeps the requests it is asked. +struct Recording { + inner: Box, + asked: Arc>>, +} + +impl FeatureSource for Recording { + fn info(&self) -> &SourceInfo { + self.inner.info() + } + fn coord_crs(&self) -> Crs { + self.inner.coord_crs() + } + fn read(&self, req: &Request) -> rustgis_data::Result { + self.asked.lock().unwrap().push(*req); + self.inner.read(req) + } +} + +fn utm31() -> Crs { + Crs::from_epsg(32631).unwrap() +} + +/// Lines in UTM zone 31N, as a FlatGeobuf: one at Paris, one from Paris to 1e9 m east (which has +/// no place in longitude/latitude), and one 400 km south. +fn lines() -> (Box, Arc>>) { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((451_500.0, 5_411_500.0), (1e9, 5_411_500.0)), vec![Value::Text("far east".into())]); + ds.push(line((451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), vec![Value::Text("south".into())]); + ds.held_in = utm31(); + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); + let inner = rustgis_data::source::open_bytes("lines.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone() }), asked) +} + +fn names(layer: &crate::Layer) -> Vec { + let mut out: Vec = layer + .dataset + .features + .iter() + .filter_map(|f| match f.attrs.first() { + Some(Value::Text(t)) => Some(t.clone()), + _ => None, + }) + .collect(); + out.sort(); + out +} + +/// Around Paris: in longitude/latitude, and the same place in UTM 31N. +fn around_paris() -> (Extent, Extent) { + (Extent::new(2.2, 48.75, 2.5, 48.95), Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0)) +} + +fn sync(map: &mut crate::Map, lonlat: &Extent, own: &Extent) { + map.sync_sources_in(lonlat, Some(own), 1000.0, true, &rustgis_data::query::Env::default()); +} + +#[test] +fn a_map_in_the_sources_own_system_reads_its_window_in_map_units() { + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + assert_eq!(map.own_system(), Some(utm31())); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &lonlat, &utm); + let read = asked.lock().unwrap().last().copied().unwrap(); + let padded = utm.padded(0.5, 0.0); + assert_eq!(read.own, Some((utm31(), padded))); + // Its longitude/latitude extent is where that box lies, for a source reading by it. + let e = read.extent.unwrap(); + assert!(e.min_x < 2.1 && e.max_x > 2.6 && e.min_y < 48.7 && e.max_y > 49.0, "{e:?}"); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, Some(padded)); + // Tested in its own system, the line past where longitude/latitude goes is read too. + assert_eq!(names(layer), ["far east", "paris"]); + // A view within the window, in map units, reads nothing more; one past it reads again. + let reads = asked.lock().unwrap().len(); + let nudged = Extent::new(utm.min_x + 5_000.0, utm.min_y, utm.max_x + 5_000.0, utm.max_y); + sync(&mut map, &lonlat, &nudged); + assert_eq!(asked.lock().unwrap().len(), reads); + let away = Extent::new(utm.min_x + 40_000.0, utm.min_y, utm.max_x + 40_000.0, utm.max_y); + sync(&mut map, &lonlat, &away); + assert_eq!(asked.lock().unwrap().len(), reads + 1); +} + +#[test] +fn every_other_map_reads_in_longitude_latitude_as_before() { + let (lonlat, utm) = around_paris(); + // Web Mercator, and a map in another projected system: the box in map units isn't the + // source's, so it isn't given. + for projection in [crate::Projection::WebMercator, crate::Projection::Custom("EPSG:2154".into())] { + let mut map = crate::Map::new("other"); + map.set_projection(projection.clone()); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &lonlat, &utm); + let read = asked.lock().unwrap().last().copied().unwrap(); + assert_eq!(read.own, None, "{projection:?}"); + assert_eq!(read.extent, Some(clamp_world(&lonlat.padded(0.5, 0.0))), "{projection:?}"); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, None, "{projection:?}"); + assert_eq!(names(layer), ["paris"], "{projection:?}"); + } + // Without the view in map units (the globe, a caller that has none), the same. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + map.sync_sources(&lonlat, 1000.0, true); + assert_eq!(asked.lock().unwrap().last().unwrap().own, None); +} + +/// A source of points in `crs`, as a FlatGeobuf. +fn points(crs: Crs, at: &[(f64, f64, &str)]) -> (Box, Arc>>) { + let mut ds = Dataset::new("points", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for (x, y, name) in at { + ds.push(Some(Geometry::Point(Coord::new(*x, *y))), vec![Value::Text((*name).into())]); + } + ds.held_in = crs; + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", crs).unwrap(); + let inner = rustgis_data::source::open_bytes("points.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone() }), asked) +} + +#[test] +fn a_window_read_in_map_units_holds_everything_only_when_its_box_does() { + // Around the South Pole in Antarctic Polar Stereographic, the window's longitude/latitude + // extent reaches every longitude and down to its corners' latitude: points 2,500 km out on + // every side are inside that, but outside the box read (2,000 km out at its edges' middles). + let polar = Crs::from_epsg(3031).unwrap(); + let mut map = crate::Map::new("polar"); + map.set_projection(crate::Projection::Custom("EPSG:3031".into())); + assert_eq!(map.own_system(), Some(polar)); + // A GeoJSON file read in place, whose extent is where its features are, not its box's corners. + let out = 2_500_000.0; + let at = [(0.0, 0.0, "pole"), (out, 0.0, "east"), (-out, 0.0, "west"), (0.0, out, "north"), (0.0, -out, "south")]; + let features: Vec = at + .iter() + .map(|(x, y, name)| { + format!(r#"{{"type":"Feature","properties":{{"name":"{name}"}},"geometry":{{"type":"Point","coordinates":[{x},{y}]}}}}"#) + }) + .collect(); + let path = std::env::temp_dir().join(format!("rustgis-own-polar-{}.geojson", std::process::id())); + std::fs::write( + &path, + format!( + r#"{{"type":"FeatureCollection","crs":{{"type":"name","properties":{{"name":"urn:ogc:def:crs:EPSG::3031"}}}},"features":[{}]}}"#, + features.join(",") + ), + ) + .unwrap(); + let inner = Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(&path, "points").unwrap()); + let asked = Arc::new(Mutex::new(Vec::new())); + let source: Box = Box::new(Recording { inner, asked: asked.clone() }); + let id = map.add_streamed("points", SourceLayer::from_path("points.fgb", None, source)); + let view = Extent::new(-1_000_000.0, -1_000_000.0, 1_000_000.0, 1_000_000.0); + let lonlat = Extent::new(-180.0, -90.0, 180.0, -80.0); + sync(&mut map, &lonlat, &view); + let layer = map.layer(id).unwrap(); + assert_eq!(names(layer), ["pole"]); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + // Panned onto it, it is read: the window didn't hold everything. + let reads = asked.lock().unwrap().len(); + let there = Extent::new(1_500_000.0, -1_000_000.0, 3_500_000.0, 1_000_000.0); + sync(&mut map, &lonlat, &there); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["east"]); +} + +#[test] +fn a_view_past_the_world_in_map_units_reads_no_more() { + // Points sampled on a map in their own system: zoomed out past the world, a view reaches only + // as far as the world does there, so zooming further out doesn't read the sample again. + for (projection, crs) in [(crate::Projection::WebMercator, Crs::WebMercator), (crate::Projection::Custom("EPSG:32631".into()), utm31())] + { + let mut map = crate::Map::new("world"); + map.set_projection(projection.clone()); + assert_eq!(map.own_system(), Some(crs)); + let (source, asked) = points(crs, &[(0.0, 0.0, "a"), (100_000.0, 0.0, "b"), (0.0, 100_000.0, "c")]); + let mut layer = SourceLayer::from_path("points.fgb", None, source); + layer.limit = 1; + let id = map.add_streamed("points", layer); + let world = Extent::new(-180.0, -85.0, 180.0, 85.0); + sync(&mut map, &world, &Extent::new(-4e7, -4e7, 4e7, 4e7)); + assert!(!map.layer(id).unwrap().source.as_ref().unwrap().window().unwrap().complete, "{projection:?}"); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &world, &Extent::new(-9e7, -9e7, 9e7, 9e7)); + sync(&mut map, &world, &Extent::new(-3e7, -1e7, 5e7, 2e7)); + assert_eq!(asked.lock().unwrap().len(), reads, "{projection:?}"); + } + // On Web Mercator's map, the world's box to 85°, padded by half. + let mut map = crate::Map::new("mercator"); + let (source, asked) = points(Crs::WebMercator, &[(0.0, 0.0, "a")]); + map.add_streamed("points", SourceLayer::from_path("points.fgb", None, source)); + sync(&mut map, &Extent::new(-180.0, -85.0, 180.0, 85.0), &Extent::new(-4e7, -4e7, 4e7, 4e7)); + let (_, read) = asked.lock().unwrap().last().unwrap().own.unwrap(); + let corner = rustgis_geom::lonlat_to_merc(Coord::new(180.0, 85.0)); + let (w, h) = (corner.x * 2.0, corner.y * 2.0); + for (got, want) in [(read.min_x, -w), (read.min_y, -h), (read.max_x, w), (read.max_y, h)] { + assert!((got - want).abs() < 1.0, "{read:?}"); + } +} + +#[test] +fn a_stated_extent_too_small_hides_nothing_in_view() { + // A source whose stated extent misses features (a GeoPackage's stale contents row, a line + // reaching past where longitude/latitude goes): the view is read as it is. + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + let east = Extent::new(utm.min_x + 100_000.0, utm.min_y, utm.max_x + 100_000.0, utm.max_y); + sync(&mut map, &lonlat, &east); + assert_eq!(asked.lock().unwrap().last().unwrap().own, Some((utm31(), east.padded(0.5, 0.0)))); +} diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index e618399ba2..bcced86262 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -425,7 +425,8 @@ mod tests { let scratch = Dataset::new("Polar", GeometryType::Polygon, vec![]); let expr = rustgis_data::query::parse(&query.text, &scratch).unwrap(); let error = - read_filtered(source.as_ref(), &Request { extent: None, limit: 1 }, usize::MAX, scratch, &expr, true, &query.env).unwrap_err(); + read_filtered(source.as_ref(), &Request { extent: None, limit: 1, own: None }, usize::MAX, scratch, &expr, true, &query.env) + .unwrap_err(); assert!(error.to_string().contains("Polar") && error.to_string().contains("2 ring(s) in 2 feature(s)"), "{error}"); // Text mentioning $area is ordinary text, not a request to measure the geometry. let text = Query { text: "'$area' = '$area'".into(), fields: vec![], env: Default::default() }; @@ -522,7 +523,7 @@ mod tests { let source = source(); let projection = crate::Projection::WebMercator; for estimate in [0, 100] { - let request = Request { extent: None, limit: 0 }; + let request = Request { extent: None, limit: 0, own: None }; let (batch, cache) = read(source.as_ref(), &request, 4096, &projection, estimate).unwrap(); assert!(batch.features.is_empty()); assert!(cache.projected.is_empty()); @@ -674,7 +675,7 @@ mod tests { #[test] fn one_feature_can_use_the_optional_display_reservation() { let source = source(); - let req = Request { extent: None, limit: 1 }; + let req = Request { extent: None, limit: 1, own: None }; let projection = crate::Projection::WebMercator; let (mut full, cache) = read_mode(source.as_ref(), &req, 1, &projection, 0, true, None, None).unwrap(); full.features.shrink_to_fit(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d01a44e011..534d741571 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -662,8 +662,9 @@ fn draw_page( { let view = View { width: fw, height: fh, pixels_per_point: 1.0, camera: cam, sky: false }; let lonlat = crate::view_lonlat(map, &view); + let own = crate::view_own(map, &view); let scale = map.ground_res_at(&cam) / rustgis_geom::PIXEL_M; - map.sync_sources_with(&lonlat, scale, true, env); + map.sync_sources_in(&lonlat, own.as_ref(), scale, true, env); let mut failed_source = None; let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &mut failed_source, env) else { *source_error = failed_source_error(map, failed_source); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0e7dd5e767..67f3d26b83 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2095,6 +2095,12 @@ fn blend_over(dst: &mut tiny_skia::PixmapMut, src: &Pixmap, x: i64, y: i64) { } } +/// What a view shows in map units, for streamed layers in the map's own system to read by +/// ([`Map::sync_sources_in`]); `None` on the globe. +pub fn view_own(map: &Map, view: &View) -> Option { + (!map.projection.is_globe()).then(|| view.camera.extent(view.width, view.height)) +} + /// The longitude/latitude extent a view shows (the whole world on the globe, or when the /// projection can't say). pub fn view_lonlat(map: &Map, view: &View) -> Extent { @@ -4036,10 +4042,11 @@ pub fn sync_tilted_view(map: &mut Map, view: &View) -> bool { /// running. fn sync_tilted(map: &mut Map, view: &View, bands: &[rustgis_map::camera::Band], block: bool, env: &Env) -> bool { let lonlat = view_lonlat(map, view); + let own = view_own(map, view); let mut pending = false; for b in bands { let scale = map.ground_res_at(&b.camera) / rustgis_geom::PIXEL_M; - pending |= map.sync_sources_with(&lonlat, scale, block, env); + pending |= map.sync_sources_in(&lonlat, own.as_ref(), scale, block, env); } pending } @@ -4410,7 +4417,7 @@ fn render_frame( let label_env = env.at_scale(Some(label_scale)); let data_pending = match labels_to { Labels::Tilted(..) | Labels::Shared => false, - _ => map.sync_sources_with(&view_lonlat(map, view), scale, full_res_rasters, env), + _ => map.sync_sources_in(&view_lonlat(map, view), view_own(map, view).as_ref(), scale, full_res_rasters, env), }; let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); let (flat, key) = (map.flat(), map.projection.code()); diff --git a/crates/tiles/src/embeddings.rs b/crates/tiles/src/embeddings.rs index bdfab9fa9a..8b519ba1a7 100644 --- a/crates/tiles/src/embeddings.rs +++ b/crates/tiles/src/embeddings.rs @@ -454,7 +454,7 @@ pub fn aef_place(url: &str) -> Option { pub type Found = (Vec, bool); fn aef_request(bbox: [f64; 4]) -> Request { - Request { extent: Some(Extent::new(bbox[0], bbox[1], bbox[2], bbox[3])), limit: MAX_INDEX_ROWS } + Request { extent: Some(Extent::new(bbox[0], bbox[1], bbox[2], bbox[3])), limit: MAX_INDEX_ROWS, own: None } } /// Finds AlphaEarth's tiles of a year in a box (longitude/latitude), reading the index in place. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9d867d3716..2d4a9b063f 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1436,7 +1436,11 @@ dataset. The layer reads features in view in the background as the map moves, us indexes: the GeoPackage R-tree, the FlatGeobuf packed R-tree, GeoParquet row-group bounding boxes, or a cached Shapefile R-tree built from the shapes' bounding boxes. When a local file's view holds more than 250,000 features (100,000 in the web app), the layer draws an -evenly spread sample of them and its tooltip in Layers says so: zoom in to see them all. Remote files have lower limits (see +evenly spread sample of them and its tooltip in Layers says so: zoom in to see them all. On a map +in the file's own coordinate system (a UTM file on a UTM map), the view is read in map units: each +feature's own bounding box is compared with it as the file holds it, with no coordinate +converted, and a feature reaching past where longitude/latitude goes is read too. On any other +map, each feature is placed in longitude/latitude to be compared. Remote files have lower limits (see [Data formats](data-formats.md)). Smaller files load whole; `layer.addData` with `"stream": true` or `false` overrides the choice. From e9fb9548502334c7f7d2f4d7adc796344943792a Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 14:56:11 +0100 Subject: [PATCH 09/11] Review fixes: a map-unit window reused only by a map-unit view and never taken for everything, PostGIS queried by the box in its own system, a non-number coordinate left out there too (#2032 C2f-4a) --- crates/data/src/source/mod.rs | 9 ++++- crates/data/src/source/own_box_tests.rs | 14 +++++++ crates/data/src/source/postgis.rs | 32 ++++++++++++++- crates/map/src/source.rs | 38 +++++++---------- crates/map/src/source/own_tests.rs | 54 +++++++++++++++++++++++++ docs/user-guide/data.md | 3 +- 6 files changed, 123 insertions(+), 27 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index b595c985d6..0646ddefae 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -985,10 +985,17 @@ impl Reproject { /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is /// within `req`. Given the request's box in those coordinates ([`Request::own`]), its own box /// is tested against it, converting nothing, so a geometry with no place in - /// longitude/latitude is kept too. Otherwise as [`Reproject::read`]: `None` when a coordinate + /// longitude/latitude is kept too (`None` for one with a coordinate that isn't a number). Otherwise as [`Reproject::read`]: `None` when a coordinate /// can't be converted to longitude/latitude, and its box there tested against the extent. pub(crate) fn place(&self, g: Geometry, req: &Request) -> Option { if let Some(own) = self.own_box(req) { + // A coordinate that isn't a number has no place here either: left out, as `read` + // leaves it out, for the reader to count. + let mut finite = true; + g.for_each_coord(|c| finite &= c.is_finite()); + if !finite { + return None; + } let inside = g.extent().intersects(&own); return Some(Fitted { geometry: g, inside }); } diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs index a7e5eab478..b583dd7f2a 100644 --- a/crates/data/src/source/own_box_tests.rs +++ b/crates/data/src/source/own_box_tests.rs @@ -138,3 +138,17 @@ fn a_box_in_its_own_system_is_tested_without_converting() { assert!(lonlat_source.place(Geometry::Point(Coord::new(2.3, 48.85)), &req).unwrap().inside); assert!(notes.is_empty(), "{notes:?}"); } + +#[test] +fn a_coordinate_that_isnt_a_number_is_left_out_in_its_own_system_too() { + let mut notes = Vec::new(); + let r = Reproject::from_crs(utm31(), &mut notes); + let (lonlat, utm) = around_paris(); + let req = Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }; + let missing = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(f64::NAN, 5_411_500.0)]]); + // Left out for the reader to count, as without the box. + assert!(r.place(missing.clone(), &req).is_none()); + assert!(r.place(missing, &Request { own: None, ..req }).is_none()); + let clean = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(452_000.0, 5_411_500.0)]]); + assert!(r.place(clean, &req).unwrap().inside); +} diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 7cc20742e7..aac1b57d46 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1684,6 +1684,12 @@ fn row_extent(r: &postgres::Row) -> Option { } } +/// The box a read narrows its query by when the request gives it in the table's own system +/// ([`Request::own`], [`Reproject::own_box`]); `None` otherwise, for the extent to be converted. +fn own_query_box(reproject: Option<&Reproject>, req: &Request) -> Option { + reproject.and_then(|r| r.own_box(req)) +} + impl FeatureSource for PostgisSource { fn info(&self) -> &SourceInfo { &self.info @@ -1699,7 +1705,13 @@ impl FeatureSource for PostgisSource { fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); let mut out = Batch::default(); - let native = req.extent.map(|e| self.lonlat_to_native(&e)).transpose()?; + // In the table's own system: the box the request gives there ([`Request::own`]), which + // a feature reaching past where longitude/latitude goes meets too, else its extent + // converted (refused when it can't be bounded). + let native = match own_query_box(self.reproject.as_ref(), req) { + Some(own) => Some(own), + None => req.extent.map(|e| self.lonlat_to_native(&e)).transpose()?, + }; if limit == 0 { return Ok(out); } @@ -1769,6 +1781,24 @@ impl FeatureSource for PostgisSource { mod tests { use super::*; + /// A read given its box in the table's own system narrows the query by it, not by its + /// longitude/latitude extent converted; one in another system, or a table in + /// longitude/latitude, goes by the extent as before. + #[test] + fn a_read_in_the_tables_own_system_queries_by_its_box() { + let utm = Crs::from_epsg(32631).unwrap(); + let own = Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0); + let lonlat = Some(Extent::new(2.2, 48.75, 2.5, 48.95)); + let table = Reproject::from_crs(utm, &mut Vec::new()); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), Some(own)); + let swiss = Crs::from_epsg(2056).unwrap(); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((swiss, own)) }), None); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: None }), None); + let geographic = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); + assert_eq!(own_query_box(Some(&geographic), &Request { extent: lonlat, limit: 10, own: Some((Crs::LonLat, own)) }), None); + assert_eq!(own_query_box(None, &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), None); + } + #[test] fn families_of_declared_types() { assert_eq!(family_of("MULTIPOLYGON"), Some(Family::Polygons)); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index ec3a971bc6..b75cf1db77 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1830,34 +1830,24 @@ impl SourceLayer { (!clamped.is_empty()).then_some((flat, clamped)) }); let all = self.info().map(|i| i.extent).filter(|e| !e.is_empty()); - // In map units, where the source says its features lie, with a margin for the curve - // between the places its edges are taken at. - let all_own = own.and_then(|(flat, _)| all.and_then(|a| map_around(flat, &a))).map(|a| a.padded(0.05, 0.0)); - if let Some(w) = &self.window { - // Everything has been read: nothing more to fetch, wherever the view goes. A window - // read in map units is compared there, as its longitude/latitude extent holds more - // than was read. - let everything = match w.own { - Some(read) => all_own.is_some_and(|a| contains(&read, &a)), - None => all.is_some_and(|a| contains(&w.extent, &a)), - }; - if w.complete && everything { + // A window is reused only by a view of the kind it was read for: one read in + // longitude/latitude lacks the features a read in map units also keeps (a place past + // where longitude/latitude goes), and one read in map units holds less than its + // longitude/latitude extent. + if let Some(w) = self.window.as_ref().filter(|w| w.own.is_some() == own.is_some()) { + // Everything has been read: nothing more to fetch, wherever the view goes. Only in + // longitude/latitude, where the source's extent bounds every feature it reads; in map + // units a feature with no place in longitude/latitude lies outside that extent. + if w.own.is_none() && w.complete && all.is_some_and(|a| contains(&w.extent, &a)) { return None; } // The window covers the view, and is complete or not much larger (a view zoomed well - // inside a sampled window reads again, for the detail the sample left out): in map - // units when the window and the view are both there, else in longitude/latitude. A - // window read in map units isn't compared in longitude/latitude, where its extent - // holds more than was read. - let compared = match (own, w.own) { - (Some((_, o)), Some(read)) => Some((o, read)), - (_, None) => Some((v, w.extent)), - (None, Some(_)) => None, + // inside a sampled window reads again, for the detail the sample left out). + let (view, read) = match (own, w.own) { + (Some((_, o)), Some(read)) => (o, read), + _ => (v, w.extent), }; - if let Some((view, read)) = compared - && contains(&read, &view) - && (w.complete || area(&view) * 6.0 > area(&read)) - { + if contains(&read, &view) && (w.complete || area(&view) * 6.0 > area(&read)) { return None; } } diff --git a/crates/map/src/source/own_tests.rs b/crates/map/src/source/own_tests.rs index 5ca1d92a3d..c756f3eb40 100644 --- a/crates/map/src/source/own_tests.rs +++ b/crates/map/src/source/own_tests.rs @@ -228,3 +228,57 @@ fn a_stated_extent_too_small_hides_nothing_in_view() { sync(&mut map, &lonlat, &east); assert_eq!(asked.lock().unwrap().last().unwrap().own, Some((utm31(), east.padded(0.5, 0.0)))); } + +/// Lines in UTM 31N as a FlatGeobuf: one at Paris and one from 1,200 km east to 1e9 m east, whose +/// far end has no place in longitude/latitude, so the file's stated extent covers Paris only. +fn far_lines() -> (Box, Arc>>) { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((1_200_000.0, 5_411_000.0), (1e9, 5_411_000.0)), vec![Value::Text("far".into())]); + ds.held_in = utm31(); + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); + let inner = rustgis_data::source::open_bytes("far.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone() }), asked) +} + +#[test] +fn a_complete_window_in_map_units_still_reads_a_feature_past_the_stated_extent() { + let (source, asked) = far_lines(); + let stated = source.info().extent; + assert!(stated.max_x < 3.0, "the stated extent covers Paris only: {stated:?}"); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let id = map.add_streamed("lines", SourceLayer::from_path("far.fgb", None, source)); + let (lonlat, utm) = around_paris(); + sync(&mut map, &lonlat, &utm); + let layer = map.layer(id).unwrap(); + assert_eq!(names(layer), ["paris"]); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + // Panned 750 km east, onto the far line: read, though the window read everything the stated + // extent holds. + let reads = asked.lock().unwrap().len(); + let east = Extent::new(1_190_000.0, 5_400_000.0, 1_220_000.0, 5_420_000.0); + sync(&mut map, &Extent::new(12.0, 48.5, 13.0, 49.5), &east); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["far"]); +} + +#[test] +fn a_window_read_in_longitude_latitude_isnt_reused_for_a_view_in_map_units() { + // Read first without the view in map units (the far line is left out there, as its far end + // has no place in longitude/latitude), then with it on the same map: read again, the far line + // with it. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + let (lonlat, utm) = around_paris(); + map.sync_sources(&lonlat, 1000.0, true); + assert_eq!(names(map.layer(id).unwrap()), ["paris"]); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &lonlat, &utm); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["far east", "paris"]); +} diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 2d4a9b063f..96a18872ff 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1439,7 +1439,8 @@ local file's view holds more than 250,000 features (100,000 in the web app), the evenly spread sample of them and its tooltip in Layers says so: zoom in to see them all. On a map in the file's own coordinate system (a UTM file on a UTM map), the view is read in map units: each feature's own bounding box is compared with it as the file holds it, with no coordinate -converted, and a feature reaching past where longitude/latitude goes is read too. On any other +converted, and a feature reaching past where longitude/latitude goes is read too (except from a +GeoJSON file, which leaves such a feature out when it opens, and says so). On any other map, each feature is placed in longitude/latitude to be compared. Remote files have lower limits (see [Data formats](data-formats.md)). Smaller files load whole; `layer.addData` with `"stream": true` or `false` overrides the choice. From 12cd8025b1b1902090adcd4b9b810257aff8f36c Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 15:36:20 +0100 Subject: [PATCH 10/11] Review fixes: map-unit windows only for sources that read by the box, decided once the source is open, kept in map units where the map can't place the view (#2032 C2f-4a) --- crates/data/src/source/fgb.rs | 4 ++ crates/data/src/source/geojson.rs | 4 ++ crates/data/src/source/gpkg.rs | 4 ++ crates/data/src/source/gpkg_mem.rs | 4 ++ crates/data/src/source/mod.rs | 13 +++++ crates/data/src/source/parquet.rs | 4 ++ crates/data/src/source/postgis.rs | 4 ++ crates/data/src/source/shp.rs | 4 ++ crates/map/src/lib.rs | 32 +++++++---- crates/map/src/source.rs | 20 +++++-- crates/map/src/source/own_tests.rs | 89 ++++++++++++++++++++++++++++-- 11 files changed, 160 insertions(+), 22 deletions(-) diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 8a078203ee..58a58126e9 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -829,6 +829,10 @@ impl FeatureSource for FgbSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 7bf789306c..5656a03301 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -317,6 +317,10 @@ impl FeatureSource for GeoJsonSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index 3ef9b52d0d..bef6c18542 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -434,6 +434,10 @@ impl FeatureSource for GpkgSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index d1611f26d2..3475675f8a 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -336,6 +336,10 @@ impl FeatureSource for GpkgMemSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 0646ddefae..8fc396b9cd 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -422,6 +422,15 @@ pub trait FeatureSource: Send + Sync { fn coord_crs(&self) -> crate::raster::Crs { crate::raster::Crs::LonLat } + + /// Whether a read given its box in the source's own system ([`Request::own`]) tests its + /// features against that box (a file read in place, PostGIS), so a map in that system keeps + /// its window in map units for it. A source that reads by the longitude/latitude extent + /// whatever it is given (another database, a service, a converted copy) says no: its window is + /// kept in longitude/latitude, as it reads. + fn reads_own_box(&self) -> bool { + false + } /// The encoding the source's text values are read in, for the notice of those that aren't /// valid in it ([`not_utf8_note`]). fn text_encoding(&self) -> &'static str { @@ -684,6 +693,10 @@ impl FeatureSource for Fetching { self.0.coord_crs() } + fn reads_own_box(&self) -> bool { + self.0.reads_own_box() + } + fn lost_to_crs(&self) -> bool { self.0.lost_to_crs() } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 3bdf676a65..af436f6d38 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -487,6 +487,10 @@ impl FeatureSource for ParquetSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index aac1b57d46..99b093fba7 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1697,6 +1697,10 @@ impl FeatureSource for PostgisSource { /// The table's own system when RustGIS converts it itself, else longitude/latitude, which /// the server gives. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> Crs { self.held } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 65291d226b..9fbbb9130a 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -237,6 +237,10 @@ impl FeatureSource for ShpSource { } /// Its own system, in which it gives its features as the file holds them. + fn reads_own_box(&self) -> bool { + true + } + fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 513e9ea915..cda4c65c55 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -643,15 +643,11 @@ impl Layer { self.sync_source_with(view, None, block, &rustgis_data::query::Env::default()) } - /// Updates the source window, using the page when its definition query depends on it; `own` - /// is the view in map units, given when the map is in the source's own system. - fn sync_source_with( - &mut self, - view: &Extent, - own: Option<(&projection::Flat, Extent)>, - block: bool, - env: &rustgis_data::query::Env, - ) -> bool { + /// Updates the source window, using the page when its definition query depends on it. `own` + /// is the view in map units with the map's system: taken when the source, once open, is in + /// that system and tests its features against a box there + /// (`FeatureSource::reads_own_box`). + fn sync_source_with(&mut self, view: &Extent, own: Option<&MapView<'_>>, block: bool, env: &rustgis_data::query::Env) -> bool { let Some(src) = &mut self.source else { return false }; if !src.is_open() { // Opened once after a project loads; a failure is kept, not retried every frame. @@ -708,6 +704,9 @@ impl Layer { source::Polled::Idle | source::Polled::Waiting => {} } let Some(src) = &mut self.source else { return false }; + // Decided now that the source is open: one opened in this very call (an export waiting for + // it) reads in map units from its first window. + let own = own.filter(|m| src.reads_own_box() && src.coord_crs() == m.system).map(|m| (m.flat, m.view)); if let Some(wanted) = src.wanted_in(view, own) { src.start_wanted(wanted, block); match src.poll(block) { @@ -3112,10 +3111,11 @@ impl Map { } } let flat = self.flat(); - let system = own.and(Self::own_system_of(&flat, &self.projection)); + // The view in map units with the map's system, for each layer to take once its source is + // open and says its own system ([`Layer::sync_source_with`]). + let own = own.and_then(|o| Self::own_system_of(&flat, &self.projection).map(|system| MapView { flat: &flat, system, view: *o })); for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) { - let in_own = own.filter(|_| system.is_some() && l.source.as_ref().map(|s| s.coord_crs()) == system); - pending |= l.sync_source_with(view, in_own.map(|o| (&flat, *o)), block, env); + pending |= l.sync_source_with(view, own.as_ref(), block, env); } pending } @@ -3785,6 +3785,14 @@ impl LonLatCopy { } } +/// A view in map units, with the projection and the system the map's coordinates are in +/// ([`Map::own_system`]), for a streamed layer in that system to read by +/// ([`Map::sync_sources_in`]). +struct MapView<'a> { + flat: &'a projection::Flat, + system: Crs, + view: Extent, +} #[cfg(test)] mod tests { use super::*; diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index b75cf1db77..cdd52fe26a 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1179,6 +1179,12 @@ impl SourceLayer { self.handle.as_ref().map_or(rustgis_data::raster::Crs::LonLat, |h| h.coord_crs()) } + /// Whether its source tests its features against a box in its own system + /// ([`FeatureSource::reads_own_box`]); no until it is open. + pub fn reads_own_box(&self) -> bool { + self.handle.as_ref().is_some_and(|h| h.reads_own_box()) + } + /// A source that can be read whole a chunk at a time, for an export. pub fn visit_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() @@ -1857,15 +1863,17 @@ impl SourceLayer { if self.pending.is_some() { return None; } - // In map units, the read's longitude/latitude extent is the place of its box there, for - // a source that reads by that; a box the map can't take back is read as without one. + let lonlat = clamp_world(&v.padded(0.5, 0.0)); + // In map units, the read's longitude/latitude extent is the place of its box there. Where + // the map can't take that box back (a regional system zoomed far out), it is the view's, + // as without one; the window is still kept in map units, so the same view doesn't read + // again. if let Some((flat, o)) = own { let padded = o.padded(0.5, 0.0); - if let Some(lonlat) = lonlat_around(flat, &padded).map(|e| clamp_world(&e)).filter(|e| !e.is_empty()) { - return Some(Wanted { extent: lonlat, own: Some(padded) }); - } + let extent = lonlat_around(flat, &padded).map(|e| clamp_world(&e)).filter(|e| !e.is_empty()).unwrap_or(lonlat); + return Some(Wanted { extent, own: Some(padded) }); } - Some(Wanted { extent: clamp_world(&v.padded(0.5, 0.0)), own: None }) + Some(Wanted { extent: lonlat, own: None }) } /// Starts reading an extent: on a background thread unless `block` (or in the browser). diff --git a/crates/map/src/source/own_tests.rs b/crates/map/src/source/own_tests.rs index c756f3eb40..a744b28de9 100644 --- a/crates/map/src/source/own_tests.rs +++ b/crates/map/src/source/own_tests.rs @@ -10,6 +10,9 @@ use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; struct Recording { inner: Box, asked: Arc>>, + /// Whether it says it reads by a box in its own system, as its inner source does, or not + /// (as a database read by its longitude/latitude extent). + own_box: bool, } impl FeatureSource for Recording { @@ -19,6 +22,9 @@ impl FeatureSource for Recording { fn coord_crs(&self) -> Crs { self.inner.coord_crs() } + fn reads_own_box(&self) -> bool { + self.own_box && self.inner.reads_own_box() + } fn read(&self, req: &Request) -> rustgis_data::Result { self.asked.lock().unwrap().push(*req); self.inner.read(req) @@ -41,7 +47,7 @@ fn lines() -> (Box, Arc>>) { let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); let inner = rustgis_data::source::open_bytes("lines.fgb", bytes, None).unwrap(); let asked = Arc::new(Mutex::new(Vec::new())); - (Box::new(Recording { inner, asked: asked.clone() }), asked) + (Box::new(Recording { inner, asked: asked.clone(), own_box: true }), asked) } fn names(layer: &crate::Layer) -> Vec { @@ -133,7 +139,7 @@ fn points(crs: Crs, at: &[(f64, f64, &str)]) -> (Box, Arc = Box::new(Recording { inner, asked: asked.clone() }); + let source: Box = Box::new(Recording { inner, asked: asked.clone(), own_box: true }); let id = map.add_streamed("points", SourceLayer::from_path("points.fgb", None, source)); let view = Extent::new(-1_000_000.0, -1_000_000.0, 1_000_000.0, 1_000_000.0); let lonlat = Extent::new(-180.0, -90.0, 180.0, -80.0); @@ -240,7 +246,7 @@ fn far_lines() -> (Box, Arc>>) { let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); let inner = rustgis_data::source::open_bytes("far.fgb", bytes, None).unwrap(); let asked = Arc::new(Mutex::new(Vec::new())); - (Box::new(Recording { inner, asked: asked.clone() }), asked) + (Box::new(Recording { inner, asked: asked.clone(), own_box: true }), asked) } #[test] @@ -282,3 +288,78 @@ fn a_window_read_in_longitude_latitude_isnt_reused_for_a_view_in_map_units() { assert_eq!(asked.lock().unwrap().len(), reads + 1); assert_eq!(names(map.layer(id).unwrap()), ["far east", "paris"]); } + +#[test] +fn a_source_that_reads_by_longitude_latitude_keeps_its_window_there() { + // A source in the map's system that reads by the longitude/latitude extent whatever it is given + // (another database, a service) gets no box in map units, and its window is kept in + // longitude/latitude, where "everything read" holds and panning past it reads nothing more. + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + let source: Box = { + let inner = source; + Box::new(Recording { inner, asked: asked.clone(), own_box: false }) + }; + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &Extent::new(-6.0, 41.0, 10.0, 52.0), &Extent::new(-500_000.0, 4_500_000.0, 1_500_000.0, 5_800_000.0)); + let read = asked.lock().unwrap().last().copied().unwrap(); + assert_eq!(read.own, None); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, None); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &lonlat, &utm); + sync(&mut map, &Extent::new(2.0, 44.5, 3.0, 45.5), &Extent::new(420_000.0, 4_930_000.0, 500_000.0, 5_040_000.0)); + assert_eq!(asked.lock().unwrap().len(), reads); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_layer_opened_as_it_syncs_reads_in_map_units_from_its_first_window() { + // A layer of a project just opened has no source yet: opened in the sync that waits for it (an + // export), its first read is in map units already, so no second read follows. + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + ds.push( + Some(Geometry::Line(vec![vec![Coord::new(451_000.0, 5_411_000.0), Coord::new(452_000.0, 5_412_000.0)]])), + vec![Value::Text("paris".into())], + ); + ds.held_in = utm31(); + let path = std::env::temp_dir().join(format!("rustgis-own-opened-{}.fgb", std::process::id())); + rustgis_data::io::write_path_in(&ds, &path, utm31()).unwrap(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let src = SourceLayer { path: Some(path.display().to_string()), ..SourceLayer::default() }; + let id = map.add_streamed("lines", src); + assert!(!map.layer(id).unwrap().source.as_ref().unwrap().is_open()); + let (lonlat, utm) = around_paris(); + sync(&mut map, &lonlat, &utm); + let window = *map.layer(id).unwrap().source.as_ref().unwrap().window().unwrap(); + assert_eq!(window.own, Some(utm.padded(0.5, 0.0))); + assert_eq!(names(map.layer(id).unwrap()), ["paris"]); + let _ = std::fs::remove_file(path); +} + +#[test] +fn a_view_the_map_cant_place_reads_once() { + // On a UTM map, a view the map can't take back to longitude/latitude: read once, by the + // view's longitude/latitude, the window kept in map units, so the same view reads nothing more. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + // A view whose longitude/latitude is known, but whose padded box reaches past where the + // system goes, so the map can't take that box back. + let (lonlat, _) = around_paris(); + let edge = Extent::new(1e8, 1e8, 1.1e8, 1.1e8); + sync(&mut map, &lonlat, &edge); + let reads = asked.lock().unwrap().len(); + let first = asked.lock().unwrap().last().copied().unwrap(); + assert!(first.own.is_some()); + assert_eq!(first.extent, Some(lonlat.padded(0.5, 0.0)), "read by the view's longitude/latitude"); + for _ in 0..3 { + sync(&mut map, &lonlat, &edge); + } + assert_eq!(asked.lock().unwrap().len(), reads); +} From 5cdcd4b7a6e07d7ff244099041df6ef564b00513 Mon Sep 17 00:00:00 2001 From: strebdom Date: Mon, 23 Nov 2026 16:12:55 +0100 Subject: [PATCH 11/11] Review fixes: unread-value tallies kept apart by a window's box in map units, docs back on coord_crs, the unused wanted dropped (#2032 C2f-4a) --- crates/data/src/source/fgb.rs | 2 +- crates/data/src/source/geojson.rs | 2 +- crates/data/src/source/gpkg.rs | 2 +- crates/data/src/source/gpkg_mem.rs | 2 +- crates/data/src/source/mod.rs | 11 +++--- crates/data/src/source/parquet.rs | 2 +- crates/data/src/source/postgis.rs | 4 +- crates/data/src/source/shp.rs | 2 +- crates/map/src/lib.rs | 12 +++--- crates/map/src/source.rs | 59 +++++++++++++++++++++++------- crates/map/src/source/own_tests.rs | 4 +- 11 files changed, 67 insertions(+), 35 deletions(-) diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 58a58126e9..6ebb37d5f3 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -828,11 +828,11 @@ impl FeatureSource for FgbSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 5656a03301..ff48277804 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -316,11 +316,11 @@ impl FeatureSource for GeoJsonSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index bef6c18542..a6f86f2dbc 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -433,11 +433,11 @@ impl FeatureSource for GpkgSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index 3475675f8a..48a9ac6df0 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -335,11 +335,11 @@ impl FeatureSource for GpkgMemSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 8fc396b9cd..2ab9f63b00 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -978,7 +978,7 @@ impl Reproject { /// A geometry as the file holds it, kept in the source's own coordinates /// ([`Reproject::crs`]), with its box in longitude/latitude for a request's extent to test - /// ([`Placed::in_request`]); `None` when a coordinate can't be converted to longitude/latitude, + /// ([`Reproject::place`]); `None` when a coordinate can't be converted to longitude/latitude, /// as a feature that can't be placed is left out. Each coordinate is converted to be checked, /// none is kept converted. pub(crate) fn read(&self, g: Geometry) -> Option { @@ -998,15 +998,14 @@ impl Reproject { /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is /// within `req`. Given the request's box in those coordinates ([`Request::own`]), its own box /// is tested against it, converting nothing, so a geometry with no place in - /// longitude/latitude is kept too (`None` for one with a coordinate that isn't a number). Otherwise as [`Reproject::read`]: `None` when a coordinate - /// can't be converted to longitude/latitude, and its box there tested against the extent. + /// longitude/latitude is kept too (`None` for one with a coordinate that isn't a number). + /// Otherwise as [`Reproject::read`]: `None` when a coordinate can't be converted to + /// longitude/latitude, and its box there tested against the extent. pub(crate) fn place(&self, g: Geometry, req: &Request) -> Option { if let Some(own) = self.own_box(req) { // A coordinate that isn't a number has no place here either: left out, as `read` // leaves it out, for the reader to count. - let mut finite = true; - g.for_each_coord(|c| finite &= c.is_finite()); - if !finite { + if !g.is_finite() { return None; } let inside = g.extent().intersects(&own); diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index af436f6d38..94fdb484e5 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -486,11 +486,11 @@ impl FeatureSource for ParquetSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 99b093fba7..ffe85406f1 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1695,12 +1695,12 @@ impl FeatureSource for PostgisSource { &self.info } - /// The table's own system when RustGIS converts it itself, else longitude/latitude, which - /// the server gives. fn reads_own_box(&self) -> bool { true } + /// The table's own system when RustGIS converts it itself, else longitude/latitude, which + /// the server gives. fn coord_crs(&self) -> Crs { self.held } diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 9fbbb9130a..3cdd3533f3 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -236,11 +236,11 @@ impl FeatureSource for ShpSource { &self.info } - /// Its own system, in which it gives its features as the file holds them. fn reads_own_box(&self) -> bool { true } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() } diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index cda4c65c55..064a10162d 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -694,9 +694,9 @@ impl Layer { // previous view's features. match src.poll(block) { source::Polled::Done(window, batch) => { - src.saw_unread_dates(&window.extent, &batch.unread_dates, &batch.rounded_dates); - src.saw_null_text(&window.extent, &batch.null_text); - src.saw_not_utf8(&window.extent, &batch.not_utf8); + src.saw_unread_dates(&window, &batch.unread_dates, &batch.rounded_dates); + src.saw_null_text(&window, &batch.null_text); + src.saw_not_utf8(&window, &batch.not_utf8); src.saw_read_notes(&batch.notes); self.install(batch.features) } @@ -711,9 +711,9 @@ impl Layer { src.start_wanted(wanted, block); match src.poll(block) { source::Polled::Done(window, batch) => { - src.saw_unread_dates(&window.extent, &batch.unread_dates, &batch.rounded_dates); - src.saw_null_text(&window.extent, &batch.null_text); - src.saw_not_utf8(&window.extent, &batch.not_utf8); + src.saw_unread_dates(&window, &batch.unread_dates, &batch.rounded_dates); + src.saw_null_text(&window, &batch.null_text); + src.saw_not_utf8(&window, &batch.not_utf8); src.saw_read_notes(&batch.notes); self.install(batch.features) } diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index cdd52fe26a..9f36d463b7 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -780,11 +780,33 @@ pub(crate) fn another_frame() { /// How many windows a [`Tally`] keeps apart. const WINDOWS_COUNTED: usize = 64; +/// Which read a batch's counts are of ([`SourceLayer::saw_unread_dates`]): its window's +/// longitude/latitude extent and, for one read in map units, its box there. Two windows in map +/// units can share a longitude/latitude extent (both read by the view's where the map can't take +/// their boxes back), so the box tells them apart. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WindowKey { + extent: Extent, + own: Option, +} + +impl From<&Extent> for WindowKey { + fn from(extent: &Extent) -> Self { + WindowKey { extent: *extent, own: None } + } +} + +impl From<&Window> for WindowKey { + fn from(w: &Window) -> Self { + WindowKey { extent: w.extent, own: w.own } + } +} + /// What view reads found, counted for each field by its position, kept for each window read: a /// window read again replaces its counts instead of adding to them. #[derive(Clone, Default)] struct Tally { - windows: Vec<(Extent, Vec)>, + windows: Vec<(WindowKey, Vec)>, /// Counts of windows past [`WINDOWS_COUNTED`], added up as they come. // ponytail: past 64 windows between two notice passes a window read again adds up as before; // keep rows' identity in `Batch` to count exactly. @@ -792,8 +814,9 @@ struct Tally { } impl Tally { - fn saw(&mut self, window: &Extent, counts: &[usize]) { - let at = self.windows.iter().position(|(w, _)| w == window); + fn saw(&mut self, window: impl Into, counts: &[usize]) { + let window = window.into(); + let at = self.windows.iter().position(|(w, _)| *w == window); if counts.iter().all(|n| *n == 0) { if let Some(at) = at { self.windows.remove(at); @@ -801,7 +824,7 @@ impl Tally { } else if let Some((_, kept)) = at.and_then(|at| self.windows.get_mut(at)) { *kept = counts.to_vec(); } else if self.windows.len() < WINDOWS_COUNTED { - self.windows.push((*window, counts.to_vec())); + self.windows.push((window, counts.to_vec())); } else { rustgis_data::source::add_unread_dates(&mut self.rest, counts); } @@ -846,10 +869,11 @@ impl SourceLayer { /// [`SourceLayer::take_unread_dates`] says it. Once said, later reads aren't counted: they /// read the same features again, and the notice says Load All Features counts them all. /// Each kind is counted until its own notice is said, so saying one doesn't silence the other. - /// `window` is the extent the batch was read for: reading it again replaces its counts, so the - /// same rows aren't counted twice. Two different windows that overlap still count the rows + /// `window` is what the batch was read for ([`WindowKey`]: its extent, and its box in map + /// units): reading it again replaces its counts, so the same rows aren't counted twice. Two different windows that overlap still count the rows /// they share twice; the notice says "so far" and Load All Features counts them all. - pub fn saw_unread_dates(&mut self, window: &Extent, unread: &[usize], rounded: &[usize]) { + pub fn saw_unread_dates(&mut self, window: impl Into, unread: &[usize], rounded: &[usize]) { + let window = window.into(); if !self.unread_dates_said { self.unread_dates.saw(window, unread); } @@ -877,7 +901,7 @@ impl SourceLayer { /// Keeps what view reads found of text values `` read as null, until /// [`SourceLayer::take_null_text`] says it, as [`SourceLayer::saw_unread_dates`] does for dates. - pub fn saw_null_text(&mut self, window: &Extent, counts: &[usize]) { + pub fn saw_null_text(&mut self, window: impl Into, counts: &[usize]) { if !self.null_text_said { self.null_text.saw(window, counts); } @@ -894,7 +918,7 @@ impl SourceLayer { /// Keeps what view reads found of text values that aren't UTF-8, until /// [`SourceLayer::take_not_utf8`] says it, as [`SourceLayer::saw_unread_dates`] does for dates. - pub fn saw_not_utf8(&mut self, window: &Extent, counts: &[usize]) { + pub fn saw_not_utf8(&mut self, window: impl Into, counts: &[usize]) { if !self.not_utf8_said { let encoding = self.handle.as_ref().map_or("UTF-8", |h| h.text_encoding()); // Counts of another encoding are of another opening's text: they aren't added to these. @@ -1807,11 +1831,6 @@ impl SourceLayer { self.saved_selection.clear(); } - /// The extent to read for a view (longitude/latitude), or `None` when the window serves it. - pub fn wanted(&self, view: &Extent) -> Option { - self.wanted_in(view, None).map(|w| w.extent) - } - /// The extent to read for a view, or `None` when the window serves it. `own` is the view in /// map units with the map's projection, given when the map is in the source's own system: the /// window is then read and kept in map units too, its longitude/latitude extent the place of @@ -2333,6 +2352,18 @@ mod tests { assert_eq!(tally.total(), Some(vec![1])); tally.saw(&b, &[0]); assert_eq!(tally.total(), None); + // Two windows in map units read by the same longitude/latitude extent (where the map can't + // take their boxes back) are told apart by their boxes: the second's clean read leaves the + // first's counts. + let mut apart = Tally::default(); + let first = + super::Window { extent: a, complete: true, matched: 1, kept: 1, filtered: false, own: Some(Extent::new(0.0, 0.0, 1.0, 1.0)) }; + let second = super::Window { own: Some(Extent::new(5.0, 5.0, 6.0, 6.0)), ..first }; + apart.saw(&first, &[1]); + apart.saw(&second, &[0]); + assert_eq!(apart.total(), Some(vec![1])); + apart.saw(&first, &[0]); + assert_eq!(apart.total(), None); let nan = Extent::new(f64::NAN, 0.0, 1.0, 1.0); for _ in 0..2 * WINDOWS_COUNTED { tally.saw(&nan, &[1]); diff --git a/crates/map/src/source/own_tests.rs b/crates/map/src/source/own_tests.rs index a744b28de9..307da7e66a 100644 --- a/crates/map/src/source/own_tests.rs +++ b/crates/map/src/source/own_tests.rs @@ -229,10 +229,12 @@ fn a_stated_extent_too_small_hides_nothing_in_view() { let mut map = crate::Map::new("utm"); map.set_projection(crate::Projection::Custom("EPSG:32631".into())); let (source, asked) = lines(); - map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); let east = Extent::new(utm.min_x + 100_000.0, utm.min_y, utm.max_x + 100_000.0, utm.max_y); sync(&mut map, &lonlat, &east); assert_eq!(asked.lock().unwrap().last().unwrap().own, Some((utm31(), east.padded(0.5, 0.0)))); + // 100 km east of Paris only the line reaching 1e9 m east passes, past the stated extent: read. + assert_eq!(names(map.layer(id).unwrap()), ["far east"]); } /// Lines in UTM 31N as a FlatGeobuf: one at Paris and one from 1,200 km east to 1e9 m east, whose