From 70ae05b8037a2b529fb0b4f95cc0c2d836933329 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 13:26:01 +0100 Subject: [PATCH 01/12] fix(data): a streamed Shapefile keeps a shape whose coordinates aren't numbers without its geometry, as a whole read does --- crates/data/src/source/shp.rs | 62 +++++++++++++++------ crates/data/src/source/shp/tests.rs | 86 ++++++++++++++++++++--------- crates/engine/src/tests.rs | 2 +- 3 files changed, 104 insertions(+), 46 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 913efb1eb1..0bddb4cd3c 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -312,6 +312,7 @@ impl ShpSource { let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); let mut deleted = 0usize; + let mut kept_no_number = 0usize; // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing // their directory or the complete feature collection in memory. @@ -320,6 +321,7 @@ impl ShpSource { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); let mut each = |i: u32, place: Place| -> Result<()> { crate::progress::step(1)?; + let mut no_number = false; if u64::from(place.len) > MAX_RECORD { skipped += 1; return Ok(()); @@ -331,14 +333,15 @@ impl ShpSource { return Ok(()); } let geometry = match parse_shape(&buf) { - // A coordinate that isn't a number (NaN or infinite) has no place: the record is - // left out and counted, as one that can't be converted (#1985). One under a stored - // box the index takes ([`index::usable`]) is counted apart too, as the index framed - // it by that box; a backwards one it can't frame, and counts as unboxed instead. + // A coordinate that isn't a number (NaN or infinite) has no place: the record keeps + // its attributes without its geometry, as a whole read keeps it (#1985, #2032 + // C2f), and is counted where it is read. One under a stored box the index takes + // ([`index::usable`]) is counted apart too, as the index framed it by that box; a + // backwards one it can't frame, and counts as unboxed instead. Ok(Some(g)) if !g.is_finite() => { - skipped += 1; boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); - return Ok(()); + no_number = true; + None } Ok(Some(g)) => { // A box the index took as stored (one in order) that misses part of the shape. @@ -382,6 +385,7 @@ impl ShpSource { } else { vec![Value::Null; self.table.columns.len()] }; + kept_no_number += usize::from(no_number); chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs }) }; let (matched, complete) = match numbered { @@ -402,6 +406,7 @@ impl ShpSource { null_text, notes: boxed_off_note(boxed_off, false, late) .into_iter() + .chain(kept_no_number_note(kept_no_number, false)) .chain(deleted_note(deleted, false).map(crate::loss::Note::from)) .chain(nonfinite_note(&self.info.fields, &nonfinite, false)) .collect(), @@ -451,6 +456,7 @@ impl FeatureSource for ShpSource { let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); let mut deleted = 0usize; + let mut kept_no_number = 0usize; // An extent the file's system couldn't bound (#1925) has no boxes for the index to sample // by: every record is visited, tested, and the matches sampled as they come. let late = req.extent.is_some() && bounds.is_none(); @@ -462,6 +468,7 @@ impl FeatureSource for ShpSource { if late { crate::progress::step(1)?; } + let mut no_number = false; if u64::from(place.len) > MAX_RECORD { skipped += 1; return Ok(()); @@ -472,14 +479,15 @@ impl FeatureSource for ShpSource { return Ok(()); } let geometry = match parse_shape(&buf) { - // A coordinate that isn't a number (NaN or infinite) has no place: the record is - // left out and counted, as one that can't be converted (#1985). One under a stored - // box the index takes ([`index::usable`]) is counted apart too, as the index framed - // it by that box; a backwards one it can't frame, and counts as unboxed instead. + // A coordinate that isn't a number (NaN or infinite) has no place: the record keeps + // its attributes without its geometry, as a whole read keeps it (#1985, #2032 + // C2f), and is counted where it is read. One under a stored box the index takes + // ([`index::usable`]) is counted apart too, as the index framed it by that box; a + // backwards one it can't frame, and counts as unboxed instead. Ok(Some(g)) if !g.is_finite() => { - skipped += 1; boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); - return Ok(()); + no_number = true; + None } Ok(Some(g)) => match self.reproject.place(g, req) { Some(placed) => Some(placed), @@ -522,9 +530,11 @@ impl FeatureSource for ShpSource { vec![Value::Null; self.table.columns.len()] }; let f = Feature { id: u64::from(i) + 1, geometry, attrs }; + // A late read is one by area, which gives no feature without geometry. if late { sample.keep(f) } else { + kept_no_number += usize::from(no_number); features.push(f) } Ok(()) @@ -548,6 +558,7 @@ impl FeatureSource for ShpSource { // visits the whole layer, so its count is of the layer. notes: boxed_off_note(boxed_off, !late && !complete, late) .into_iter() + .chain(kept_no_number_note(kept_no_number, !late && !complete)) .chain(deleted_note(deleted, !late && !complete).map(crate::loss::Note::from)) // The values a late read decodes are of the records its sample keeps (geometry checks // aside), so its count is of a sample whenever the sample isn't the whole layer. @@ -594,12 +605,12 @@ impl FeatureSource for ShpSource { } } -/// Says how many shapes a read left out for a coordinate that isn't a number while their stored -/// box is one the index takes (finite and in order, [`index::usable`]): [`record_box`] doesn't read +/// Says how many shapes a read found with a coordinate that isn't a number, which have no geometry +/// to read ([`kept_no_number_note`]), while their stored box is one the index takes (finite and in order, [`index::usable`]): [`record_box`] doesn't read /// the points, so the layer's extent and its index still take in those boxes. A backwards stored /// box over such a point isn't counted here: the index can't frame it from the points, so it's -/// left out of the extent and counted with the shapes that have no usable box. A `sampled` read visited only some of the matches, so its count is of -/// the shapes it read, not of the layer. A `late` read (an area the layer's system couldn't bound, +/// left out of the extent and counted with the shapes that have no usable box. A `sampled` read +/// visited only some of the matches, so its count is of the shapes it read, not of the layer. A `late` read (an area the layer's system couldn't bound, /// #1925) visited every record and can't place a NaN shape's stored box in the area, so its count /// is of the whole layer, and says so. fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { @@ -614,13 +625,28 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { format!("{n} shape(s)") }; vec![crate::loss::Note::loss( - crate::loss::LossCode::DroppedFeature, + crate::loss::LossCode::DroppedGeometry, format!( - "{what} have a coordinate that isn't a number under a bounding box that is one: they're left out of the read, but the layer's extent and its index still take in their stored boxes" + "{what} have a coordinate that isn't a number under a bounding box that is one: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" ), )] } +/// Says how many shapes with a coordinate that isn't a number a read gave without geometry, +/// keeping their attributes, in the words a whole read says it with +/// ([`crate::io`]'s Shapefile reader); of those read when the read is `sampled`. +fn kept_no_number_note(n: usize, sampled: bool) -> Option { + let what = match n { + 0 => return None, + n if sampled => format!("{n} of the shapes read (a sample of the layer, which may hold more)"), + n => format!("{n} shape(s)"), + }; + Some(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{what} have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"), + )) +} + /// The numbers in the `.dbf` that aren't finite, read as empty ([`crate::io::nonfinite_note`]); a /// `sampled` read counts only the records it read, and says so, as [`deleted_note`] does. fn nonfinite_note(fields: &[crate::Field], counts: &[usize], sampled: bool) -> Option { diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 54eb599e5d..f1a583332a 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -692,11 +692,12 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( std::fs::write(&p, b).unwrap(); let src = open_path(&p, None).unwrap(); // Every record is visited, so the NaN shapes can't be ruled out of the area: both reads - // skip them, and the note says its count is of the layer, not of the area. + // give none of them (a shape without geometry is in no area), and the note says its count + // is of the layer, not of the area. let layer = vec![format!( - "2 shape(s) in the layer (a count of the whole layer, as the area couldn't be placed in its coordinates) {SAID}: they're left out of the read, but the layer's extent and its index still take in their stored boxes" + "2 shape(s) in the layer (a count of the whole layer, as the area couldn't be placed in its coordinates) {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" )]; - assert_eq!(reads(src.as_ref()), ((0, 2, layer.clone()), (0, 2, layer))); + assert_eq!(reads(src.as_ref()), ((0, 0, layer.clone()), (0, 0, layer))); // A whole read keeps its plain count. assert_eq!(said(&src.read(&Request::all()).unwrap().notes).first().map(|n| n.starts_with("2 shape(s) have")), Some(true)); }); @@ -704,11 +705,12 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( } /// A line with a coordinate that isn't a number under a stored box that is one: the index takes -/// the stored box (the points aren't read to build it), and a read leaves the line out. Both -/// reads, sampled and in chunks, count it and say so, once with its count, whole or by area; a -/// limited read says its count is of the shapes it read; a clean file says nothing. +/// the stored box (the points aren't read to build it), and a read keeps the line's attributes +/// without its geometry, as a whole read of the file does (#2032 C2f). Both reads, sampled and in +/// chunks, say so, once with its count, whole or by area (which gives no feature without +/// geometry); a limited read says its count is of the shapes it read; a clean file says nothing. #[test] -fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { +fn a_nan_shape_under_a_finite_box_is_said_when_kept_without_geometry() { let fixture = dir(); cache::with_index_dir(fixture.join("cache"), || { let write = |name: &str| { @@ -722,24 +724,42 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { p }; const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; - // Each read says the shapes it left out as dropped features, which the checks below see. + const KEPT: &str = "have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"; + // Each read says the shapes it gave without geometry as dropped geometry, which the + // checks below see. let said = |notes: &[crate::loss::Note]| { notes .iter() .filter(|n| n.contains(SAID)) - .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedFeature), "{n:?}")) + .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedGeometry), "{n:?}")) .map(|n| n.text.clone()) .collect::>() }; + let kept = |notes: &[crate::loss::Note]| { + notes + .iter() + .filter(|n| n.contains(KEPT)) + .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedGeometry), "{n:?}")) + .map(|n| n.text.clone()) + .collect::>() + }; + // Skips, features without geometry given, and the two notes. let chunk_notes = |src: &dyn FeatureSource, extent| { - let batch = src.visit_chunks(extent, 1 << 20, &mut |_| Ok(())).unwrap(); - (batch.skipped, said(&batch.notes)) + let mut bare = 0; + let batch = src + .visit_chunks(extent, 1 << 20, &mut |f| { + bare += f.iter().filter(|f| f.geometry.is_none()).count(); + Ok(()) + }) + .unwrap(); + (batch.skipped, bare, said(&batch.notes), kept(&batch.notes)) }; let clean = open_path(&write("clean.shp"), None).unwrap(); let (_, report) = crate::source::materialize(clean.as_ref()).unwrap(); assert!(said(&report.messages).is_empty(), "{:?}", report.messages); assert!(said(&clean.read(&Request::all()).unwrap().notes).is_empty()); - assert_eq!(chunk_notes(clean.as_ref(), None), (0, Vec::new())); + assert!(kept(&clean.read(&Request::all()).unwrap().notes).is_empty()); + assert_eq!(chunk_notes(clean.as_ref(), None), (0, 0, Vec::new(), Vec::new())); // The second record (each record 8 + 80 bytes, so its content at 100 + 88 + 8): its first // point's x at 196 + 48 = 244, its stored box (1, 1, 2, 2) left as it is. let p = write("nan.shp"); @@ -750,20 +770,30 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { assert!(src.info().indexed); assert_eq!(src.info().extent, Extent::new(0.0, 0.0, 3.0, 3.0), "the stored box framed"); let one = vec![format!( - "1 shape(s) {SAID}: they're left out of the read, but the layer's extent and its index still take in their stored boxes" + "1 shape(s) {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" )]; + let one_kept = vec![format!("1 shape(s) {KEPT}")]; + // Kept without geometry, its attributes too, as a whole read of the file keeps it. let (ds, report) = crate::source::materialize(src.as_ref()).unwrap(); - assert_eq!((ds.features.len(), report.skipped), (2, 1)); + assert_eq!((ds.features.len(), report.skipped), (3, 0)); + assert!(ds.features[1].geometry.is_none()); + let (whole, _) = crate::io::read_path(&p).unwrap(); + assert_eq!(whole.features.iter().map(|f| f.geometry.is_none()).collect::>(), [false, true, false]); assert_eq!(said(&report.messages).len(), 1, "{:?}", report.messages); assert!(report.messages.iter().any(|m| m.ends_with(&one[0])), "{:?}", report.messages); + assert!(report.messages.iter().any(|m| m.ends_with(&one_kept[0])), "{:?}", report.messages); let all = src.read(&Request::all()).unwrap(); - assert_eq!((all.skipped, said(&all.notes)), (1, one.clone())); - // By area, over the stored box only: matched by it, left out, said. + assert_eq!((all.features.len(), all.skipped, said(&all.notes), kept(&all.notes)), (3, 0, one.clone(), one_kept.clone())); + // By area, over the stored box only: matched by it, given as no feature (a shape without + // geometry is in no area), its box said. let area = Some(Extent::new(1.4, 1.4, 1.6, 1.6)); let by_area = src.read(&Request { extent: area, ..Request::all() }).unwrap(); - assert_eq!((by_area.features.len(), by_area.skipped, said(&by_area.notes)), (0, 1, one.clone())); - assert_eq!(chunk_notes(src.as_ref(), None), (1, one.clone())); - assert_eq!(chunk_notes(src.as_ref(), area), (1, one.clone())); + assert_eq!( + (by_area.features.len(), by_area.skipped, said(&by_area.notes), kept(&by_area.notes)), + (0, 0, one.clone(), Vec::new()) + ); + assert_eq!(chunk_notes(src.as_ref(), None), (0, 1, one.clone(), one_kept.clone())); + assert_eq!(chunk_notes(src.as_ref(), area), (0, 0, one.clone(), Vec::new())); // A limited read visits a sample (here the first and third records), so its count is of // the shapes it read, not a total: the first record's point made NaN (content at 108, // its first x at 108 + 48 = 156). @@ -774,14 +804,16 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { let src = open_path(&p, None).unwrap(); let some = src.read(&Request { limit: 2, ..Request::all() }).unwrap(); assert!(!some.complete); + let sample = "1 of the shapes read (a sample of the layer, which may hold more)"; assert_eq!( - (some.features.len(), some.skipped, said(&some.notes)), + (some.features.len(), some.skipped, said(&some.notes), kept(&some.notes)), ( - 1, - 1, + 2, + 0, vec![format!( - "1 of the shapes read (a sample of the layer, which may hold more) {SAID}: they're left out of the read, but the layer's extent and its index still take in their stored boxes" - )] + "{sample} {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" + )], + vec![format!("{sample} {KEPT}")] ) ); // A whole read of the same file still gives the total. @@ -803,12 +835,12 @@ fn a_nan_shape_under_a_finite_box_is_said_when_left_out() { let src = open_path(&p, None).unwrap(); let unboxed = "1 shape(s) have no usable bounding box"; let (ds, report) = crate::source::materialize(src.as_ref()).unwrap(); - assert_eq!((ds.features.len(), report.skipped), (2, 1)); + assert_eq!((ds.features.len(), report.skipped), (3, 0)); assert!(said(&report.messages).is_empty(), "{:?}", report.messages); assert!(report.messages.iter().any(|m| m.contains(unboxed)), "{:?}", report.messages); let all = src.read(&Request::all()).unwrap(); - assert_eq!((all.skipped, said(&all.notes)), (1, Vec::new())); - assert_eq!(chunk_notes(src.as_ref(), None), (1, Vec::new())); + assert_eq!((all.skipped, said(&all.notes), kept(&all.notes)), (0, Vec::new(), one_kept.clone())); + assert_eq!(chunk_notes(src.as_ref(), None), (0, 1, Vec::new(), one_kept)); }); std::fs::remove_dir_all(fixture).unwrap(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 74b6718f25..874c3ed69b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2108,7 +2108,7 @@ fn a_streamed_layer_says_its_view_reads_notes_once() { }; let expected: &[&str] = if nan { &[ - "roads: 1 shape(s) have a coordinate that isn't a number under a bounding box that is one: they're left out of the read, but the layer's extent and its index still take in their stored boxes", + "roads: 1 shape(s) have a coordinate that isn't a number under a bounding box that is one: they have no geometry to read, but the layer's extent and its index still take in their stored boxes", ] } else { &[] From af8e2e327a23ab94f12fb34570225f06b2f94a10 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 13:26:08 +0100 Subject: [PATCH 02/12] docs(data-formats): a Shapefile shape whose coordinates aren't numbers is kept without geometry --- docs/user-guide/data-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4a360e2ed6..aa08bd68ed 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -20,7 +20,7 @@ export names its feature. | --- | --- | --- | --- | | GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system is the layer's own: its coordinates are kept as the file holds them and drawn in the map's projection (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted is kept as the file holds it and counted in a notice; it doesn't draw. One whose coordinates convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers) is kept too, and a notice says it may draw out of place (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, in English or another language such as `經度`/`緯度`, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within the size read into memory of expanded text (256 MiB in the web app); decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | -| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | +| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry, read whole or in place, and is counted in a notice. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | | dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | | KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder` or `style` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | | GPX | `.gpx` | Add Data, drop the file, or upload it in the web app | Waypoints, routes, tracks (one line per track, its segments as parts) and track points (with elevation and time) as separate layers. | From 98942eead95b6b90fa2a616828c7d665e10dad36 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 13:41:54 +0100 Subject: [PATCH 03/12] perf(map): a held layer on a map in its own system is drawn from its rows, with no projected copy (Shapes) --- crates/data/src/source/shp/tests.rs | 5 +- crates/engine/src/tests.rs | 2 +- crates/engine/src/tests/held_layers.rs | 4 +- .../tests/integration/vertex_snap_identity.rs | 2 +- crates/map/src/lib.rs | 142 +++++++++++++----- crates/map/src/lod.rs | 16 +- crates/map/src/look.rs | 3 + crates/map/src/shapes.rs | 139 +++++++++++++++++ crates/map/src/source/window.rs | 103 +++++++++---- crates/render/src/lib.rs | 10 +- docs/user-guide/data.md | 4 +- 11 files changed, 348 insertions(+), 82 deletions(-) create mode 100644 crates/map/src/shapes.rs diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index f1a583332a..10e6385fb1 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -788,10 +788,7 @@ fn a_nan_shape_under_a_finite_box_is_said_when_kept_without_geometry() { // geometry is in no area), its box said. let area = Some(Extent::new(1.4, 1.4, 1.6, 1.6)); let by_area = src.read(&Request { extent: area, ..Request::all() }).unwrap(); - assert_eq!( - (by_area.features.len(), by_area.skipped, said(&by_area.notes), kept(&by_area.notes)), - (0, 0, one.clone(), Vec::new()) - ); + assert_eq!((by_area.features.len(), by_area.skipped, said(&by_area.notes), kept(&by_area.notes)), (0, 0, one.clone(), Vec::new())); assert_eq!(chunk_notes(src.as_ref(), None), (0, 1, one.clone(), one_kept.clone())); assert_eq!(chunk_notes(src.as_ref(), area), (0, 0, one.clone(), Vec::new())); // A limited read visits a sample (here the first and third records), so its count is of diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 874c3ed69b..75de759dcf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1074,7 +1074,7 @@ fn undo_steps_share_the_layers_they_leave_alone() { for (snap, ..) in &s.undo { let old = snap.maps.iter().flat_map(|m| &m.layers).find(|l| l.id == id).unwrap(); assert!(old.dataset.features.shares(&live.dataset.features), "the snapshot copied the features"); - assert_eq!(old.projected_cache().as_ptr(), live.projected_cache().as_ptr(), "the snapshot copied the projected geometry"); + assert!(old.projected_cache().same(live.projected_cache()), "the snapshot copied the projected geometry"); } // An edit copies the layer it changes, once, and leaves the snapshot as it was. let before = s.map().layer_by_name("Cities").unwrap().dataset.features.len(); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 4f0cfb9342..e8c95897f8 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -1305,7 +1305,7 @@ fn edits_on_a_map_in_another_datums_system_land_on_what_it_draws() { assert_eq!(flat.direct_system(), Some(Crs::Epsg(25832))); let id = s.map().layer_by_name("Roads").unwrap().id; let stored = s.map().layer(id).unwrap().dataset.features[0].geometry.clone().unwrap(); - let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test")[0].clone().unwrap(); + let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test").get(0).cloned().unwrap(); let (Geometry::Line(stored_parts), Geometry::Line(drawn_parts)) = (&stored, &drawn) else { panic!("a line") }; let l = s.map().layer(id).unwrap(); assert_eq!(l.dataset.shown_in, Some(Crs::Epsg(25832)), "the map told its layer its system"); @@ -1343,7 +1343,7 @@ fn a_moved_label_becomes_an_annotation_where_it_was_drawn() { let flat = s.map().flat(); assert_eq!(flat.direct_system(), Some(Crs::Epsg(25832))); let id = s.map().layer_by_name("Wells").unwrap().id; - let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test")[2].clone().unwrap(); + let drawn = s.map_mut().layer_mut(id).unwrap().projected_in(&flat, "test").get(2).cloned().unwrap(); let Geometry::Point(drawn) = drawn else { panic!("a point") }; let l = s.map().layer(id).unwrap(); let (moved, target) = (l.dataset.features[1].id, l.dataset.features[2].geometry.clone().unwrap()); diff --git a/crates/engine/tests/integration/vertex_snap_identity.rs b/crates/engine/tests/integration/vertex_snap_identity.rs index fb2e4cbae5..09f3940114 100644 --- a/crates/engine/tests/integration/vertex_snap_identity.rs +++ b/crates/engine/tests/integration/vertex_snap_identity.rs @@ -194,7 +194,7 @@ fn projection_cuts_do_not_supply_source_addresses_or_bridge_the_world() { hit(snap_vertex_except(&mut s, Coord::new(-110., 20.), node), Coord::new(-110., 20.), "vertex"); assert!(snap_vertex_except(&mut s, Coord::new(-100., 20.), node).is_none()); assert!(snap_vertex_except(&mut s, Coord::new(90., -20.), node).is_none()); - let Geometry::Line(parts) = s.map().layer(id).unwrap().projected_cache()[0].as_ref().unwrap() else { panic!("line") }; + let Geometry::Line(parts) = s.map().layer(id).unwrap().projected_cache().get(0).unwrap() else { panic!("line") }; assert!(parts.len() > 2, "the fixture must actually split at the world edge"); s.map_mut().editing.snapping.vertex = false; s.map_mut().editing.snapping.edge = true; diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 22d6ebce7b..4faa8b6445 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -30,6 +30,7 @@ pub mod report; mod row_boxes; pub mod rows; pub mod shadow; +pub mod shapes; pub mod slots; pub mod source; pub use slots::{LayerRole, Slot, SlotPos, TileRole}; @@ -45,6 +46,7 @@ pub use color::{Ramp, RampGroup, Rgba}; pub use diagram::{DiagramCategory, DiagramKind, DiagramLabel, DiagramSettings, DiagramSize}; pub use globe::{Globe, Projection}; pub use raster::{RasterDefaults, RasterLayer, RasterRenderer, RasterStyle, Resampling, Stretch}; +pub use shapes::Shapes; pub use symbology::{ ClassMethod, Classer, FontName, Glyph, LabelBackground, LabelClass, LabelGuide, LabelKey, LabelMatcher, LabelPlacement, Labeling, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, Marker, MarkerRotation, Picture, Placements, Renderer, SquareSide, SquareTo, @@ -305,6 +307,11 @@ pub struct Layer { /// Shared, like the features: an undo snapshot or other copy of the layer doesn't copy it. #[serde(skip)] projected: std::sync::Arc>>, + /// Whether the projected geometry is the layer's own rows, read in place (`projected` then + /// empty): on a map in the system it holds them in, which draws every place as it is, so no + /// copy is made ([`Layer::projected_in`]). + #[serde(skip)] + projected_own: bool, /// The active Mercator display level; full projection stays lazy for interaction. #[serde(skip)] display: Option>, @@ -557,6 +564,7 @@ impl Layer { connection: String::new(), anonymous: false, projected: Default::default(), + projected_own: false, display: None, display_rejected: Vec::new(), display_levels: Vec::new(), @@ -764,6 +772,7 @@ impl Layer { self.touch_geometry(); if let Some(cache) = self.source.as_mut().and_then(|s| s.ready_cache.take()) { self.projected = cache.projected; + self.projected_own = cache.own; self.projected_extents = cache.extents; self.projected_vertices = cache.vertices; self.projected_for = cache.key; @@ -1139,7 +1148,7 @@ impl Layer { /// parts and vertices needn't match the source's (a cut feature has more parts, and a point /// the projection can't use breaks a line): hit-testing and snapping use the shape, never a /// vertex index, which only the source geometry has. - pub fn projected_in(&mut self, flat: &projection::Flat, key: &str) -> &[Option] { + pub fn projected_in(&mut self, flat: &projection::Flat, key: &str) -> Shapes<'_> { if !self.is_cached(key) { // Display copies made for another map are of no use on this one. if self.display_rows(flat).is_none() { @@ -1148,7 +1157,7 @@ impl Layer { self.fill_projected(key, flat); } self.drawn.flat = true; - &self.projected + self.projected_cache() } /// Its geometry in longitude/latitude, for the globe, which draws there: kept in a cache of @@ -1268,15 +1277,18 @@ impl Layer { fn fill_projected(&mut self, key: &str, flat: &projection::Flat) { self.display = None; let crs = self.dataset.coord_crs(); + self.projected_own = false; let projected: Vec> = if crs == Crs::LonLat { self.dataset.features.rows().map(|r| r.geometry().map(|g| flat.project(g))).collect() } else { match flat.held(crs) { // Every place is drawn as it is, those longitude/latitude can't give too: the // conversion leaves none out (a place a reader kept missing is said by the reader). + // Its own rows, read in place: no copy (#2032 C2f). Ok(held) if held.is_identity() => { self.flat_unplaced = Unplaced { rev: self.geometry_rev, crs: Some(crs), count: Ok(0) }; - self.dataset.features.rows().map(|r| r.geometry().cloned()).collect() + self.projected_own = true; + Vec::new() } Ok(held) => { let mut lost = 0usize; @@ -1299,10 +1311,11 @@ impl Layer { } } }; - self.projected_extents = - std::sync::Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); - self.projected_vertices = projected.iter().flatten().map(lod::thinnable).sum(); self.projected = std::sync::Arc::new(projected); + let shapes = self.projected_cache(); + let extents = std::sync::Arc::new(shapes.iter().map(|g| g.map_or(Extent::EMPTY, Geometry::extent)).collect()); + let vertices = shapes.iter().flatten().map(lod::thinnable).sum(); + (self.projected_extents, self.projected_vertices) = (extents, vertices); self.thinned = Default::default(); self.projected_rev = self.geometry_rev; self.projected_for = key.to_string(); @@ -1311,7 +1324,7 @@ impl Layer { } /// Web Mercator copies of every geometry (see [`Layer::projected_in`]). - pub fn projected(&mut self) -> &[Option] { + pub fn projected(&mut self) -> Shapes<'_> { self.projected_in(&projection::Flat::Mercator, "mercator") } @@ -1424,14 +1437,15 @@ impl Layer { /// The projected geometry (see [`Layer::projected_in`]) as drawn at a tolerance in projection /// units: a thinned copy at the level just under it (see [`lod`]), made on first use, or the /// geometry itself for a small layer. Read it back with [`Layer::thinned_cache`]. - pub fn thinned_in(&mut self, flat: &projection::Flat, key: &str, tol: f64) -> &[Option] { + pub fn thinned_in(&mut self, flat: &projection::Flat, key: &str, tol: f64) -> Shapes<'_> { self.display = None; self.projected_in(flat, key); self.trim_display_levels(self.lod_budget()); let display_bytes: usize = self.display_levels.iter().map(|d| d.bytes).sum(); let budget = self.lod_budget().saturating_sub(display_bytes); self.trim_thinned_levels(budget); - let Some(level) = lod::level(tol).filter(|_| self.projected_vertices > lod::THIN_ABOVE) else { return &self.projected }; + let Some(level) = lod::level(tol).filter(|_| self.projected_vertices > lod::THIN_ABOVE) else { return self.projected_cache() }; + let shapes = shapes_of(self.projected_own, &self.dataset.features, &self.projected); let levels = std::sync::Arc::make_mut(&mut self.thinned); match levels.iter().position(|(l, _)| *l == level) { Some(i) => { @@ -1459,10 +1473,10 @@ impl Layer { } else if lonlat_rows { lod::project_budgeted(&self.dataset.features, lod::Rows::LonLat, level, budget) } else { - lod::thin_budgeted(&self.projected, t, budget) + lod::thin_budgeted(shapes, t, budget) }; // The saving counts against every vertex the copy holds, points included. - let all: usize = self.projected.iter().flatten().map(lod::vertices).sum(); + let all: usize = shapes.iter().flatten().map(lod::vertices).sum(); let copy = copy.filter(|c| { let kept: usize = c.iter().flatten().map(lod::vertices).sum(); (kept as f64) <= all as f64 * (1.0 - lod::MIN_SAVING) @@ -1477,11 +1491,12 @@ impl Layer { /// The geometry from the last [`Layer::thinned_in`] call at this tolerance, without making /// it: the full projected geometry when there is no thinned copy for it. - pub fn thinned_cache(&self, tol: f64) -> &[Option] { + pub fn thinned_cache(&self, tol: f64) -> Shapes<'_> { let level = lod::level(tol).filter(|_| self.projected_vertices > lod::THIN_ABOVE); + let shapes = self.projected_cache(); match level.and_then(|level| self.thinned.iter().find(|(l, _)| *l == level)) { - Some((_, Some(g))) if g.len() == self.projected.len() => g, - _ => &self.projected, + Some((_, Some(g))) if g.len() == shapes.len() => Shapes::Copies(g), + _ => shapes, } } @@ -1492,8 +1507,8 @@ impl Layer { /// The Web Mercator copies from the last [`Layer::projected`] call, without refreshing them: /// call `projected` first (it needs `&mut self`) whenever the geometry may have changed. - pub fn projected_cache(&self) -> &[Option] { - &self.projected + pub fn projected_cache(&self) -> Shapes<'_> { + shapes_of(self.projected_own, &self.dataset.features, &self.projected) } /// Drops the projected geometry cache (the feature cache). @@ -1502,6 +1517,7 @@ impl Layer { self.display_levels.clear(); self.display_rejected.clear(); self.projected = Default::default(); + self.projected_own = false; self.projected_extents = Default::default(); self.projected_vertices = 0; self.thinned = Default::default(); @@ -1547,6 +1563,7 @@ impl Layer { self.display_levels = other.display_levels.clone(); if other.is_cached(&other.projected_for) { self.projected = other.projected.clone(); + self.projected_own = other.projected_own; self.projected_extents = other.projected_extents.clone(); self.projected_vertices = other.projected_vertices; self.thinned = other.thinned.clone(); @@ -1567,8 +1584,9 @@ impl Layer { /// frame drawn there from display copies alone ([`Layer::prepare_display`]) has no use for it, /// and it would stay, a copy of the layer's geometry, until that map came back. pub fn release_projected_other_than(&mut self, key: &str) { - if !self.projected.is_empty() && self.projected_for != key { + if (!self.projected.is_empty() || self.projected_own) && self.projected_for != key { self.projected = Default::default(); + self.projected_own = false; self.projected_extents = Default::default(); self.projected_vertices = 0; self.thinned = Default::default(); @@ -1595,7 +1613,7 @@ impl Layer { pub fn is_cached(&self, key: &str) -> bool { self.projected_for == key && self.projected_rev == self.geometry_rev - && self.projected.len() == self.dataset.features.len() + && (self.projected_own || self.projected.len() == self.dataset.features.len()) && self.projected_crs == Some(self.dataset.coord_crs()) } @@ -3754,6 +3772,7 @@ impl Layer { anonymous: _, instance_id: _, projected: _, + projected_own: _, display: _, display_rejected: _, display_levels: _, @@ -3926,6 +3945,12 @@ struct MapView<'a> { system: Crs, view: Extent, } +/// A layer's projected geometry ([`Layer::projected_cache`]) from its fields: its own rows when +/// `own`, else the copies. +fn shapes_of<'a>(own: bool, rows: &'a rustgis_data::Features, copies: &'a [Option]) -> Shapes<'a> { + if own { Shapes::Rows(rows) } else { Shapes::Copies(copies) } +} + #[cfg(test)] mod tests { use super::*; @@ -4443,6 +4468,51 @@ mod tests { assert!(!m.layer(id).unwrap().is_cached("mercator")); } + /// On a map in the system a layer is held in, the geometry frames read for exact positions + /// (labels, selection: [`Layer::projected_in`]) is its own rows, read in place: no copy is + /// made or counted, an edit shows at once, and its thinned copy is made from those rows. A map + /// in another system draws a copy, as before (#2032 C2f). + #[test] + fn a_held_layer_on_a_map_in_its_own_system_shares_its_rows() { + let n = lod::THIN_ABOVE + 1000; + let mut d = Dataset::new("zigzag", GeometryType::Polyline, vec![]); + let run: Vec = (0..n) + .map(|i| Coord::new(500_000.0 + 100_000.0 * i as f64 / n as f64, 5_316_000.0 + if i % 2 == 0 { 1.0 } else { -1.0 })) + .collect(); + d.push(Some(Geometry::Line(vec![run.clone()])), vec![]); + d.held_in = Crs::Epsg(32632); + let mut l = Layer::new(1, d); + let own = projection::Flat::of(&Projection::Custom("EPSG:32632".into())); + let before = l.view_cache_bytes(); + let stored = l.dataset.features.geometry(0).cloned(); + let drawn = l.projected_in(&own, "utm"); + assert!(matches!(drawn, Shapes::Rows(_)), "its own rows"); + assert_eq!(drawn.get(0), stored.as_ref()); + assert_eq!(l.projected_extents(), &[l.dataset.features.geometry(0).unwrap().extent()]); + assert!(l.projected.is_empty()); + assert!(l.view_cache_bytes() < before + 64 * 1024, "no copy counted: {} then {}", before, l.view_cache_bytes()); + assert!(l.is_cached("utm")); + // Thinned from its rows, its ends as held. + let thinned = l.thinned_in(&own, "utm", 1_000.0).get(0).cloned().unwrap(); + assert!(lod::vertices(&thinned) < n / 40); + let Geometry::Line(parts) = &thinned else { panic!("a line") }; + assert_eq!((parts[0][0], *parts[0].last().unwrap()), (run[0], *run.last().unwrap())); + // An edit: the cache is made again, still its rows. + l.dataset.features[0].geometry = Some(Geometry::Line(vec![run[..2].to_vec()])); + l.touch_geometry(); + assert!(!l.is_cached("utm")); + assert_eq!(l.projected_in(&own, "utm").get(0), Some(&Geometry::Line(vec![run[..2].to_vec()]))); + // A copy of the layer (an undo snapshot, a drawing off the UI thread) shares it. + let copy = l.clone(); + assert!(copy.projected_cache().same(l.projected_cache())); + // On a map in another system, a copy, converted. + let other = projection::Flat::of(&Projection::Custom("EPSG:25832".into())); + let drawn = l.projected_in(&other, "etrs"); + assert!(matches!(drawn, Shapes::Copies(_))); + assert_ne!(drawn.get(0), stored.as_ref()); + assert!(!l.projected.is_empty()); + } + /// A layer held in the system its map is drawn in gets display copies made from its own rows, /// simplified as they are, with nothing converted and no full copy of it on the map; a map in /// another system makes none (it draws the projected copy, as before), and a projection made @@ -4502,7 +4572,7 @@ mod tests { // Requesting exact positions remains exact and drops the optional display copy. assert_eq!(copy.projected().len(), 1); assert!(copy.display_cache().is_none()); - assert_eq!(lod::vertices(copy.projected_cache()[0].as_ref().unwrap()), lod::THIN_ABOVE + 1000); + assert_eq!(lod::vertices(copy.projected_cache().get(0).unwrap()), lod::THIN_ABOVE + 1000); l.touch_geometry(); assert!(l.display_cache().is_none()); assert!(l.prepare_display(&flat, 24_000.0, false)); @@ -4572,7 +4642,7 @@ mod tests { assert!(chunk.display_cache().is_none()); // Budget exhaustion falls back to the original, fully projected geometry. let full = flat.project(chunk.dataset.features[0].geometry.as_ref().unwrap()); - assert_eq!(chunk.thinned_in(&flat, "mercator", 1e6), &[Some(full)]); + assert_eq!(chunk.thinned_in(&flat, "mercator", 1e6), [Some(full)]); } /// #2678: a layer read in place counts its source's features, not the view's: whatever the @@ -4878,7 +4948,7 @@ mod tests { } }; near(&coords(&stored), &[(3513304.512454, 5404737.597295), (3514768.524742, 5406965.390660)]); - let on_own = gk.projected_in(&flat("EPSG:31467"), "gk")[0].clone().unwrap(); + let on_own = gk.projected_in(&flat("EPSG:31467"), "gk").get(0).cloned().unwrap(); assert_eq!(coords(&on_own), coords(&stored)); assert_eq!(gk.unplaced(), Some(&Ok(0)), "drawn as it is: none left out"); // On ETRS89 UTM 32N, the direct operation's result, not the way through WGS 84. @@ -4886,7 +4956,7 @@ mod tests { assert_eq!(utm.direct_system(), Some(Crs::Epsg(25832))); let direct = Crs::Epsg(31467).to(Crs::Epsg(25832)).unwrap(); let to_lonlat = Crs::Epsg(31467).to(Crs::LonLat).unwrap(); - let drawn = gk.projected_in(&utm, "utm")[0].clone().unwrap(); + let drawn = gk.projected_in(&utm, "utm").get(0).cloned().unwrap(); for (d, s) in coords(&drawn).into_iter().zip(coords(&stored)) { let want = direct.point(s).unwrap(); assert!((d.x - want.x).abs() < 1e-6 && (d.y - want.y).abs() < 1e-6, "{d:?} vs {want:?}"); @@ -4899,7 +4969,7 @@ mod tests { for (map, key) in [(projection::Flat::Mercator, "mercator"), (flat("ESRI:54030"), "robinson")] { assert_eq!(map.direct_system(), None, "{key}"); let want = map.project(&to_lonlat.geometry(&stored)); - assert_eq!(gk.projected_in(&map, key)[0].as_ref(), Some(&want), "{key}"); + assert_eq!(gk.projected_in(&map, key).get(0), Some(&want), "{key}"); } // A place longitude/latitude can't give is counted where drawing goes through it (Web // Mercator), and not on a map in the layer's own system, which draws it as it is. @@ -4928,14 +4998,14 @@ mod tests { // A layer held in Web Mercator is drawn on the Web Mercator map as it is. let mut merc = held(Crs::WebMercator); let stored_merc = merc.dataset.features[0].geometry.clone().unwrap(); - let on_merc = merc.projected_in(&projection::Flat::Mercator, "mercator")[0].clone().unwrap(); + let on_merc = merc.projected_in(&projection::Flat::Mercator, "mercator").get(0).cloned().unwrap(); assert_eq!(coords(&on_merc), coords(&stored_merc)); // A place far outside UTM 32N isn't drawn there, and isn't one longitude/latitude lacks. let mut d = Dataset::new("far", GeometryType::Point, vec![]); d.push(Some(Geometry::Point(Coord::new(50.0, 48.8))), vec![]); d.hold_in(Crs::Epsg(31467)).unwrap(); let mut far = Layer::new(2, d); - let drawn = far.projected_in(&utm, "utm")[0].clone().unwrap(); + let drawn = far.projected_in(&utm, "utm").get(0).cloned().unwrap(); assert!(coords(&drawn).iter().all(|c| !c.is_finite()), "{drawn:?}"); assert_eq!(far.unplaced(), Some(&Ok(0))); } @@ -4951,7 +5021,7 @@ mod tests { // The level the display attempt found saves too little isn't built again: the full // projection is drawn, as when it was. assert_eq!(lod::LEVEL_BUILDS.get(), levels, "the refused level is built once"); - assert_eq!(drawn, l.projected_cache()); + assert_eq!(l.projected_cache(), drawn[..]); assert!(!l.prepare_display(&flat, 0.001, false)); assert_eq!(lod::DISPLAY_BUILDS.get(), built, "thinned_in builds geometry only"); l.thinned_in(&flat, "mercator", 0.001); @@ -4970,22 +5040,22 @@ mod tests { fn a_detailed_layer_draws_from_a_thinned_copy() { let flat = projection::Flat::Mercator; let mut l = long_line(lod::THIN_ABOVE + 1000); - let full = lod::vertices(l.projected()[0].as_ref().unwrap()); + let full = lod::vertices(l.projected().get(0).unwrap()); // Seen whole (about 40 km a pixel), one vertex every 8 km (the level under 12 km) is enough. - let thinned = lod::vertices(l.thinned_in(&flat, "mercator", 12_000.0)[0].as_ref().unwrap()); + let thinned = lod::vertices(l.thinned_in(&flat, "mercator", 12_000.0).get(0).unwrap()); assert!(thinned < full / 40, "{thinned} of {full} vertices drawn"); - assert_eq!(lod::vertices(l.thinned_cache(12_000.0)[0].as_ref().unwrap()), thinned); + assert_eq!(lod::vertices(l.thinned_cache(12_000.0).get(0).unwrap()), thinned); // Zoomed in past its vertex spacing, every vertex draws. - assert_eq!(lod::vertices(l.thinned_in(&flat, "mercator", 0.001)[0].as_ref().unwrap()), full); + assert_eq!(lod::vertices(l.thinned_in(&flat, "mercator", 0.001).get(0).unwrap()), full); // Its extents are cached row for row, and a clone shares the caches. assert_eq!(l.projected_extents().len(), 1); let copy = l.clone(); - assert_eq!(copy.projected_cache().as_ptr(), l.projected_cache().as_ptr()); - assert_eq!(copy.thinned_cache(12_000.0).as_ptr(), l.thinned_cache(12_000.0).as_ptr()); + assert_eq!(copy.projected_cache().copies().map(<[_]>::as_ptr), l.projected_cache().copies().map(<[_]>::as_ptr)); + assert_eq!(copy.thinned_cache(12_000.0).copies().map(<[_]>::as_ptr), l.thinned_cache(12_000.0).copies().map(<[_]>::as_ptr)); // A change of geometry drops the thinned copies with the projection. l.touch_geometry(); l.projected(); - assert_eq!(l.thinned_cache(12_000.0).as_ptr(), l.projected_cache().as_ptr()); + assert_eq!(l.thinned_cache(12_000.0).copies().map(<[_]>::as_ptr), l.projected_cache().copies().map(<[_]>::as_ptr)); } #[test] @@ -4994,14 +5064,14 @@ mod tests { let flat = projection::Flat::Mercator; let mut l = long_line(lod::THIN_ABOVE + 1000); l.projected(); - assert_eq!(l.thinned_in(&flat, "mercator", 1.0).as_ptr(), l.projected_cache().as_ptr()); + assert_eq!(l.thinned_in(&flat, "mercator", 1.0).copies().map(<[_]>::as_ptr), l.projected_cache().copies().map(<[_]>::as_ptr)); // Nor for points, however many. let mut d = Dataset::new("pts", GeometryType::Point, vec![]); let pts = (0..lod::THIN_ABOVE + 10).map(|i| Coord::new(i as f64 * 1e-6, 0.0)).collect(); d.push(Some(Geometry::MultiPoint(pts)), vec![]); let mut p = Layer::new(2, d); p.projected(); - assert_eq!(p.thinned_in(&flat, "mercator", 1e6).as_ptr(), p.projected_cache().as_ptr()); + assert_eq!(p.thinned_in(&flat, "mercator", 1e6).copies().map(<[_]>::as_ptr), p.projected_cache().copies().map(<[_]>::as_ptr)); } #[test] @@ -5009,7 +5079,7 @@ mod tests { let flat = projection::Flat::Mercator; let mut l = long_line(1000); let full = l.projected().to_vec(); - assert_eq!(l.thinned_in(&flat, "mercator", 1e6), &full[..]); + assert_eq!(l.thinned_in(&flat, "mercator", 1e6), full[..]); } #[test] diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index 48fc494578..aca1b42591 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -192,8 +192,14 @@ pub(crate) fn cache_bytes(geoms: &Vec>) -> usize { /// Build one level without first allocating a whole window's extra geometry. Running out of /// budget discards only this optional display cache; drawing still uses the full projection. -pub(crate) fn thin_budgeted(geoms: &[Option], tol: f64, budget: usize) -> Option>> { - map_budgeted(geoms, budget, Option::as_ref, |g| thin(g, tol)) +pub(crate) fn thin_budgeted(geoms: crate::shapes::Shapes<'_>, tol: f64, budget: usize) -> Option>> { + match geoms { + crate::shapes::Shapes::Rows(rows) => { + let rows: Vec> = rows.rows().map(|r| r.geometry()).collect(); + map_budgeted(&rows, budget, |g| *g, |g| thin(g, tol)) + } + crate::shapes::Shapes::Copies(c) => map_budgeted(c, budget, Option::as_ref, |g| thin(g, tol)), + } } /// `build` of each item's geometry (`geometry`), in order ([`map_budgeted_on`]), on up to the @@ -712,9 +718,9 @@ mod tests { Coord::new(0.0, 0.0), ]]]))]; let before = original.clone(); - assert!(thin_budgeted(&original, 0.1, 0).is_none()); - assert!(thin_budgeted(&original, 0.1, std::mem::size_of::>()).is_none()); - let copy = thin_budgeted(&original, 0.1, 1024).unwrap(); + assert!(thin_budgeted(crate::Shapes::Copies(&original), 0.1, 0).is_none()); + assert!(thin_budgeted(crate::Shapes::Copies(&original), 0.1, std::mem::size_of::>()).is_none()); + let copy = thin_budgeted(crate::Shapes::Copies(&original), 0.1, 1024).unwrap(); assert!(cache_bytes(©) <= 1024); assert_eq!(copy, before); assert_eq!(original, before); diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 74b72e29ae..c3a458a8f4 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -87,6 +87,7 @@ fn bare(layer: &Layer) -> Layer { replacement_rev, // Caches, emptied below. projected, + projected_own, display, display_rejected: _, display_levels, @@ -164,6 +165,7 @@ fn bare(layer: &Layer) -> Layer { instance_id: *instance_id, replacement_rev: *replacement_rev, projected: projected.clone(), + projected_own: *projected_own, display: display.clone(), display_rejected: Vec::new(), display_levels: display_levels.clone(), @@ -262,6 +264,7 @@ impl LayerLook { replacement_rev, // Caches worked out from the rows, which are compared themselves. projected: _, + projected_own: _, display: _, display_rejected: _, display_levels: _, diff --git a/crates/map/src/shapes.rs b/crates/map/src/shapes.rs new file mode 100644 index 0000000000..a8df990846 --- /dev/null +++ b/crates/map/src/shapes.rs @@ -0,0 +1,139 @@ +//! A layer's geometry as a map draws it ([`crate::Layer::projected_in`]), row for row: the +//! layer's own rows, read in place, on a map in the system it holds them in (no copy is made, +//! #2032 C2f), or the copies made for another projection, or thinned for display. + +use rustgis_data::{Features, Geometry}; + +/// A layer's geometry as drawn, row for row ([`crate::Layer::projected_in`]): each row's +/// geometry, `None` for a row without one. +#[derive(Clone, Copy)] +pub enum Shapes<'a> { + /// The layer's own rows, as they are: on a map in the system the layer holds them in. + Rows(&'a Features), + /// Copies made for the map (projected, or thinned for display). + Copies(&'a [Option]), +} + +impl<'a> Shapes<'a> { + /// No rows. + pub const EMPTY: Shapes<'static> = Shapes::Copies(&[]); + + /// How many rows. + pub fn len(self) -> usize { + match self { + Shapes::Rows(f) => f.len(), + Shapes::Copies(c) => c.len(), + } + } + + pub fn is_empty(self) -> bool { + self.len() == 0 + } + + /// Row `row`'s geometry: `None` past the last row, or for a row without one. + pub fn get(self, row: usize) -> Option<&'a Geometry> { + match self { + Shapes::Rows(f) => f.geometry(row), + Shapes::Copies(c) => c.get(row)?.as_ref(), + } + } + + /// Each row's geometry, in row order. + pub fn iter(self) -> Iter<'a> { + match self { + Shapes::Rows(f) => Iter::Rows(f, 0..f.len()), + Shapes::Copies(c) => Iter::Copies(c.iter()), + } + } + + /// Each row's geometry, copied. + pub fn to_vec(self) -> Vec> { + self.iter().map(|g| g.cloned()).collect() + } + + /// Whether both are the same geometry, not a copy of it: the same rows or the same copies. + pub fn same(self, other: Shapes<'_>) -> bool { + match (self, other) { + (Shapes::Rows(a), Shapes::Rows(b)) => a.shares(b), + (Shapes::Copies(a), Shapes::Copies(b)) => std::ptr::eq(a, b), + _ => false, + } + } + + /// The copies, when these are copies: `None` for the layer's own rows. + pub fn copies(self) -> Option<&'a [Option]> { + match self { + Shapes::Rows(_) => None, + Shapes::Copies(c) => Some(c), + } + } +} + +impl std::fmt::Debug for Shapes<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl PartialEq for Shapes<'_> { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other.iter()) + } +} + +impl PartialEq<[Option]> for Shapes<'_> { + fn eq(&self, other: &[Option]) -> bool { + self.len() == other.len() && self.iter().eq(other.iter().map(Option::as_ref)) + } +} + +impl PartialEq<[Option; N]> for Shapes<'_> { + fn eq(&self, other: &[Option; N]) -> bool { + *self == other[..] + } +} + +impl<'a> IntoIterator for Shapes<'a> { + type Item = Option<&'a Geometry>; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} + +/// [`Shapes::iter`]. +#[derive(Clone)] +pub enum Iter<'a> { + Rows(&'a Features, std::ops::Range), + Copies(std::slice::Iter<'a, Option>), +} + +impl<'a> Iterator for Iter<'a> { + type Item = Option<&'a Geometry>; + + fn next(&mut self) -> Option { + match self { + Iter::Rows(f, rows) => rows.next().map(|row| f.geometry(row)), + Iter::Copies(c) => c.next().map(Option::as_ref), + } + } + + fn size_hint(&self) -> (usize, Option) { + match self { + Iter::Rows(_, rows) => rows.size_hint(), + Iter::Copies(c) => c.size_hint(), + } + } +} + +impl ExactSizeIterator for Iter<'_> {} + +impl DoubleEndedIterator for Iter<'_> { + fn next_back(&mut self) -> Option { + match self { + Iter::Rows(f, rows) => rows.next_back().map(|row| f.geometry(row)), + Iter::Copies(c) => c.next_back().map(Option::as_ref), + } + } +} diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index bcced86262..1bcc3805a4 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -10,6 +10,9 @@ use std::sync::Arc; pub(crate) struct Cache { pub areas: super::AmbiguousAreas, pub projected: Arc>>, + /// Whether the rows are drawn as they are (on a map in the source's own system), with no + /// projected copy (`projected` empty, [`crate::Layer::projected_in`]). + pub own: bool, pub extents: Arc>, pub vertices: usize, pub key: String, @@ -22,10 +25,24 @@ pub(crate) struct Cache { pub crs: Crs, } -fn base_bytes(batch: &Batch, projected: &Vec>) -> usize { +fn base_bytes(batch: &Batch, projected: &Drawn) -> usize { memory::features_bytes(&batch.features) - .saturating_add(crate::lod::cache_bytes(projected)) - .saturating_add(projected.len().saturating_mul(std::mem::size_of::())) + .saturating_add(projected.as_ref().map_or(0, crate::lod::cache_bytes)) + .saturating_add(batch.features.len().saturating_mul(std::mem::size_of::())) +} + +/// A window's rows as drawn ([`projected_rows`]): `None` when drawn as they are, with no copy. +type Drawn = Option>>; + +/// The extents, the vertices thinning can drop, and the bytes of a window's rows as drawn. +fn drawn_stats(features: &[rustgis_data::Feature], projected: &Drawn) -> (Arc>, usize, usize) { + let geoms: Vec> = match projected { + Some(p) => p.iter().map(Option::as_ref).collect(), + None => features.iter().map(|f| f.geometry.as_ref()).collect(), + }; + let extents = Arc::new(geoms.iter().map(|g| g.map_or(Extent::EMPTY, Geometry::extent)).collect()); + let vertices = geoms.iter().flatten().map(|g| crate::lod::thinnable(g)).sum(); + (extents, vertices, projected.as_ref().map_or(0, crate::lod::cache_bytes)) } fn retain_evenly(items: &mut Vec, kept: usize) { @@ -225,14 +242,16 @@ fn check_areas(expr: &Expr, held: &Dataset, features: &[rustgis_data::Feature], fn whole(batch: Batch, projection: &crate::Projection, crs: Crs) -> (Batch, Cache) { let flat = crate::projection::Flat::of(projection); let projected = projected_rows(&flat, crs, &batch.features); + let (extents, vertices, projected_bytes) = drawn_stats(&batch.features, &projected); let cache = Cache { areas: super::AmbiguousAreas::from_features_in(&batch.features, crs), - extents: Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()), - vertices: projected.iter().flatten().map(crate::lod::thinnable).sum(), + extents, + vertices, mean_bytes: 0, feature_bytes: memory::features_bytes(&batch.features), - projected_bytes: crate::lod::cache_bytes(&projected), - projected: Arc::new(projected), + projected_bytes, + own: projected.is_none(), + projected: Arc::new(projected.unwrap_or_default()), key: projection.code(), filtered: false, crs, @@ -243,13 +262,16 @@ fn whole(batch: Batch, projection: &crate::Projection, crs: Crs) -> (Batch, Cach /// Each feature's geometry, given in `crs` (the source's own system), in the map's coordinates on /// `flat`, as the map draws a layer held there ([`crate::projection::Flat::held`]): none when the /// system can't be converted, as the map draws none of such a layer. -fn projected_rows(flat: &crate::projection::Flat, crs: Crs, features: &[rustgis_data::Feature]) -> Vec> { +/// A window's rows as `flat` draws them: `None` on a map in the system they are given in, which +/// draws them as they are, with no copy (#2032 C2f). +fn projected_rows(flat: &crate::projection::Flat, crs: Crs, features: &[rustgis_data::Feature]) -> Drawn { if crs == Crs::LonLat { - return features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect(); + return Some(features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect()); } match flat.held(crs) { - Ok(held) => features.iter().map(|f| f.geometry.as_ref().map(|g| held.geometry(g).0)).collect(), - Err(_) => features.iter().map(|_| None).collect(), + Ok(held) if held.is_identity() => None, + Ok(held) => Some(features.iter().map(|f| f.geometry.as_ref().map(|g| held.geometry(g).0)).collect()), + Err(_) => Some(features.iter().map(|_| None).collect()), } } @@ -351,13 +373,7 @@ fn pad(batch: &mut Batch, bytes: usize, fields: Option) -> Result<()> { /// Thins the rows and their projection evenly until they fit three quarters of `bytes`, and /// builds the window's cache. -fn trim( - mut batch: Batch, - mut projected: Vec>, - bytes: usize, - projection: &crate::Projection, - crs: Crs, -) -> Result<(Batch, Cache)> { +fn trim(mut batch: Batch, mut projected: Drawn, bytes: usize, projection: &crate::Projection, crs: Crs) -> Result<(Batch, Cache)> { let base_budget = bytes.saturating_mul(3) / 4; // Keep room for display levels. Actual allocation accounting also handles projections // that split at a world seam and create more parts than the original geometry. @@ -376,20 +392,21 @@ fn trim( let kept = batch.features.len().saturating_mul(base_budget) / used.max(1); let kept = kept.max(1).min(batch.features.len() - 1); retain_evenly(&mut batch.features, kept); - retain_evenly(&mut projected, kept); + if let Some(p) = &mut projected { + retain_evenly(p, kept); + } batch.complete = false; } - let extents = Arc::new(projected.iter().map(|g| g.as_ref().map_or(Extent::EMPTY, Geometry::extent)).collect()); - let vertices = projected.iter().flatten().map(crate::lod::thinnable).sum(); + let (extents, vertices, projected_bytes) = drawn_stats(&batch.features, &projected); let mean_bytes = base_bytes(&batch, &projected).div_ceil(batch.features.len().max(1)); let feature_bytes = memory::features_bytes(&batch.features); - let projected_bytes = crate::lod::cache_bytes(&projected); let areas = super::AmbiguousAreas::from_features_in(&batch.features, crs); Ok(( batch, Cache { areas, - projected: Arc::new(projected), + own: projected.is_none(), + projected: Arc::new(projected.unwrap_or_default()), extents, vertices, key: projection.code(), @@ -480,6 +497,38 @@ mod tests { assert_eq!(source.read(&Request::all()).unwrap().features.len(), 600); } + /// A source in the system its map is drawn in gives a window drawn as its rows are: no copy + /// is made or counted against the budget, so more rows fit; one in another system gets a + /// converted copy (#2032 C2f). + #[test] + fn a_window_on_a_map_in_its_sources_system_makes_no_copy() { + struct InUtm(Box); + impl FeatureSource for InUtm { + fn info(&self) -> &rustgis_data::source::SourceInfo { + self.0.info() + } + fn read(&self, req: &Request) -> Result { + self.0.read(req) + } + fn coord_crs(&self) -> Crs { + Crs::Epsg(32632) + } + } + let source = InUtm(source()); + let budget = 128 * 1024; + let own = crate::Projection::Custom("EPSG:32632".into()); + let (batch, cache) = read(&source, &Request::all(), budget, &own, 0).unwrap(); + assert!(cache.own && cache.projected.is_empty() && cache.projected_bytes == 0); + assert_eq!(cache.extents.len(), batch.features.len()); + for (row, e) in batch.features.iter().zip(cache.extents.iter()) { + assert_eq!(*e, row.geometry.as_ref().unwrap().extent()); + } + let other = crate::Projection::Custom("EPSG:25832".into()); + let (copied, cache) = read(&source, &Request::all(), budget, &other, 0).unwrap(); + assert!(!cache.own && cache.projected.len() == copied.features.len()); + assert!(batch.features.len() > copied.features.len(), "{} vs {}", batch.features.len(), copied.features.len()); + } + #[test] fn installed_windows_share_the_map_budget_and_reuse_prepared_geometry() { let mut map = crate::Map::new("budget"); @@ -542,7 +591,7 @@ mod tests { let (batch, cache) = read_with_fields(source.as_ref(), &Request::all(), bytes, &crate::Projection::WebMercator, 0, Some(200)).unwrap(); assert!(batch.features.iter().all(|f| f.attrs.len() == 200)); - assert!(base_bytes(&batch, &cache.projected) <= bytes * 3 / 4); + assert!(base_bytes(&batch, &(!cache.own).then(|| cache.projected.to_vec())) <= bytes * 3 / 4); assert!(!batch.complete); assert!(read_with_fields(source.as_ref(), &Request::all(), bytes, &crate::Projection::WebMercator, 0, Some(usize::MAX)).is_err()); } @@ -669,7 +718,7 @@ mod tests { let (batch, cache) = read(&source, &Request::all(), 128 * 1024, &crate::Projection::WebMercator, 0).unwrap(); assert!(!batch.features.is_empty()); assert_eq!(batch.features.len(), cache.projected.len()); - assert!(base_bytes(&batch, &cache.projected) <= 96 * 1024); + assert!(base_bytes(&batch, &(!cache.own).then(|| cache.projected.to_vec())) <= 96 * 1024); assert_eq!(source.read(&Request::all()).unwrap().features.len(), 600); } #[test] @@ -679,10 +728,10 @@ mod tests { 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(); - let budget = base_bytes(&full, &cache.projected); + let budget = base_bytes(&full, &(!cache.own).then(|| cache.projected.to_vec())); let (batch, cache) = read(source.as_ref(), &req, budget, &projection, 0).unwrap(); assert_eq!(batch.features, full.features); - assert!(base_bytes(&batch, &cache.projected) <= budget); + assert!(base_bytes(&batch, &(!cache.own).then(|| cache.projected.to_vec())) <= budget); } #[test] fn measured_rows_read_once_and_still_reject_newly_oversized_features() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 426475cad9..d97e4d1646 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4269,7 +4269,7 @@ fn extrusions_tilted(map: &mut Map, view: &View, pm: &mut Pixmap, env: &Env) -> layer.projected_in(&flat, &key); let layer: &rustgis_map::Layer = layer; let styler = layer.styler_with(env.at_scale(Some(scale))); - let geoms: Vec> = layer.projected_cache().iter().map(Option::as_ref).collect(); + let geoms: Vec> = layer.projected_cache().iter().collect(); let draw = |target: &mut Pixmap| { effects::extrude_tilted( target, @@ -5519,7 +5519,7 @@ fn render_frame( } else if display_only { layer.display_cache().map_or(&[][..], |(g, _)| g).iter().map(Option::as_ref).collect() } else { - layer.projected_cache().iter().map(Option::as_ref).collect() + layer.projected_cache().iter().collect() }; // What the features draw from, and their extents for culling (on the flat map, cached). // Only the fills and strokes below draw thinned: the selection, labels, aggregation and @@ -5545,7 +5545,7 @@ fn render_frame( } else if complete_source { if thin_complete { chunk_thinned.iter().map(Option::as_ref).collect() } else { geoms.clone() } } else { - layer.thinned_cache(thin_tol).iter().map(Option::as_ref).collect() + layer.thinned_cache(thin_tol).iter().collect() }; let extents = if globe.is_some() { &[][..] @@ -5590,7 +5590,7 @@ fn render_frame( let level = rustgis_map::lod::level(thin_tol); let drawn_copy = if display_only { layer_meshes::Drawn::Display(level) - } else if std::ptr::eq(layer.thinned_cache(thin_tol), layer.projected_cache()) { + } else if layer.thinned_cache(thin_tol).same(layer.projected_cache()) { layer_meshes::Drawn::Projected } else { layer_meshes::Drawn::Thinned(level) @@ -7832,7 +7832,7 @@ fn guides_of( }; let drawn = || match layer.is_cached(key) { true => Some((layer.thinned_cache(ctx.view.lod_tolerance()), layer.projected_extents())), - false => layer.display_cache(), + false => layer.display_cache().map(|(g, e)| (rustgis_map::Shapes::Copies(g), e)), }; if let Some((geoms, extents)) = ctx.globe.is_none().then(drawn).flatten() { // A point the projection can't show is NaN in the copy, and breaks the line there. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b1d9d0e186..4df409dd0b 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -205,7 +205,9 @@ say), one in another system is drawn by the transformation PROJ picks between th two datums, the one for that pair, not one through WGS 84); on a world projection, such a layer goes through WGS 84 longitude/latitude. On a map in a coordinate system, Zoom To Layer, Zoom To Selection and Full Extent frame a layer in the map's system by its own coordinates, and its -simplified drawing at small scales is made from them, with nothing converted. +simplified drawing at small scales is made from them, with nothing converted. Labels, the +selection and hit-testing read its coordinates too, so the map keeps no second copy of such a +layer; a layer read in place keeps none of the view it reads either. Coordinate systems are read and transformed as PROJ 9.9.0 does, through terrio-crs. A few EPSG and ESRI codes PROJ 9.9.0 dropped or can't compute (EPSG:3752 and 22700, ESRI:10820 and 65162) From 63574b70af5981689d177d358ab9e55816b8ee9b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 13:59:10 +0100 Subject: [PATCH 04/12] fix: one notice per NaN shape (kept, with its stored box); thinning scratch counted; window row uses; own-cache extents checked; docs --- crates/data/src/source/shp.rs | 78 ++++++++++++++++++----------- crates/data/src/source/shp/tests.rs | 40 +++++++-------- crates/engine/src/tests.rs | 2 +- crates/map/src/lib.rs | 9 ++-- crates/map/src/lod.rs | 2 + crates/map/src/source/window.rs | 11 ++-- docs/user-guide/data-formats.md | 2 +- 7 files changed, 86 insertions(+), 58 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 0bddb4cd3c..4bf27cf661 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -312,7 +312,9 @@ impl ShpSource { let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); let mut deleted = 0usize; - let mut kept_no_number = 0usize; + // Shapes whose coordinates aren't numbers given without geometry, and of them those under + // a box the index takes. + let (mut kept_no_number, mut kept_boxed) = (0usize, 0usize); // The same directory, ordering, extent rules and read-only scan fallback as sampled // reads, with no interaction row cap. The index visits records without materializing // their directory or the complete feature collection in memory. @@ -321,7 +323,8 @@ impl ShpSource { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); let mut each = |i: u32, place: Place| -> Result<()> { crate::progress::step(1)?; - let mut no_number = false; + // A shape whose coordinates aren't numbers: whether its stored box is one the index takes. + let mut no_number: Option = None; if u64::from(place.len) > MAX_RECORD { skipped += 1; return Ok(()); @@ -335,12 +338,11 @@ impl ShpSource { let geometry = match parse_shape(&buf) { // A coordinate that isn't a number (NaN or infinite) has no place: the record keeps // its attributes without its geometry, as a whole read keeps it (#1985, #2032 - // C2f), and is counted where it is read. One under a stored box the index takes - // ([`index::usable`]) is counted apart too, as the index framed it by that box; a - // backwards one it can't frame, and counts as unboxed instead. + // C2f), and is counted as the read gives it, or leaves it out of an area. One under + // a stored box the index takes ([`index::usable`]) is said with it, as the index + // framed it by that box; a backwards one it can't frame, and counts as unboxed. Ok(Some(g)) if !g.is_finite() => { - boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); - no_number = true; + no_number = Some(index::usable(record_box(&buf, u64::from(place.len)))); None } Ok(Some(g)) => { @@ -367,6 +369,7 @@ impl ShpSource { // As a read by area, its box in the file's own system included, gives no rows // without a shape. if geometry.as_ref().map_or(if own.is_some() { !everywhere } else { req.extent.is_some() }, |g| !g.inside) { + boxed_off += u64::from(no_number == Some(true)); return Ok(()); } let geometry = geometry.map(|p| p.geometry); @@ -385,7 +388,8 @@ impl ShpSource { } else { vec![Value::Null; self.table.columns.len()] }; - kept_no_number += usize::from(no_number); + kept_no_number += usize::from(no_number.is_some()); + kept_boxed += usize::from(no_number == Some(true)); chunks.push(Feature { id: u64::from(i) + 1, geometry, attrs }) }; let (matched, complete) = match numbered { @@ -406,7 +410,7 @@ impl ShpSource { null_text, notes: boxed_off_note(boxed_off, false, late) .into_iter() - .chain(kept_no_number_note(kept_no_number, false)) + .chain(kept_no_number_note(kept_no_number, kept_boxed, false)) .chain(deleted_note(deleted, false).map(crate::loss::Note::from)) .chain(nonfinite_note(&self.info.fields, &nonfinite, false)) .collect(), @@ -456,7 +460,9 @@ impl FeatureSource for ShpSource { let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); let mut deleted = 0usize; - let mut kept_no_number = 0usize; + // Shapes whose coordinates aren't numbers given without geometry, and of them those under + // a box the index takes. + let (mut kept_no_number, mut kept_boxed) = (0usize, 0usize); // An extent the file's system couldn't bound (#1925) has no boxes for the index to sample // by: every record is visited, tested, and the matches sampled as they come. let late = req.extent.is_some() && bounds.is_none(); @@ -468,7 +474,8 @@ impl FeatureSource for ShpSource { if late { crate::progress::step(1)?; } - let mut no_number = false; + // A shape whose coordinates aren't numbers: whether its stored box is one the index takes. + let mut no_number: Option = None; if u64::from(place.len) > MAX_RECORD { skipped += 1; return Ok(()); @@ -481,12 +488,11 @@ impl FeatureSource for ShpSource { let geometry = match parse_shape(&buf) { // A coordinate that isn't a number (NaN or infinite) has no place: the record keeps // its attributes without its geometry, as a whole read keeps it (#1985, #2032 - // C2f), and is counted where it is read. One under a stored box the index takes - // ([`index::usable`]) is counted apart too, as the index framed it by that box; a - // backwards one it can't frame, and counts as unboxed instead. + // C2f), and is counted as the read gives it, or leaves it out of an area. One under + // a stored box the index takes ([`index::usable`]) is said with it, as the index + // framed it by that box; a backwards one it can't frame, and counts as unboxed. Ok(Some(g)) if !g.is_finite() => { - boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); - no_number = true; + no_number = Some(index::usable(record_box(&buf, u64::from(place.len)))); None } Ok(Some(g)) => match self.reproject.place(g, req) { @@ -505,6 +511,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.inside) { + boxed_off += u64::from(no_number == Some(true)); return Ok(()); } let geometry = geometry.map(|p| p.geometry); @@ -534,7 +541,8 @@ impl FeatureSource for ShpSource { if late { sample.keep(f) } else { - kept_no_number += usize::from(no_number); + kept_no_number += usize::from(no_number.is_some()); + kept_boxed += usize::from(no_number == Some(true)); features.push(f) } Ok(()) @@ -558,7 +566,7 @@ impl FeatureSource for ShpSource { // visits the whole layer, so its count is of the layer. notes: boxed_off_note(boxed_off, !late && !complete, late) .into_iter() - .chain(kept_no_number_note(kept_no_number, !late && !complete)) + .chain(kept_no_number_note(kept_no_number, kept_boxed, !late && !complete)) .chain(deleted_note(deleted, !late && !complete).map(crate::loss::Note::from)) // The values a late read decodes are of the records its sample keeps (geometry checks // aside), so its count is of a sample whenever the sample isn't the whole layer. @@ -605,14 +613,16 @@ impl FeatureSource for ShpSource { } } -/// Says how many shapes a read found with a coordinate that isn't a number, which have no geometry -/// to read ([`kept_no_number_note`]), while their stored box is one the index takes (finite and in order, [`index::usable`]): [`record_box`] doesn't read -/// the points, so the layer's extent and its index still take in those boxes. A backwards stored -/// box over such a point isn't counted here: the index can't frame it from the points, so it's -/// left out of the extent and counted with the shapes that have no usable box. A `sampled` read -/// visited only some of the matches, so its count is of the shapes it read, not of the layer. A `late` read (an area the layer's system couldn't bound, -/// #1925) visited every record and can't place a NaN shape's stored box in the area, so its count -/// is of the whole layer, and says so. +/// Says how many shapes with a coordinate that isn't a number a read by area left out (a shape +/// without geometry is in no area) while their stored box is one the index takes (finite and in +/// order, [`index::usable`]): [`record_box`] doesn't read the points, so the layer's extent and +/// its index still take in those boxes, and the area seemed to hold them. A read that gives them +/// says them with [`kept_no_number_note`]. A backwards stored box over such a point isn't counted +/// here: the index can't frame it from the points, so it's left out of the extent and counted with +/// the shapes that have no usable box. A `sampled` read visited only some of the matches, so its +/// count is of the shapes it read, not of the layer. A `late` read (an area the layer's system +/// couldn't bound, #1925) visited every record and can't place a NaN shape's stored box in the +/// area, so its count is of the whole layer, and says so. fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { if n == 0 { return Vec::new(); @@ -627,15 +637,16 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { vec![crate::loss::Note::loss( crate::loss::LossCode::DroppedGeometry, format!( - "{what} have a coordinate that isn't a number under a bounding box that is one: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" + "{what} have a coordinate that isn't a number under a bounding box that is one: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes" ), )] } /// Says how many shapes with a coordinate that isn't a number a read gave without geometry, /// keeping their attributes, in the words a whole read says it with -/// ([`crate::io`]'s Shapefile reader); of those read when the read is `sampled`. -fn kept_no_number_note(n: usize, sampled: bool) -> Option { +/// ([`crate::io`]'s Shapefile reader), and of them how many lie under a stored box the index +/// takes (`boxed`, [`boxed_off_note`]); of those read when the read is `sampled`. +fn kept_no_number_note(n: usize, boxed: usize, sampled: bool) -> Option { let what = match n { 0 => return None, n if sampled => format!("{n} of the shapes read (a sample of the layer, which may hold more)"), @@ -643,7 +654,14 @@ fn kept_no_number_note(n: usize, sampled: bool) -> Option { }; Some(crate::loss::Note::loss( crate::loss::LossCode::DroppedGeometry, - format!("{what} have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"), + format!( + "{what} have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry{}", + match boxed { + 0 => String::new(), + b if b == n => ", but the layer's extent and its index still take in their stored boxes".to_string(), + b => format!(", but the layer's extent and its index still take in the stored boxes of {b} of them"), + } + ), )) } diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 10e6385fb1..302ca75a19 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -695,11 +695,15 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( // give none of them (a shape without geometry is in no area), and the note says its count // is of the layer, not of the area. let layer = vec![format!( - "2 shape(s) in the layer (a count of the whole layer, as the area couldn't be placed in its coordinates) {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" + "2 shape(s) in the layer (a count of the whole layer, as the area couldn't be placed in its coordinates) {SAID}: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes" )]; assert_eq!(reads(src.as_ref()), ((0, 0, layer.clone()), (0, 0, layer))); - // A whole read keeps its plain count. - assert_eq!(said(&src.read(&Request::all()).unwrap().notes).first().map(|n| n.starts_with("2 shape(s) have")), Some(true)); + // A whole read gives them without geometry, and says that once, with its plain count. + let whole = src.read(&Request::all()).unwrap(); + assert!(said(&whole.notes).is_empty(), "{:?}", whole.notes); + let kept: Vec<_> = whole.notes.iter().filter(|n| n.contains("their features are kept without geometry")).collect(); + assert_eq!(kept.len(), 1, "{:?}", whole.notes); + assert!(kept[0].starts_with("2 shape(s) have"), "{:?}", kept[0]); }); std::fs::remove_dir_all(fixture).unwrap(); } @@ -770,26 +774,29 @@ fn a_nan_shape_under_a_finite_box_is_said_when_kept_without_geometry() { assert!(src.info().indexed); assert_eq!(src.info().extent, Extent::new(0.0, 0.0, 3.0, 3.0), "the stored box framed"); let one = vec![format!( - "1 shape(s) {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" + "1 shape(s) {SAID}: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes" )]; + const BOXES: &str = ", but the layer's extent and its index still take in their stored boxes"; let one_kept = vec![format!("1 shape(s) {KEPT}")]; + let one_kept_boxed = vec![format!("1 shape(s) {KEPT}{BOXES}")]; // Kept without geometry, its attributes too, as a whole read of the file keeps it. let (ds, report) = crate::source::materialize(src.as_ref()).unwrap(); assert_eq!((ds.features.len(), report.skipped), (3, 0)); assert!(ds.features[1].geometry.is_none()); let (whole, _) = crate::io::read_path(&p).unwrap(); assert_eq!(whole.features.iter().map(|f| f.geometry.is_none()).collect::>(), [false, true, false]); - assert_eq!(said(&report.messages).len(), 1, "{:?}", report.messages); - assert!(report.messages.iter().any(|m| m.ends_with(&one[0])), "{:?}", report.messages); - assert!(report.messages.iter().any(|m| m.ends_with(&one_kept[0])), "{:?}", report.messages); + // Said once: kept without geometry, under its stored box. + assert!(said(&report.messages).is_empty(), "{:?}", report.messages); + assert_eq!(kept(&report.messages).len(), 1, "{:?}", report.messages); + assert!(report.messages.iter().any(|m| m.ends_with(&one_kept_boxed[0])), "{:?}", report.messages); let all = src.read(&Request::all()).unwrap(); - assert_eq!((all.features.len(), all.skipped, said(&all.notes), kept(&all.notes)), (3, 0, one.clone(), one_kept.clone())); - // By area, over the stored box only: matched by it, given as no feature (a shape without - // geometry is in no area), its box said. + assert_eq!((all.features.len(), all.skipped, said(&all.notes), kept(&all.notes)), (3, 0, Vec::new(), one_kept_boxed.clone())); + // By area, over the stored box only: matched by it, left out (a shape without geometry is + // in no area), its box said. let area = Some(Extent::new(1.4, 1.4, 1.6, 1.6)); let by_area = src.read(&Request { extent: area, ..Request::all() }).unwrap(); assert_eq!((by_area.features.len(), by_area.skipped, said(&by_area.notes), kept(&by_area.notes)), (0, 0, one.clone(), Vec::new())); - assert_eq!(chunk_notes(src.as_ref(), None), (0, 1, one.clone(), one_kept.clone())); + assert_eq!(chunk_notes(src.as_ref(), None), (0, 1, Vec::new(), one_kept_boxed.clone())); assert_eq!(chunk_notes(src.as_ref(), area), (0, 0, one.clone(), Vec::new())); // A limited read visits a sample (here the first and third records), so its count is of // the shapes it read, not a total: the first record's point made NaN (content at 108, @@ -804,17 +811,10 @@ fn a_nan_shape_under_a_finite_box_is_said_when_kept_without_geometry() { let sample = "1 of the shapes read (a sample of the layer, which may hold more)"; assert_eq!( (some.features.len(), some.skipped, said(&some.notes), kept(&some.notes)), - ( - 2, - 0, - vec![format!( - "{sample} {SAID}: they have no geometry to read, but the layer's extent and its index still take in their stored boxes" - )], - vec![format!("{sample} {KEPT}")] - ) + (2, 0, Vec::new(), vec![format!("{sample} {KEPT}{BOXES}")]) ); // A whole read of the same file still gives the total. - assert_eq!(said(&src.read(&Request::all()).unwrap().notes), one); + assert_eq!(kept(&src.read(&Request::all()).unwrap().notes), one_kept_boxed); // The second record's stored box made backwards, (2, 2, 1, 1) at 200..232, over the same // NaN point: the index can't frame it from the points, so it's left out of the extent and // said as having no usable box, and the read doesn't claim the index took it in. Reads by diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 75de759dcf..c8b60dc229 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2108,7 +2108,7 @@ fn a_streamed_layer_says_its_view_reads_notes_once() { }; let expected: &[&str] = if nan { &[ - "roads: 1 shape(s) have a coordinate that isn't a number under a bounding box that is one: they have no geometry to read, but the layer's extent and its index still take in their stored boxes", + "roads: 1 shape(s) have a coordinate that isn't a number under a bounding box that is one: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes", ] } else { &[] diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 4faa8b6445..20dae7aed7 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1505,8 +1505,10 @@ impl Layer { &self.projected_extents } - /// The Web Mercator copies from the last [`Layer::projected`] call, without refreshing them: - /// call `projected` first (it needs `&mut self`) whenever the geometry may have changed. + /// The geometry as the last [`Layer::projected_in`] call drew it, without refreshing it: call + /// that first (it needs `&mut self`) whenever the geometry or the map may have changed. On a + /// map in the layer's own system it is the layer's rows, read in place, so a later edit shows + /// in it at once, while [`Layer::projected_extents`] stays as made until it is refreshed. pub fn projected_cache(&self) -> Shapes<'_> { shapes_of(self.projected_own, &self.dataset.features, &self.projected) } @@ -1613,7 +1615,8 @@ impl Layer { pub fn is_cached(&self, key: &str) -> bool { self.projected_for == key && self.projected_rev == self.geometry_rev - && (self.projected_own || self.projected.len() == self.dataset.features.len()) + // Its own rows read in place: their extents still made for as many rows. + && (if self.projected_own { self.projected_extents.len() } else { self.projected.len() }) == self.dataset.features.len() && self.projected_crs == Some(self.dataset.coord_crs()) } diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index aca1b42591..1a2d3eaaa9 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -194,7 +194,9 @@ pub(crate) fn cache_bytes(geoms: &Vec>) -> usize { /// budget discards only this optional display cache; drawing still uses the full projection. pub(crate) fn thin_budgeted(geoms: crate::shapes::Shapes<'_>, tol: f64, budget: usize) -> Option>> { match geoms { + // A layer's own rows: a list of their geometry to work over, counted against the budget. crate::shapes::Shapes::Rows(rows) => { + let budget = budget.checked_sub(rows.len().checked_mul(std::mem::size_of::>())?)?; let rows: Vec> = rows.rows().map(|r| r.geometry()).collect(); map_budgeted(&rows, budget, |g| *g, |g| thin(g, tol)) } diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index 1bcc3805a4..dd8bb264d1 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -38,7 +38,7 @@ type Drawn = Option>>; fn drawn_stats(features: &[rustgis_data::Feature], projected: &Drawn) -> (Arc>, usize, usize) { let geoms: Vec> = match projected { Some(p) => p.iter().map(Option::as_ref).collect(), - None => features.iter().map(|f| f.geometry.as_ref()).collect(), + None => features.iter().map(geometry).collect(), }; let extents = Arc::new(geoms.iter().map(|g| g.map_or(Extent::EMPTY, Geometry::extent)).collect()); let vertices = geoms.iter().flatten().map(|g| crate::lod::thinnable(g)).sum(); @@ -266,15 +266,20 @@ fn whole(batch: Batch, projection: &crate::Projection, crs: Crs) -> (Batch, Cach /// draws them as they are, with no copy (#2032 C2f). fn projected_rows(flat: &crate::projection::Flat, crs: Crs, features: &[rustgis_data::Feature]) -> Drawn { if crs == Crs::LonLat { - return Some(features.iter().map(|f| f.geometry.as_ref().map(|g| flat.project(g))).collect()); + return Some(features.iter().map(|f| geometry(f).map(|g| flat.project(g))).collect()); } match flat.held(crs) { Ok(held) if held.is_identity() => None, - Ok(held) => Some(features.iter().map(|f| f.geometry.as_ref().map(|g| held.geometry(g).0)).collect()), + Ok(held) => Some(features.iter().map(|f| geometry(f).map(|g| held.geometry(g).0)).collect()), Err(_) => Some(features.iter().map(|_| None).collect()), } } +/// A window row's geometry. +fn geometry(f: &rustgis_data::Feature) -> Option<&Geometry> { + f.geometry.as_ref() +} + #[cfg(test)] fn read( source: &dyn FeatureSource, diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index aa08bd68ed..c8cdcb3868 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -20,7 +20,7 @@ export names its feature. | --- | --- | --- | --- | | GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system is the layer's own: its coordinates are kept as the file holds them and drawn in the map's projection (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted is kept as the file holds it and counted in a notice; it doesn't draw. One whose coordinates convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers) is kept too, and a notice says it may draw out of place (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, in English or another language such as `經度`/`緯度`, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within the size read into memory of expanded text (256 MiB in the web app); decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | -| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry, read whole or in place, and is counted in a notice. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | +| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry when the whole layer is read, in place too, and is counted in a notice; a view of an area, which holds no feature without geometry, leaves it out. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | | dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | | KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder` or `style` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | | GPX | `.gpx` | Add Data, drop the file, or upload it in the web app | Waypoints, routes, tracks (one line per track, its segments as parts) and track points (with elevation and time) as separate layers. | From 7680879894799898fc8d7bea827313039061d7e7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 14:25:33 +0100 Subject: [PATCH 05/12] test(engine): a streamed Shapefile's NaN shape is kept without geometry, as a whole read keeps it --- crates/engine/src/tests.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c8b60dc229..bdf988b865 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -60871,9 +60871,9 @@ fn a_save_refuses_coordinates_that_arent_numbers_and_keeps_the_file() { assert_eq!(t.map().layer_by_name("ways").unwrap().dataset.features.len(), 3); } -/// A Shapefile read in place (streamed) leaves out a shape with a coordinate that isn't a number, -/// counted, as one it can't convert (#1985): nothing NaN reaches the map. Read whole, the feature -/// keeps its attributes without geometry. Either way the project saves and opens again. +/// A Shapefile shape with a coordinate that isn't a number keeps its attributes without geometry, +/// counted, read whole or in place (streamed; before #2032 C2f the streamed read left it out): +/// nothing NaN reaches the map, and the project saves and opens again. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_shapefile_coordinate_that_isnt_a_number_reaches_no_layer() { @@ -60908,15 +60908,12 @@ fn a_shapefile_coordinate_that_isnt_a_number_reaches_no_layer() { t.run("layer.loadAll", &json!({"layer": id})).unwrap(); } let notices: Vec = t.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - let said = if stream { - "pts: 1 row couldn't be read and was left out" - } else { - "pts: 1 shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry" - }; - assert!(notices.iter().any(|n| n == said), "stream {stream}: {notices:?}"); + let said = "1 shape(s) have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"; + assert_eq!(notices.iter().filter(|n| n.contains(said)).count(), 1, "stream {stream}: {notices:?}"); + assert!(!notices.iter().any(|n| n.contains("couldn't be read")), "stream {stream}: {notices:?}"); let geometries: Vec<_> = t.map().layer(id).unwrap().dataset.features.iter().map(|f| f.geometry.clone()).collect(); let kept = Some(Geometry::Point(Coord::new(11.0, 21.0))); - assert_eq!(geometries, if stream { vec![kept] } else { vec![None, kept] }, "stream {stream}"); + assert_eq!(geometries, vec![None, kept], "stream {stream}"); let saved = dir.join(format!("p-{stream}.rgis")); t.run("project.saveAs", &json!({"path": saved})).unwrap(); Session::new(Project::default()).run("project.open", &json!({"path": saved})).unwrap(); From a21d8a5c2c2556761d8cbd49a3a610c2e37996c7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 14:59:39 +0100 Subject: [PATCH 06/12] fix: a Shapefile read by a box in its own system gives no shape without geometry; an edit drops own rows from the projected cache until drawn again --- crates/data/src/source/shp.rs | 6 +++++- crates/data/src/source/shp/tests.rs | 5 +++++ crates/map/src/lib.rs | 10 ++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 4bf27cf661..dbdc8700a1 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -467,6 +467,10 @@ impl FeatureSource for ShpSource { // by: every record is visited, tested, and the matches sampled as they come. let late = req.extent.is_some() && bounds.is_none(); let mut sample = super::Sampler::new(limit); + // A read of an area, in longitude/latitude or in the file's own system, which holds no + // shape without geometry; a box over the whole plane in its own system is no area, as in + // `visit_with`. + let by_area = req.extent.is_some() || self.reproject.own_box(req).is_some_and(|b| b != super::whole_plane()); if late { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); } @@ -510,7 +514,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.inside) { + if geometry.as_ref().map_or(by_area, |g| !g.inside) { boxed_off += u64::from(no_number == Some(true)); return Ok(()); } diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 302ca75a19..f449b30b32 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -698,6 +698,11 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( "2 shape(s) in the layer (a count of the whole layer, as the area couldn't be placed in its coordinates) {SAID}: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes" )]; assert_eq!(reads(src.as_ref()), ((0, 0, layer.clone()), (0, 0, layer))); + // A box in the file's own system is an area too, which holds no shape without geometry: + // only the line with a place. + let own = Some((crs, Extent::new(-1e7, -1e7, 1e7, 1e7))); + let boxed = src.read(&Request { own, ..Request::all() }).unwrap(); + assert_eq!(boxed.features.iter().map(|f| f.geometry.is_some()).collect::>(), [true]); // A whole read gives them without geometry, and says that once, with its plain count. let whole = src.read(&Request::all()).unwrap(); assert!(said(&whole.notes).is_empty(), "{:?}", whole.notes); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 20dae7aed7..d98b49fabe 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -1507,8 +1507,9 @@ impl Layer { /// The geometry as the last [`Layer::projected_in`] call drew it, without refreshing it: call /// that first (it needs `&mut self`) whenever the geometry or the map may have changed. On a - /// map in the layer's own system it is the layer's rows, read in place, so a later edit shows - /// in it at once, while [`Layer::projected_extents`] stays as made until it is refreshed. + /// map in the layer's own system it is the layer's rows, read in place, row for row with + /// [`Layer::projected_extents`]; an edit marked ([`Layer::touch_geometry`]) leaves none until + /// it is drawn again, so the rows aren't paired with extents made before it. pub fn projected_cache(&self) -> Shapes<'_> { shapes_of(self.projected_own, &self.dataset.features, &self.projected) } @@ -1629,6 +1630,10 @@ impl Layer { /// Marks geometry as changed. pub fn touch_geometry(&mut self) { self.geometry_rev = self.geometry_rev.wrapping_add(1); + // Its own rows, read in place as the projected geometry, are no longer what its extents + // and thinned copies were made from: until drawn again, there is none, as for a copy + // made from geometry since changed ([`Layer::projected_cache`]). + self.projected_own = false; } /// Puts the selection in range, in order and with each row once: the state selecting leaves @@ -4504,6 +4509,7 @@ mod tests { l.dataset.features[0].geometry = Some(Geometry::Line(vec![run[..2].to_vec()])); l.touch_geometry(); assert!(!l.is_cached("utm")); + assert!(l.projected_cache().is_empty(), "the rows aren't paired with extents made before the edit"); assert_eq!(l.projected_in(&own, "utm").get(0), Some(&Geometry::Line(vec![run[..2].to_vec()]))); // A copy of the layer (an undo snapshot, a drawing off the UI thread) shares it. let copy = l.clone(); From eaae06d3912e3ec3287fd35ce0303ba804368c87 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 15:55:43 +0100 Subject: [PATCH 07/12] fix(data): a Shapefile read by a box over the whole plane in its own system reads every record; row-use count down to 767 --- crates/data/src/source/shp.rs | 5 ++++- crates/data/src/source/shp/tests.rs | 15 +++++++++++++++ xtask/row-uses.txt | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index dbdc8700a1..5b9af69fb7 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -470,6 +470,7 @@ impl FeatureSource for ShpSource { // A read of an area, in longitude/latitude or in the file's own system, which holds no // shape without geometry; a box over the whole plane in its own system is no area, as in // `visit_with`. + let everywhere = req.extent.is_none() && self.reproject.own_box(req) == Some(super::whole_plane()); let by_area = req.extent.is_some() || self.reproject.own_box(req).is_some_and(|b| b != super::whole_plane()); if late { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); @@ -556,7 +557,9 @@ impl FeatureSource for ShpSource { features = std::mem::take(&mut sample.items); (sample.seen(), sample.complete()) } else { - self.index.visit(bounds, limit, &mut each)? + // A box over the whole plane narrows nothing: every record, those without a usable + // box too, as `visit_with` reads them. + self.index.visit(bounds.filter(|_| !everywhere), limit, &mut each)? }; Ok(Batch { features, diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index f449b30b32..56e06f3bfa 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -703,6 +703,21 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( let own = Some((crs, Extent::new(-1e7, -1e7, 1e7, 1e7))); let boxed = src.read(&Request { own, ..Request::all() }).unwrap(); assert_eq!(boxed.features.iter().map(|f| f.geometry.is_some()).collect::>(), [true]); + // A box over the whole plane in its own system is no area: every record, as a whole read + // gives them, one without a usable box too (the first record's stored box made + // backwards: its corners at 112..144 swapped). + let p = write("nan_unboxed.shp"); + let mut b = std::fs::read(&p).unwrap(); + b[156..164].copy_from_slice(&f64::NAN.to_le_bytes()); + let (lo, hi) = (b[112..128].to_vec(), b[128..144].to_vec()); + b[112..128].copy_from_slice(&hi); + b[128..144].copy_from_slice(&lo); + std::fs::write(&p, b).unwrap(); + let unboxed = open_path(&p, None).unwrap(); + let plane = Request { own: Some((crs, crate::source::whole_plane())), ..Request::all() }; + let all = |r: &Batch| r.features.iter().map(|f| f.geometry.is_some()).collect::>(); + assert_eq!(all(&unboxed.read(&plane).unwrap()), [false, true, true]); + assert_eq!(all(&unboxed.read(&Request::all()).unwrap()), [false, true, true]); // A whole read gives them without geometry, and says that once, with its plain count. let whole = src.read(&Request::all()).unwrap(); assert!(said(&whole.notes).is_empty(), "{:?}", whole.notes); diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 5c52ff9646..67af684444 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 768 +count = 767 From 3ed0a1019a63c21741641df8b21f20616b2ec51a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 22:34:31 +0100 Subject: [PATCH 08/12] fix(data): a streamed Shapefile read in chunks by an extent and a whole-plane box takes it as an area, as a sampled read does; test name says the feature is kept --- crates/data/src/source/shp.rs | 12 +++++++----- crates/data/src/source/shp/tests.rs | 13 +++++++++++++ crates/engine/src/tests.rs | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 5b9af69fb7..d1057eb457 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -285,10 +285,11 @@ impl ShpSource { let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let req = Request { limit: usize::MAX, ..*req }; // The request's box in the file's own system, when it is one (a box in another system - // is read as if absent), and whether it is one over the whole plane, which narrows - // nothing: every record, those without a box too, as a whole read. + // is read as if absent), and whether it is one over the whole plane with no extent + // beside it, which narrows nothing: every record, those without a box too, as a whole + // read (and as `read` decides). let own = self.reproject.own_box(&req); - let everywhere = own == Some(super::whole_plane()); + let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); let extent = self.reproject.request_box(&req).filter(|_| !everywhere); if extent.is_some_and(|e| e.is_empty()) { return Ok(Batch { complete: true, ..Batch::default() }); @@ -470,8 +471,9 @@ impl FeatureSource for ShpSource { // A read of an area, in longitude/latitude or in the file's own system, which holds no // shape without geometry; a box over the whole plane in its own system is no area, as in // `visit_with`. - let everywhere = req.extent.is_none() && self.reproject.own_box(req) == Some(super::whole_plane()); - let by_area = req.extent.is_some() || self.reproject.own_box(req).is_some_and(|b| b != super::whole_plane()); + let own = self.reproject.own_box(req); + let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); + let by_area = req.extent.is_some() || own.is_some() && !everywhere; if late { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); } diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 56e06f3bfa..0bf6cf6add 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -718,6 +718,19 @@ fn a_nan_shape_outside_an_area_its_system_cant_bound_is_counted_as_of_the_layer( let all = |r: &Batch| r.features.iter().map(|f| f.geometry.is_some()).collect::>(); assert_eq!(all(&unboxed.read(&plane).unwrap()), [false, true, true]); assert_eq!(all(&unboxed.read(&Request::all()).unwrap()), [false, true, true]); + // With an extent beside it, the whole-plane box is an area again, read alike sampled and + // in chunks: the index takes no record without a usable box, and no shape without + // geometry is in an area. + let both = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), ..plane }; + let mut chunked = Vec::new(); + unboxed + .visit_request_chunks(&both, 1 << 20, &mut |f| { + chunked.extend(f.iter().map(|f| f.geometry.is_some())); + Ok(()) + }) + .unwrap(); + assert_eq!(all(&unboxed.read(&both).unwrap()), [true, true]); + assert_eq!(chunked, [true, true]); // A whole read gives them without geometry, and says that once, with its plain count. let whole = src.read(&Request::all()).unwrap(); assert!(said(&whole.notes).is_empty(), "{:?}", whole.notes); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bdf988b865..3da2654d5e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -60876,7 +60876,7 @@ fn a_save_refuses_coordinates_that_arent_numbers_and_keeps_the_file() { /// nothing NaN reaches the map, and the project saves and opens again. #[cfg(not(target_arch = "wasm32"))] #[test] -fn a_shapefile_coordinate_that_isnt_a_number_reaches_no_layer() { +fn a_shapefile_coordinate_that_isnt_a_number_keeps_its_feature_without_geometry() { use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; // Removed however the test ends. struct Dir(std::path::PathBuf); From ae345b758cab063c5eee7a0eed10556e3f356197 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Thu, 26 Nov 2026 23:36:53 +0100 Subject: [PATCH 09/12] refactor: one rule for how a request narrows a Shapefile read; a streamed window's stats in one walk, with no list of its rows --- crates/data/src/source/shp.rs | 36 +++++++++++++++++++++------------ crates/map/src/source/window.rs | 14 ++++++++----- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index d1057eb457..3192cb491a 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -270,7 +270,27 @@ impl ShpSource { } } +/// How a request narrows a read of the file ([`ShpSource::narrowing`]), the same for a sampled +/// read and a visit in chunks. +struct Narrowing { + /// The request's box in the file's own system, when it is one (a box in another system is + /// read as if absent). + own: Option, + /// A box over the whole plane in its own system with no extent beside it, which narrows + /// nothing: every record, those without a box too, as a whole read. + everywhere: bool, + /// A read of an area, in longitude/latitude or in the file's own system, which holds no + /// shape without geometry. + by_area: bool, +} + impl ShpSource { + fn narrowing(&self, req: &Request) -> Narrowing { + let own = self.reproject.own_box(req); + let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); + Narrowing { own, everywhere, by_area: req.extent.is_some() || own.is_some() && !everywhere } + } + /// A complete visit of a request's records, or of those numbered `numbered` (from 0, in /// order), parsed and given a chunk at a time ([`FeatureSource::visit_request_chunks`], /// [`FeatureSource::visit_ids_chunks`]). Only a whole read looks at the stored boxes. @@ -284,12 +304,7 @@ impl ShpSource { let encoding = self.encoding.decoder(); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let req = Request { limit: usize::MAX, ..*req }; - // The request's box in the file's own system, when it is one (a box in another system - // is read as if absent), and whether it is one over the whole plane with no extent - // beside it, which narrows nothing: every record, those without a box too, as a whole - // read (and as `read` decides). - let own = self.reproject.own_box(&req); - let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); + let Narrowing { own, everywhere, by_area } = self.narrowing(&req); let extent = self.reproject.request_box(&req).filter(|_| !everywhere); if extent.is_some_and(|e| e.is_empty()) { return Ok(Batch { complete: true, ..Batch::default() }); @@ -369,7 +384,7 @@ impl ShpSource { // As in `read`, the shape itself is checked. // As a read by area, its box in the file's own system included, gives no rows // without a shape. - if geometry.as_ref().map_or(if own.is_some() { !everywhere } else { req.extent.is_some() }, |g| !g.inside) { + if geometry.as_ref().map_or(by_area, |g| !g.inside) { boxed_off += u64::from(no_number == Some(true)); return Ok(()); } @@ -468,12 +483,7 @@ impl FeatureSource for ShpSource { // by: every record is visited, tested, and the matches sampled as they come. let late = req.extent.is_some() && bounds.is_none(); let mut sample = super::Sampler::new(limit); - // A read of an area, in longitude/latitude or in the file's own system, which holds no - // shape without geometry; a box over the whole plane in its own system is no area, as in - // `visit_with`. - let own = self.reproject.own_box(req); - let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); - let by_area = req.extent.is_some() || own.is_some() && !everywhere; + let Narrowing { everywhere, by_area, .. } = self.narrowing(req); if late { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); } diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index dd8bb264d1..5e1171e952 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -36,12 +36,16 @@ type Drawn = Option>>; /// The extents, the vertices thinning can drop, and the bytes of a window's rows as drawn. fn drawn_stats(features: &[rustgis_data::Feature], projected: &Drawn) -> (Arc>, usize, usize) { - let geoms: Vec> = match projected { - Some(p) => p.iter().map(Option::as_ref).collect(), - None => features.iter().map(geometry).collect(), + // One walk over the rows as drawn, with no list of them beside the window. + let mut vertices = 0; + let mut extent = |g: Option<&Geometry>| { + vertices += g.map_or(0, crate::lod::thinnable); + g.map_or(Extent::EMPTY, Geometry::extent) }; - let extents = Arc::new(geoms.iter().map(|g| g.map_or(Extent::EMPTY, Geometry::extent)).collect()); - let vertices = geoms.iter().flatten().map(|g| crate::lod::thinnable(g)).sum(); + let extents = Arc::new(match projected { + Some(p) => p.iter().map(|g| extent(g.as_ref())).collect(), + None => features.iter().map(|f| extent(geometry(f))).collect(), + }); (extents, vertices, projected.as_ref().map_or(0, crate::lod::cache_bytes)) } From ba1b1a9bd6fea8504d7defaf007eb2c71d593223 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 09:23:55 +0100 Subject: [PATCH 10/12] perf(map): a level of a layer's own rows is built reading them in place, with no list of them taken from the display budget --- crates/map/src/lod.rs | 80 +++++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 22 deletions(-) diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index 1a2d3eaaa9..0c4dd66eb6 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -194,17 +194,13 @@ pub(crate) fn cache_bytes(geoms: &Vec>) -> usize { /// budget discards only this optional display cache; drawing still uses the full projection. pub(crate) fn thin_budgeted(geoms: crate::shapes::Shapes<'_>, tol: f64, budget: usize) -> Option>> { match geoms { - // A layer's own rows: a list of their geometry to work over, counted against the budget. - crate::shapes::Shapes::Rows(rows) => { - let budget = budget.checked_sub(rows.len().checked_mul(std::mem::size_of::>())?)?; - let rows: Vec> = rows.rows().map(|r| r.geometry()).collect(); - map_budgeted(&rows, budget, |g| *g, |g| thin(g, tol)) - } + // A layer's own rows, read in place: no list of them beside the level. + crate::shapes::Shapes::Rows(_) => map_budgeted_at(geoms.len(), budget, |row| geoms.get(row), |g| thin(g, tol)), crate::shapes::Shapes::Copies(c) => map_budgeted(c, budget, Option::as_ref, |g| thin(g, tol)), } } -/// `build` of each item's geometry (`geometry`), in order ([`map_budgeted_on`]), on up to the +/// `build` of each item's geometry (`geometry`), in order ([`map_budgeted_rows`]), on up to the /// user's thread count ([`rustgis_data::threads`]): one below [`THREADS_FROM_VERTICES`], and no /// more than [`rustgis_data::memory::thread_scratch`] holds, beyond one thread's, with each thread /// building the biggest row at once ([`row_scratch`]). @@ -213,11 +209,21 @@ fn map_budgeted( budget: usize, geometry: impl Fn(&T) -> Option<&Geometry> + Sync, build: impl Fn(&Geometry) -> Geometry + Sync, +) -> Option>> { + map_budgeted_at(items.len(), budget, |i| geometry(&items[i]), build) +} + +/// [`map_budgeted`] of rows `0..len`, each row's geometry read by `geometry` where it is. +fn map_budgeted_at<'g>( + len: usize, + budget: usize, + geometry: impl Fn(usize) -> Option<&'g Geometry> + Sync, + build: impl Fn(&Geometry) -> Geometry + Sync, ) -> Option>> { let (total, biggest) = - items.iter().filter_map(&geometry).fold((0usize, 0usize), |(t, b), g| (t.saturating_add(vertices(g)), b.max(row_scratch(g)))); - let threads = threads_for(total, biggest, rustgis_data::threads::for_items(items.len()), rustgis_data::memory::thread_scratch()); - map_budgeted_on(items, budget, threads, |item| geometry(item).map(&build)) + (0..len).filter_map(&geometry).fold((0usize, 0usize), |(t, b), g| (t.saturating_add(vertices(g)), b.max(row_scratch(g)))); + let threads = threads_for(total, biggest, rustgis_data::threads::for_items(len), rustgis_data::memory::thread_scratch()); + map_budgeted_rows(len, budget, threads, |row| geometry(row).map(&build)) } /// The threads to build a level of `total` vertices on, the biggest row taking `biggest` bytes to @@ -242,33 +248,44 @@ fn row_scratch(g: &Geometry) -> usize { vertices(g).saturating_mul(SCRATCH_PER_VERTEX).saturating_add(parts.saturating_mul(SCRATCH_PER_PART)) } -/// `build` of each item, in order, on up to `threads` threads taking turns at chunks of rows (at +/// [`map_budgeted_rows`] of `items`. +#[cfg(test)] +fn map_budgeted_on( + items: &[T], + budget: usize, + threads: usize, + build: impl Fn(&T) -> Option + Sync, +) -> Option>> { + map_budgeted_rows(items.len(), budget, threads, |i| build(&items[i])) +} + +/// `build` of each row of `0..len`, given its number, in order, on up to `threads` threads taking turns at chunks of rows (at /// most [`CHUNK_ROWS`], and eight turns a thread where the rows allow); /// `None` when the copy (a slot a row, and each geometry's heap) takes more than `budget` bytes, /// as one thread would find it. Each row is built on its own, so the copy is the same on any /// number of threads. Past the budget the threads stop after the row they are on: at most one row /// each beyond it is made, and dropped. A thread the system refuses costs speed: the others, and /// this one, take its rows. -fn map_budgeted_on( - items: &[T], +fn map_budgeted_rows( + len: usize, budget: usize, threads: usize, - build: impl Fn(&T) -> Option + Sync, + build: impl Fn(usize) -> Option + Sync, ) -> Option>> { - let slots = items.len().checked_mul(std::mem::size_of::>())?; + let slots = len.checked_mul(std::mem::size_of::>())?; let left = budget.checked_sub(slots)?; - let mut copy: Vec> = Vec::with_capacity(items.len()); - copy.resize_with(items.len(), || None); + let mut copy: Vec> = Vec::with_capacity(len); + copy.resize_with(len, || None); let (used, over, next) = (AtomicUsize::new(0), AtomicBool::new(false), AtomicUsize::new(0)); - type Chunk<'a, T> = Mutex])>>; - let rows = items.len().div_ceil(threads.max(1).saturating_mul(8)).clamp(1, CHUNK_ROWS); - let chunks: Vec> = items.chunks(rows).zip(copy.chunks_mut(rows)).map(|c| Mutex::new(Some(c))).collect(); + type Chunk<'a> = Mutex])>>; + let rows = len.div_ceil(threads.max(1).saturating_mul(8)).clamp(1, CHUNK_ROWS); + let chunks: Vec = copy.chunks_mut(rows).enumerate().map(|(i, out)| Mutex::new(Some((i * rows, out)))).collect(); let work = || { while !over.load(Ordering::Relaxed) { let Some(chunk) = chunks.get(next.fetch_add(1, Ordering::Relaxed)) else { break }; // Never held while a row is built, so never poisoned; if it were, its rows still are. - let Some((rows, out)) = chunk.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { continue }; - for (row, out) in rows.iter().zip(out) { + let Some((first, out)) = chunk.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take() else { continue }; + for (row, out) in (first..).zip(out) { let g = build(row); let bytes = g.as_ref().map_or(0, heap_bytes); // Bytes held in memory: their sum fits. @@ -728,6 +745,25 @@ mod tests { assert_eq!(original, before); } + /// A layer's own rows are thinned in place: within the same budget as copies of them, with + /// nothing beside the level counted, so a layer thinned from its copies is thinned from its + /// rows too, at the smallest budget either takes. + #[test] + fn a_level_of_a_layers_own_rows_takes_the_budget_its_copies_take() { + let square = + Geometry::Polygon(vec![vec![vec![Coord::new(0.0, 0.0), Coord::new(10.0, 0.0), Coord::new(10.0, 10.0), Coord::new(0.0, 0.0)]]]); + let mut ds = rustgis_data::Dataset::new("squares", rustgis_data::GeometryType::Polygon, vec![]); + for _ in 0..3 { + ds.push(Some(square.clone()), vec![]); + } + ds.push(None, vec![]); + let copies: Vec<_> = (0..ds.features.len()).map(|row| ds.features.geometry(row).cloned()).collect(); + let takes = cache_bytes(&thin_budgeted(crate::Shapes::Copies(&copies), 0.1, usize::MAX).unwrap()); + let rows = crate::Shapes::Rows(&ds.features); + assert_eq!(thin_budgeted(rows, 0.1, takes).unwrap(), thin_budgeted(crate::Shapes::Copies(&copies), 0.1, takes).unwrap()); + assert!(thin_budgeted(rows, 0.1, takes - 1).is_none()); + } + #[test] fn thinning_keeps_ends_and_the_vertices_the_shape_needs() { // A straight run keeps its ends only, however long; a corner is kept. From bf69cc452acda4b41b50339deedaef76f8eea8de Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 12:50:21 +0100 Subject: [PATCH 11/12] fix: shapes an area read leaves out are said as dropped features again; a test from main reads Shapes; by_area parenthesised --- crates/data/src/source/shp.rs | 4 ++-- crates/data/src/source/shp/tests.rs | 6 +++--- crates/map/src/lib.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 3192cb491a..d063459f0b 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -288,7 +288,7 @@ impl ShpSource { fn narrowing(&self, req: &Request) -> Narrowing { let own = self.reproject.own_box(req); let everywhere = req.extent.is_none() && own == Some(super::whole_plane()); - Narrowing { own, everywhere, by_area: req.extent.is_some() || own.is_some() && !everywhere } + Narrowing { own, everywhere, by_area: req.extent.is_some() || (own.is_some() && !everywhere) } } /// A complete visit of a request's records, or of those numbered `numbered` (from 0, in @@ -654,7 +654,7 @@ fn boxed_off_note(n: u64, sampled: bool, late: bool) -> Vec { format!("{n} shape(s)") }; vec![crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, + crate::loss::LossCode::DroppedFeature, format!( "{what} have a coordinate that isn't a number under a bounding box that is one: they have no geometry, so the read leaves them out, but the layer's extent and its index still take in their stored boxes" ), diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index 0bf6cf6add..bf3556a68f 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -762,13 +762,13 @@ fn a_nan_shape_under_a_finite_box_is_said_when_kept_without_geometry() { }; const SAID: &str = "have a coordinate that isn't a number under a bounding box that is one"; const KEPT: &str = "have a coordinate that isn't a number (NaN or infinite): their features are kept without geometry"; - // Each read says the shapes it gave without geometry as dropped geometry, which the - // checks below see. + // A read says the shapes it gave without geometry as dropped geometry, and those an area + // read left out as dropped features, which the checks below see. let said = |notes: &[crate::loss::Note]| { notes .iter() .filter(|n| n.contains(SAID)) - .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedGeometry), "{n:?}")) + .inspect(|n| assert_eq!(n.loss, Some(crate::loss::LossCode::DroppedFeature), "{n:?}")) .map(|n| n.text.clone()) .collect::>() }; diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index e27904c66a..d88aa6c0b1 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -5358,7 +5358,7 @@ mod tests { let id = m.add_dataset(d); let at = |x: f64, y: f64| lonlat_to_merc(Coord::new(x, y)); let outside = at(-50.0, 5.0); - assert!(m.layers[0].projected()[0].as_ref().unwrap().hit(outside, 1000.0), "the gap lets the inside out"); + assert!(m.layers[0].projected().get(0).unwrap().hit(outside, 1000.0), "the gap lets the inside out"); assert_eq!(m.hits_at(outside, 1000.0, 1e6, |_| true, false, 10), vec![]); assert_eq!(m.hits_at(at(5.0, 5.0), 1000.0, 1e6, |_| true, false, 10), vec![(id, 0)]); assert_eq!(m.hits_at(at(10.0, 5.0), 1000.0, 1e6, |_| true, false, 10), vec![(id, 0)]); From d53f1526019bcb1d3de32a10d022aacd2a5b6f29 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 13:11:10 +0100 Subject: [PATCH 12/12] docs(map): reflow map_budgeted_rows doc --- crates/map/src/lod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/map/src/lod.rs b/crates/map/src/lod.rs index 0c4dd66eb6..eed912d573 100644 --- a/crates/map/src/lod.rs +++ b/crates/map/src/lod.rs @@ -259,8 +259,9 @@ fn map_budgeted_on( map_budgeted_rows(items.len(), budget, threads, |i| build(&items[i])) } -/// `build` of each row of `0..len`, given its number, in order, on up to `threads` threads taking turns at chunks of rows (at -/// most [`CHUNK_ROWS`], and eight turns a thread where the rows allow); +/// `build` of each row of `0..len`, given its number, in order, on up to `threads` threads +/// taking turns at chunks of rows (at most [`CHUNK_ROWS`], and eight turns a thread where the +/// rows allow); /// `None` when the copy (a slot a row, and each geometry's heap) takes more than `budget` bytes, /// as one thread would find it. Each row is built on its own, so the copy is the same on any /// number of threads. Past the budget the threads stop after the row they are on: at most one row