From 2503b1490135a27b3d0e28d9c452b24dd8696a78 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 13:01:09 +0100 Subject: [PATCH 1/2] LiDAR points held in the file's own system; LiDAR, MySQL and SQL Server keep places with no longitude/latitude (#2032 C2f-4b-3) --- crates/data/src/lidar.rs | 153 +++++++++++++++++------- crates/data/src/source/lidar.rs | 66 +++++++--- crates/data/src/source/mod.rs | 35 +++--- crates/data/src/source/mysql.rs | 18 +-- crates/data/src/source/own_box_tests.rs | 21 ++++ crates/data/src/source/sqlserver.rs | 13 +- docs/user-guide/data-formats.md | 20 ++-- 7 files changed, 232 insertions(+), 94 deletions(-) diff --git a/crates/data/src/lidar.rs b/crates/data/src/lidar.rs index 76532a5a5b..ffdf896ece 100644 --- a/crates/data/src/lidar.rs +++ b/crates/data/src/lidar.rs @@ -6,7 +6,7 @@ use std::io::{Read, Seek, SeekFrom}; use crate::raster::Crs; use crate::{DataError, Dataset, Feature, Field, FieldType, Geometry, GeometryType, ReadReport, Result, Value}; -use rustgis_geom::Coord; +use rustgis_geom::{Coord, Extent}; /// Most points read whole; larger files are sampled only for display. pub const MAX_POINTS: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; @@ -232,11 +232,12 @@ fn point(h: &Header, rec: &[u8]) -> Option { Some(Point { x, y, z, intensity, class, ret, rgb }) } -/// Reads a LAS or LAZ file in longitude/latitude when the file says its coordinate system -/// (or `crs` gives it). Refuses files over [`MAX_POINTS`] or missing records; coordinate -/// conversion failures remain counted skips. +/// Reads a LAS or LAZ file, its points kept as the file holds them, held in the coordinate system +/// it says (or `crs` gives) when RustGIS converts it ([`Dataset::held_in`]). Points with no place +/// in longitude/latitude are kept too, and said. Refuses files over [`MAX_POINTS`] or missing +/// records; points with a coordinate that isn't a number are counted skips. pub fn read(r: R, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { - let (ds, report, count) = read_points(r, name, crs, false)?; + let Cloud { ds, report, count, .. } = read_points(r, name, crs, false)?; let read = (ds.features.len() as u64).saturating_add(report.skipped as u64); if read < count { return Err(DataError::Format(format!( @@ -246,13 +247,24 @@ pub fn read(r: R, name: &str, crs: Option) -> Ok((ds, report)) } +/// A cloud [`read_points`] read. +pub(crate) struct Cloud { + pub(crate) ds: Dataset, + pub(crate) report: ReadReport, + /// The header's point count. + pub(crate) count: u64, + /// For a display sample of points held in a system other than longitude/latitude: each + /// point's place there, in the order of the features (NaN for one with none). + pub(crate) places: Option>, +} + /// Reads a display sample, retaining the header's original point count for whole-read checks. -pub(crate) fn read_sample(r: R, name: &str) -> Result<(Dataset, ReadReport, u64)> { +pub(crate) fn read_sample(r: R, name: &str) -> Result { read_points(r, name, None, true) } /// Shared decoder; only a display read may sample an oversized cloud. -fn read_points(mut r: R, name: &str, crs: Option, sample: bool) -> Result<(Dataset, ReadReport, u64)> { +fn read_points(mut r: R, name: &str, crs: Option, sample: bool) -> Result { let mut head = vec![0u8; 375]; r.seek(SeekFrom::Start(0))?; let got = read_up_to(&mut r, &mut head)?; @@ -323,7 +335,7 @@ fn read_points(mut r: R, name: &str, crs: Option(mut r: R, name: &str, crs: Option 255; - let mut lost = 0usize; + // Kept as the file holds them, held in its system when RustGIS converts it (#2032 C2f-4b). + // Each point is converted once to be checked: one with no place in longitude/latitude is + // kept too and counted, and a sample keeps the places for its reads to test. + let (mut not_numbers, mut unplaced, mut beyond) = (0usize, 0usize, 0usize); + let mut places = (sample && transform.is_some()).then(Vec::new); for (id, p) in points.into_iter().enumerate() { let c = Coord::new(p.x, p.y); if !c.is_finite() { - lost += 1; + not_numbers += 1; continue; } - let c = match &transform { - Some(t) => match t.to_lonlat(c) { - Some(c) => c, - None => { - lost += 1; - ds.crs_incomplete = true; - continue; - } - }, - None => c, - }; + if let Some(t) = &transform { + let place = t.to_lonlat(c).filter(|l| l.is_finite()); + match place { + None => unplaced += 1, + Some(l) if Extent::new(l.x, l.y, l.x, l.y).beyond_lonlat() => beyond += 1, + Some(_) => {} + } + if let Some(places) = &mut places { + places.push(place.unwrap_or(Coord::new(f64::NAN, f64::NAN))); + } + } let mut attrs = vec![Value::Float(p.z), Value::Int(i64::from(p.intensity)), Value::Int(i64::from(p.class)), Value::Int(i64::from(p.ret))]; if has_rgb { @@ -411,11 +427,23 @@ fn read_points(mut r: R, name: &str, crs: Option 0 { - report.skipped += lost; - report.messages.push(format!("{name}: {lost} points couldn't be converted to longitude/latitude")); + if not_numbers > 0 { + report.skipped += not_numbers; + let n = if not_numbers == 1 { + "one point has a coordinate that isn't a number (NaN or infinite) and was left out".to_string() + } else { + format!("{not_numbers} points have a coordinate that isn't a number (NaN or infinite) and were left out") + }; + report.messages.push(format!("{name}: {n}")); } - Ok((ds, report, total)) + if let (Some(c), Some(_)) = (crs, &transform) { + ds.crs = Some(c); + ds.held_in = c; + let kept = ds.features.len(); + let notes = crate::io::kept_unplaced_note("points", unplaced, unplaced == kept, c).into_iter(); + report.messages.extend(notes.chain(crate::io::beyond_lonlat_note("points", beyond, c)).map(|m| format!("{name}: {m}"))); + } + Ok(Cloud { ds, report, count: total, places }) } fn read_up_to(r: &mut R, buf: &mut [u8]) -> Result { @@ -586,7 +614,11 @@ mod tests { // UTM 32N metres, with a WKT record. let wkt = r#"PROJCS["WGS 84 / UTM zone 32N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",9],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1],AUTHORITY["EPSG","32632"]]"#; let (ds, _) = read_bytes(&las(2, 0, &[(500000.0, 5_000_000.0, 1.0, 1)], Some(wkt)), "t", None).unwrap(); - let Some(Geometry::Point(c)) = ds.features[0].geometry else { panic!() }; + // Kept as the file holds it, held in its system, and placed at 9°E through it. + assert_eq!(ds.held_in, Crs::Epsg(32632)); + assert_eq!(ds.crs, Some(Crs::Epsg(32632))); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(500000.0, 5_000_000.0)))); + let Geometry::Point(c) = ds.geometry_to_lonlat(ds.features[0].geometry.as_ref().unwrap()).unwrap().into_owned() else { panic!() }; assert!((c.x - 9.0).abs() < 1e-6 && (c.y - 45.1535).abs() < 0.001, "{c:?}"); // Projected coordinates with no system: kept, and said. let (ds, report) = read_bytes(&las(2, 0, &[(500000.0, 5_000_000.0, 1.0, 1)], None), "t", None).unwrap(); @@ -594,7 +626,8 @@ mod tests { assert!(report.messages.iter().any(|m| m.contains("doesn't say its coordinate system"))); let (ds, report) = read_bytes(&las(2, 0, &[(500000.0, 5_000_000.0, 1.0, 1)], None), "t", Some(Crs::Epsg(32632))).unwrap(); assert!(report.messages.is_empty()); - assert!(matches!(ds.features[0].geometry, Some(Geometry::Point(c)) if (c.x - 9.0).abs() < 1e-6)); + assert_eq!(ds.held_in, Crs::Epsg(32632)); + assert!(matches!(ds.features[0].geometry, Some(Geometry::Point(c)) if c.x == 500000.0)); } /// What reading a WKT record finds is said: UTM zone 17N on NAD 27 bound to WGS 84 by an NTv2 @@ -605,7 +638,8 @@ mod tests { let bound = crate::raster::wkt::tests::BOUND_BY_A_GRID; let (ds, report) = read_bytes(&las(2, 0, &[(500000.0, 4_800_000.0, 1.0, 1)], Some(bound)), "t", None).unwrap(); // On UTM zone 17N's central meridian, 81°W. - assert!(matches!(ds.features[0].geometry, Some(Geometry::Point(c)) if (c.x + 81.0).abs() < 1e-3), "{:?}", ds.features[0].geometry); + let lonlat = ds.geometry_to_lonlat(ds.features[0].geometry.as_ref().unwrap()).unwrap().into_owned(); + assert!(matches!(lonlat, Geometry::Point(c) if (c.x + 81.0).abs() < 1e-3), "{lonlat:?}"); let said = "t: the coordinate system: the file's NTv2 transformation to WGS 84 (conus) isn't applied, so positions may be off by as much as that shift"; assert_eq!(report.messages, [said]); let utm32 = r#"PROJCS["WGS 84 / UTM zone 32N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",9],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1],AUTHORITY["EPSG","32632"]]"#; @@ -652,9 +686,10 @@ mod tests { assert!(crate::io::read_owned("oversized.las", bytes).is_err()); } - /// Conversion losses are disclosed skips, while missing records still prevent a whole read. + /// A point with a coordinate that isn't a number is a disclosed skip, read whole or through + /// the source, while missing records still prevent a whole read. #[test] - fn source_materializes_with_counted_conversion_losses() { + fn source_materializes_with_counted_losses() { let mut bytes = las(2, 0, &[(0.0, 0.0, 3.0, 2), (1.0, 0.0, 4.0, 2)], Some("EPSG:32632")); // A finite scale overflows only the second point's X during coordinate decoding. bytes[131..139].copy_from_slice(&f64::MAX.to_le_bytes()); @@ -662,35 +697,73 @@ mod tests { assert_eq!(direct.features.len(), 1); assert!(!direct.crs_incomplete); assert_eq!(report.skipped, 1); + assert_eq!(report.messages, ["lossy: one point has a coordinate that isn't a number (NaN or infinite) and was left out"]); let src = crate::source::open_bytes("lossy.las", bytes.clone(), None).unwrap(); assert_eq!(src.info().count, Some(2)); let (ds, report) = crate::source::materialize(src.as_ref()).unwrap(); assert_eq!(ds.features, direct.features); assert!(!ds.crs_incomplete); assert_eq!(report.skipped, 1); - assert_eq!(report.messages.len(), 1); - assert!(report.messages[0].contains("1 points couldn't be converted")); + assert_eq!(report.messages.len(), 1, "{:?}", report.messages); bytes.truncate(bytes.len() - usize::from(RECORD_LEN[0])); assert!(crate::io::read_bytes("truncated.las", &bytes).is_err()); let truncated = crate::source::open_bytes("truncated.las", bytes, None).unwrap(); assert!(crate::source::materialize(truncated.as_ref()).is_err()); } - /// Projection repairs must re-read the original cloud if a transform already lost points. + /// A point with no place in longitude/latitude is kept as the file holds it and said once, + /// read whole or through the source (#2032 C2f-4b); nothing is lost, so Define Projection + /// may give the cloud another system. #[test] - fn transform_losses_block_projection_redefinition() { + fn a_point_with_no_place_is_kept_and_said() { let bytes = las(2, 0, &[(500_000.0, 5_000_000.0, 3.0, 2), (20_000_000.0, 0.0, 4.0, 2)], Some("EPSG:32632")); - let direct = crate::io::read_bytes("transform.las", &bytes).unwrap(); - let src = crate::source::open_bytes("transform.las", bytes, None).unwrap(); + let direct = crate::io::read_bytes("far.las", &bytes).unwrap(); + let src = crate::source::open_bytes("far.las", bytes, None).unwrap(); let materialized = crate::source::materialize(src.as_ref()).unwrap(); + let said = "one of the points has a place in EPSG:32632 that can't be given in longitude/latitude: it is kept as the file holds it, but doesn't draw"; for (ds, report) in [direct, materialized] { - assert_eq!(ds.features.len(), 1); - assert_eq!(report.skipped, 1); - assert!(crate::io::define_projection(&ds, Crs::LonLat).is_err()); - assert!(ds.crs_incomplete); + assert_eq!(ds.features.len(), 2); + assert_eq!(ds.held_in, Crs::Epsg(32632)); + assert_eq!(report.skipped, 0); + assert!(!ds.crs_incomplete); + assert_eq!(report.messages.iter().filter(|m| m.ends_with(said)).count(), 1, "{:?}", report.messages); + assert!(crate::io::define_projection(&ds, Crs::WebMercator).is_ok()); } } + /// The source reads a box in longitude/latitude by the points' places there, which a point + /// with none is outside of, and a box in the file's own system by the points as they are. + #[test] + fn a_point_with_no_place_is_outside_a_box_in_longitude_latitude() { + let bytes = las(2, 0, &[(500_000.0, 5_000_000.0, 3.0, 2), (20_000_000.0, 0.0, 4.0, 2)], Some("EPSG:32632")); + let src = crate::source::open_bytes("far.las", bytes, None).unwrap(); + let ids = |req: &crate::source::Request| src.read(req).unwrap().features.iter().map(|f| f.id).collect::>(); + assert_eq!(ids(&crate::source::Request::all()), [0, 1]); + let around = Extent::new(8.0, 44.0, 10.0, 46.0); + assert_eq!(ids(&crate::source::Request { extent: Some(around), limit: 10, own: None }), [0]); + let world = Extent::new(-180.0, -90.0, 180.0, 90.0); + assert_eq!(ids(&crate::source::Request { extent: Some(world), limit: 10, own: None }), [0]); + let east = Extent::new(19_000_000.0, -1.0, 21_000_000.0, 1.0); + let own = crate::source::Request { extent: Some(world), limit: 10, own: Some((Crs::Epsg(32632), east)) }; + assert_eq!(ids(&own), [1]); + // The extent is the place that has one. + let e = src.info().extent; + assert!((e.min_x - 9.0).abs() < 1e-6 && (e.max_y - 45.1535).abs() < 0.001, "{e:?}"); + } + + /// A cloud none of whose points has a place in the system it says is said so, and Define + /// Projection can give it the one they are in. + #[test] + fn a_cloud_with_no_place_can_be_given_its_system() { + let bytes = las(2, 0, &[(20_000_000.0, 0.0, 3.0, 2), (19_000_000.0, 100.0, 4.0, 2)], Some("EPSG:32632")); + let (ds, report) = crate::io::read_bytes("mercator.las", &bytes).unwrap(); + assert_eq!(ds.features.len(), 2); + assert_eq!(report.skipped, 0); + assert!(report.messages.iter().any(|m| m.contains("none of the points has a place")), "{:?}", report.messages); + let fixed = crate::io::define_projection(&ds, Crs::WebMercator).unwrap(); + assert!(matches!(fixed.features[0].geometry, Some(Geometry::Point(c)) if c == Coord::new(20_000_000.0, 0.0))); + } + #[test] fn hostile_files_never_panic() { let b = las(4, 7, &[(1.0, 2.0, 3.0, 2), (1.5, 2.5, 3.5, 5), (1.2, 2.2, 3.2, 9)], Some("GEOGCS[\"x\"]")); diff --git a/crates/data/src/source/lidar.rs b/crates/data/src/source/lidar.rs index 20a02393ee..8266499286 100644 --- a/crates/data/src/source/lidar.rs +++ b/crates/data/src/source/lidar.rs @@ -5,15 +5,21 @@ use super::{Batch, FeatureSource, Request, SourceInfo}; use crate::Result; +use crate::raster::Crs; use crate::{Dataset, Feature, Geometry}; -use rustgis_geom::Extent; +use rustgis_geom::{Coord, Extent}; use std::path::Path; pub struct LidarSource { info: SourceInfo, features: Vec, skipped: usize, - crs_incomplete: bool, + /// The system the points are held in, as the file holds them ([`FeatureSource::coord_crs`]). + crs: Crs, + /// Each point's place in longitude/latitude, in the order of `features`, for a read of a box + /// there to test (NaN for one with none, which no box holds); `None` when the points are held + /// in longitude/latitude. + places: Option>, } impl LidarSource { @@ -29,9 +35,18 @@ impl LidarSource { } /// Keeps the file count separate from its retained display sample. - fn from_read((ds, report, count): (Dataset, crate::ReadReport, u64)) -> Result { - let Dataset { name, geometry_type, fields, features, crs_incomplete, .. } = ds; - let extent = features.iter().filter_map(|f| f.geometry.as_ref()).fold(Extent::EMPTY, |e, g| e.union(&g.extent())); + fn from_read(cloud: crate::lidar::Cloud) -> Result { + let crate::lidar::Cloud { ds, report, count, places } = cloud; + let crs = ds.coord_crs(); + let Dataset { name, geometry_type, fields, features, .. } = ds; + // The extent in longitude/latitude, from the places that have one there. + let extent = match &places { + Some(places) => places.iter().filter(|c| c.is_finite()).fold(Extent::EMPTY, |mut e, c| { + e.expand(*c); + e + }), + None => features.iter().filter_map(|f| f.geometry.as_ref()).fold(Extent::EMPTY, |e, g| e.union(&g.extent())), + }; // The reader's messages start with the layer's name, which the source's notes add. let prefix = format!("{name}: "); let notes = report.messages.into_iter().map(|m| m.map_text(|t| t.strip_prefix(&prefix).map(str::to_string).unwrap_or(t))).collect(); @@ -42,12 +57,12 @@ impl LidarSource { fields, extent, count: Some(count), - crs: "EPSG:4326".into(), + crs: crs.definition_text(), indexed: false, notes, zm_dropped: false, }; - Ok(LidarSource { info, features: features.into_vec(), skipped: report.skipped, crs_incomplete }) + Ok(LidarSource { info, features: features.into_vec(), skipped: report.skipped, crs, places }) } } @@ -56,27 +71,46 @@ impl FeatureSource for LidarSource { &self.info } - /// Conversion failures were already disclosed at open, rather than omitted by sampling. + /// The file's own system, which its points are held in. + fn coord_crs(&self) -> Crs { + self.crs + } + + /// A box in the file's own system is tested against the points as they are. + fn reads_own_box(&self) -> bool { + true + } + + /// Points that couldn't be read were already disclosed at open, rather than omitted by + /// sampling. fn skipped_at_open(&self) -> usize { self.skipped } - /// A projection repair must re-read the original file after a transform discarded points. - fn lost_to_crs(&self) -> bool { - self.crs_incomplete + /// The notes at open count the points kept with no place in longitude/latitude. + fn says_unplaced_at_open(&self) -> bool { + true } - /// Answers from retained points; a sample never constitutes a complete source read. + /// Answers from retained points; a sample never constitutes a complete source read. A box in + /// the file's own system ([`Request::own`]) is tested against the points as they are, else + /// the extent against their places in longitude/latitude, which a point with none is outside + /// of. fn read(&self, req: &Request) -> Result { - let inside = |f: &&Feature| match (req.extent, &f.geometry) { + let own = req.own.filter(|(crs, _)| self.places.is_some() && *crs == self.crs).map(|(_, e)| e); + let within = |c: Coord, e: &Extent| c.x >= e.min_x && c.x <= e.max_x && c.y >= e.min_y && c.y <= e.max_y; + let inside = |(i, f): &(usize, &Feature)| match (own.as_ref().or(req.extent.as_ref()), &f.geometry) { (None, _) => true, - (Some(e), Some(Geometry::Point(c))) => c.x >= e.min_x && c.x <= e.max_x && c.y >= e.min_y && c.y <= e.max_y, - (Some(e), Some(g)) => e.intersects(&g.extent()), (Some(_), None) => false, + (Some(e), Some(g)) => match (&self.places, own.is_some(), g) { + (Some(places), false, _) => places.get(*i).is_some_and(|c| within(*c, e)), + (_, _, Geometry::Point(c)) => within(*c, e), + (_, _, g) => e.intersects(&g.extent()), + }, }; // One pass over the points (references, not copies), then every n-th match past the // limit, so the view stays covered evenly. - let hits: Vec<&Feature> = self.features.iter().filter(inside).collect(); + let hits: Vec<&Feature> = self.features.iter().enumerate().filter(inside).map(|(_, f)| f).collect(); // A window can only contain points retained in the display sample. Even when every // retained point matches, an oversized or damaged source has not been read whole. // Known conversion skips are accounted for separately in the whole read's report. diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index a28d59e468..c605656840 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -1034,23 +1034,30 @@ impl Reproject { /// A geometry as the source holds it, kept in its own coordinates ([`Reproject::crs`]), with /// its box in longitude/latitude for a request's extent to test, for a source read by its - /// rows (MySQL, SQL Server); `None` when a coordinate can't be converted to - /// longitude/latitude, as such a feature is left out there (the others keep it: - /// [`Reproject::place`]). Each coordinate is converted to be checked, - /// none is kept converted. + /// rows (MySQL, SQL Server). A geometry with a place that can't be given in + /// longitude/latitude is kept as well, with no box (#2032 C2f-4b): within a read with no + /// extent (a whole read) and outside any extent, as [`Reproject::place`] keeps it. `None` for + /// one with a coordinate that isn't a number, which the reader leaves out and counts. Each + /// coordinate is converted to be checked, none is kept converted. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read(&self, g: Geometry) -> Option { let Some(t) = &self.t else { - let lonlat = g.extent(); + let lonlat = Some(g.extent()); return Some(Placed { geometry: g, lonlat }); }; - let mut ok = true; - let mut lonlat = Extent::EMPTY; - g.for_each_coord(|c| match t.to_lonlat(c).filter(|l| l.is_finite()) { - Some(l) => lonlat.expand(l), - None => ok = false, - }); - ok.then_some(Placed { geometry: g, lonlat }) + if !g.is_finite() { + return None; + } + let lonlat = crate::io::places_lonlat_extent(&g, t); + Some(Placed { geometry: g, lonlat }) + } + + /// Whether a geometry read with its box ([`Placed::lonlat`]) is within a request's extent: a + /// read with no extent holds every one, one with no place in longitude/latitude none with an + /// extent. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn within(lonlat: Option<&Extent>, extent: Option<&Extent>) -> bool { + extent.is_none_or(|e| lonlat.is_some_and(|l| l.intersects(e))) } /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is @@ -1442,11 +1449,11 @@ pub(crate) fn in_request(g: &Geometry, req: &Request) -> bool { } /// A geometry a source read, in its own coordinates, and its box in longitude/latitude -/// ([`Reproject::read`]). +/// ([`Reproject::read`]): `None` when a place of it can't be given there. #[cfg(not(target_arch = "wasm32"))] pub(crate) struct Placed { pub(crate) geometry: Geometry, - pub(crate) lonlat: Extent, + pub(crate) lonlat: Option, } /// A geometry a source read for a request, in its own coordinates, and whether it is within the diff --git a/crates/data/src/source/mysql.rs b/crates/data/src/source/mysql.rs index b769e95ca0..42b55fde10 100644 --- a/crates/data/src/source/mysql.rs +++ b/crates/data/src/source/mysql.rs @@ -4,8 +4,9 @@ //! RustGIS talks to the server itself (the pure-Rust `mysql` client, TLS through rustls), so //! nothing else needs installing. Extent queries use the column's spatial index //! (`MBRIntersects`); geometry comes as WKB, longitude first (MySQL's geographic coordinate -//! systems are latitude first unless asked), and RustGIS converts it to longitude/latitude -//! itself, since MariaDB has no `ST_Transform`. A capped read returns an evenly spread sample, +//! systems are latitude first unless asked), kept in the table's own system; RustGIS converts it +//! to longitude/latitude itself where that is needed (a view's box), since MariaDB has no +//! `ST_Transform`. A capped read returns an evenly spread sample, //! numbered on the server (window functions: MySQL 8 or MariaDB 10.2 and later), so only the rows //! kept cross the network. The session is read only, and a server asking for a local file //! (`LOAD DATA LOCAL INFILE`) is refused. @@ -901,7 +902,8 @@ impl MysqlSource { .into_iter() .filter_map(|f| f.geometry) .filter_map(|g| self.reproject.read(g)) - .fold(Extent::EMPTY, |e, p| e.union(&p.lonlat)) + .filter_map(|p| p.lonlat) + .fold(Extent::EMPTY, |e, l| e.union(&l)) } /// The `WHERE` condition: a geometry, of the family read, and in `window` (a polygon's text @@ -935,10 +937,10 @@ impl MysqlSource { } /// A row read as a feature: the id, the geometry (as the table holds it, in its own system) - /// and the fields, in the order of the select, with the geometry's box in longitude/latitude. - /// `None` without an id or a geometry RustGIS reads and places. A value of a date field that isn't a date - /// RustGIS holds is null, counted in `unread` ([`Batch::unread_dates`]). - fn row_feature(&self, r: &mysql::Row, unread: &mut Vec) -> Option<(Feature, Extent)> { + /// and the fields, in the order of the select, with the geometry's box in longitude/latitude + /// (`None` for one with no place there, [`Reproject::read`]). `None` without an id or a + /// geometry RustGIS reads. A value of a date field that isn't a date RustGIS holds is null, counted in `unread` ([`Batch::unread_dates`]). + fn row_feature(&self, r: &mysql::Row, unread: &mut Vec) -> Option<(Feature, Option)> { let id = id_of(at(r, 0))?; let geometry = match at(r, 1) { mysql::Value::Bytes(b) => wkb::decode(b), @@ -1087,7 +1089,7 @@ impl MysqlSource { }; // The index matched the request's box in the table's coordinates, which holds more // than the request when they are projected: placed in longitude/latitude to compare. - if req.extent.is_some_and(|e| !lonlat.intersects(&e)) { + if !Reproject::within(lonlat.as_ref(), req.extent.as_ref()) { continue; } super::add_unread_dates(&mut out.unread_dates, &unread); diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs index 8c353dcc43..89aee4dd6a 100644 --- a/crates/data/src/source/own_box_tests.rs +++ b/crates/data/src/source/own_box_tests.rs @@ -170,3 +170,24 @@ fn the_whole_plane_holds_a_shape_with_no_place() { assert!(reproject.place(empty.clone(), &none).is_some_and(|f| f.inside), "no box"); assert!(reproject.place(empty, &small).is_some_and(|f| !f.inside), "a box of somewhere"); } + +/// A source read by its rows (MySQL, SQL Server) keeps a geometry with no place in +/// longitude/latitude as the table holds it (#2032 C2f-4b): within a whole read, outside any +/// extent. One with a coordinate that isn't a number is left out for the reader to count. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_row_with_no_place_in_longitude_latitude_is_kept_outside_any_extent() { + let mut notes = Vec::new(); + let r = Reproject::from_crs(utm31(), &mut notes); + let (lonlat, _) = around_paris(); + let far = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(1e9, 5_411_500.0)]]); + let kept = r.read(far.clone()).unwrap(); + assert_eq!(kept.geometry, far); + assert_eq!(kept.lonlat, None); + assert!(Reproject::within(kept.lonlat.as_ref(), None), "a whole read"); + assert!(!Reproject::within(kept.lonlat.as_ref(), Some(&lonlat)), "a read of a box"); + let paris = r.read(Geometry::Point(Coord::new(451_500.0, 5_411_500.0))).unwrap(); + assert!(Reproject::within(paris.lonlat.as_ref(), Some(&lonlat))); + assert!(r.read(Geometry::Point(Coord::new(f64::NAN, 5_411_500.0))).is_none()); + assert!(notes.is_empty(), "{notes:?}"); +} diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 63c307194e..d9e4149a6f 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -964,7 +964,8 @@ impl SqlServerSource { .into_iter() .filter_map(|f| f.geometry) .filter_map(|g| self.reproject.read(g)) - .fold(Extent::EMPTY, |e, p| e.union(&p.lonlat)) + .filter_map(|p| p.lonlat) + .fold(Extent::EMPTY, |e, l| e.union(&l)) } fn filter(&self, window: Option<&str>) -> String { @@ -986,10 +987,10 @@ impl SqlServerSource { } /// A row read as a feature: the id, the geometry (as the table holds it, in its own system) - /// and the fields, in the order of the select, with the geometry's box in longitude/latitude. - /// `None` without an id or a geometry RustGIS reads and places. A value of a date field that - /// isn't a date RustGIS holds is null, counted in `unread` ([`Batch::unread_dates`]). - fn row_feature(&self, r: &Row, unread: &mut Vec) -> Option<(Feature, Extent)> { + /// and the fields, in the order of the select, with the geometry's box in longitude/latitude + /// (`None` for one with no place there, [`Reproject::read`]). `None` without an id or a + /// geometry RustGIS reads. A value of a date field that isn't a date RustGIS holds is null, counted in `unread` ([`Batch::unread_dates`]). + fn row_feature(&self, r: &Row, unread: &mut Vec) -> Option<(Feature, Option)> { let id = id_of(at(r, 0))?; let super::Placed { geometry, lonlat } = self.reproject.read(wkb::decode(bytes_of(at(r, 1))?)?)?; let attrs = self.info.fields.iter().enumerate().map(|(k, f)| attr_of(f.ty, at(r, k + 2), unread, k)).collect(); @@ -1050,7 +1051,7 @@ impl SqlServerSource { continue; }; // Kept as the table holds it, placed in longitude/latitude to compare with the view. - if req.extent.is_none_or(|e| lonlat.intersects(&e)) { + if Reproject::within(lonlat.as_ref(), req.extent.as_ref()) { super::add_unread_dates(&mut out.unread_dates, &unread); out.features.push(f); } diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index e7dcb5e48e..d549e02bc2 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -37,7 +37,7 @@ export names its feature. | CityGML | `.gml`, or `.xml` | Add Data, drop the file, upload, or From URL… | CityGML 1.0, 2.0 and 3.0, read in 2D as CityJSON is (the same layers, fields, footprints, heights and notices). 3.0 is read by the names it keeps and by its own where they change (thematic surfaces in `boundary`, openings in `fillingSurface`, generic attributes named by `gen:name`, a group's member inside its `Role`), read only in 3.0's namespaces, so an extension of a 1.0 or 2.0 model that uses one of those names keeps its own meaning; its spaces (a `BuildingRoom`, a `Storey`) are objects like any other. The objects are the features of the model's members and those nested in them with a `gml:id` or a geometry (a `BuildingPart`, a `Room`), each with its parent's id in `parent`; thematic surfaces and their openings are their object's faces, and a `GroundSurface` its ground. A geometry's level of detail is the one its property names (`lod2Solid` is 2); one in another property (a group's) has none. Converted from the `srsName`, by its horizontal part for a compound system (the URN and URL forms of geographic systems are latitude first, CRS84 longitude first; heights are kept as they come, and a vertical part that isn't a height in metres, such as one in feet, a depth, or one RustGIS doesn't know, is said; when a vertical part is named, its unit is the heights', not the horizontal system's), or from the coordinate system given (`crs`), which takes the place of the one the file names; a file naming different systems (on its geometries or envelopes) is refused unless a system is given, which reads them all and says how many named another, and one system with its axes in different orders is refused either way. Picked by name (`layer`), a layer keeps the notices the file as a whole gives; zipped, a model keeps the system it names, and the one given applies only when it names none RustGIS knows. Generic attributes are typed by their element, `measuredHeight`, the storey counts, years and any property with a unit in metres are numbers (a measure in another unit than the metre is text with its unit), other simple properties are text (the code list a code names, `codeSpace`, a value's other attributes, such as its language, `xml:lang`, and a generic attribute set's members with no name and its own code list aren't kept, and notices say how many, generic attributes included), a property given twice is a list and a structured one its JSON. Each member of the model is parsed on its own, with the objects nested in it (each object of a `featureMembers` on its own), so no tree of the whole model is built; the file's text and the rows read stay in memory. On the desktop, Add Data reads a file added by its path in the background, with its progress counted a member at a time and Cancel (in a zip, from text, or listed, it is read as the command runs). A member nested too deep or too large to parse is left out whole, with a notice. A geometry given by a link (`xlink:href`) to one written in the file, in the same member or another, as a solid's faces are to its walls' and roof's polygons, is read where the link stands, once its object's own geometries are read, a ground surface's links first: one its object holds already at that level of detail isn't read again (a ground face stays its ground, and a face read as a wall that a ground surface links to is read as the ground too), through links each is read at most once per object and level, so links in a cycle end, and what a member's links read is bounded by the member's size, and what links copy and read from other members by four times the file's, past which the links left are said; a solid whose exterior is a link that is followed and reads something keeps its cavities; a link to a `gml:id` that several elements have reads the one in its member, else the first in the file, and a notice says how many geometries repeat one; a geometry whose coordinates can't be read is said once, whichever object or link reads it first. An implicit geometry is its prototype (`relativeGMLGeometry`, `relativeGeometry` in 3.0, written in place or given by a link, in its member or another) placed by its matrix at its reference point, in the file's axis order (latitude first where the system is), with its heights: the prototype is read once and placed for each instance, and rings its matrix flattens are left out and said for each instance; one whose prototype is in another file (`libraryObject`), can't be read or holds nothing to place, or whose matrix isn't 16 numbers ending in `0 0 0 1`, is drawn as a point at its reference point, with no height, as are those past what placing may cost (as many points, all instances together, as the file could write out), and a notice says how many. A part, a group's member or a group's parent given by a link (`consistsOfBuildingPart`, `buildingPart`, `bridgePart` and `tunnelPart` in 3.0, `groupMember`, a `CityObjectGroup`'s `parent`) makes the object it names a child of the other, as if written in it, so its heights go to it, wherever it is in the file (an object written in a group's `parent` is the group's parent too, not its child); the link stays an attribute too, a link naming no other object of the file is said, and a member's role in its group isn't kept, and is said. Not read, and said in a notice: geometries given by a link to another file, nothing or a member that can't be parsed, to what isn't a geometry, or to one where nothing is drawn (an appearance's, a terrain intersection's), a prototype's geometry linked from outside its implicit geometry, and links inside a prototype; thematic surfaces and openings given only by a link; rings given by one (a hole so given is left out, its face kept), lines and rings with a point or curve given by one, and an oriented curve whose base curve is, terrain intersection curves, appearances, addresses, and the properties of thematic surfaces and openings (a name, generic attributes: their faces are kept as their object's); arcs and splines are read as straight lines through their points (a curve given backwards, `orientation="-"`, in its direction, and one held in a ring counted like a standalone one); an arc given by its centre (`ArcByCenterPoint`, `CircleByCenterPoint`) isn't read as the curve's points, its centre is never a vertex, and an arc that is its curve's only segment leaves the geometry with nothing to read; a `gml:Point` written with more than one position keeps the first one, and is said; a solid with no exterior shell is left out, as is a solid whose exterior has nothing read (a link that isn't followed, an empty shell, or a shell whose surfaces are all links that lead nowhere), its cavities with it (read alone they would be drawn as a footprint), and one whose cavity can't be read is left out whole; a file cut short, even inside a tag, keeps completed members and completed direct children of the truncated member; a part nested inside an unfinished object is lost with that object; `TINRelief` objects aren't drawn; 3.0's relations between objects (`CityObjectRelation`) and the model's versions (`versionMember`, `versionTransitionMember`) aren't read. Added, a model comes in standing as a CityJSON one does, by the same types and by CityGML's own names for them: 2.0's `BridgeConstructionElement` and 3.0's `GenericOccupiedSpace` stand; 2.0's `Room`, `IntBuildingInstallation` and the other interior installations, and 3.0's `Storey`, `HollowSpace`, `GenericUnoccupiedSpace`, `GenericLogicalSpace` and `GenericThematicSurface` stay flat. | | AutoCAD DXF | `.dxf` (ASCII) | Add Data › DXF…, drop the file, or upload | Points, lines and polygons layers from the drawing's entities: POINT, LINE, LWPOLYLINE and POLYLINE (bulges drawn as arcs; closed ones stay lines; polyface meshes become polygons), CIRCLE, ARC, ELLIPSE, SPLINE, HELIX, LEADER, MLINE (its centre line), TEXT, MTEXT, ATTRIB and constant ATTDEF (points with their text, at the alignment point of justified text), HATCH boundaries (holes found by nesting), SOLID, TRACE and 3DFACE (polygons). Blocks (named in any case) are drawn where INSERTs place them (scaled, rotated, in arrays, nested up to 8 deep), and so are DIMENSIONs' blocks (a linear dimension without one draws its lines and measured text); `"blocks": false` leaves them out, with a notice of how many. Entities in an object's own coordinate system are turned into the drawing's. Fields: `layer`, `entity`, `color` (ACI, BYLAYER and BYBLOCK resolved), `linetype`, `text`, `height`, `rotation`, `block`, `elevation` and `paperspace`. `elevation` keeps the first placed vertex's height; varying heights are dropped with a counted notice. Unreadable POLYLINE XY vertices are left out with a counted notice. In a 3D POLYLINE, a vertex whose supplied Z cannot be read is also left out; an absent Z still means zero. Spline-path vertices without Y, short HATCH rings and coordinates beyond the per-entity limit in LWPOLYLINE/POLYLINE paths and bulged HATCH boundaries are left out with counted notices. The drawing's layouts (paper space: title blocks, viewport frames) are left out, with a notice, unless `"paperSpace": true`. A drawing never says its coordinate system: give `"crs"` (such as `EPSG:2263`) — the import dialog offers the map's — or its coordinates are kept as they are, with a notice. `"layer"` picks one of the drawing's own layers, and `info.fileLayers` lists them. Text is read as UTF-8, and otherwise in the drawing's `$DWGCODEPAGE` (GBK, Big5, Shift_JIS, Windows-1252…), so Chinese layer names and labels come through; an unknown or missing code page is read as Latin-1, with a notice. Up to 2 million features (500,000 in the web app). Not read: binary DXF, MULTILEADER, WIPEOUT, IMAGE and ACIS solids (3DSOLID, REGION), named in a notice. | | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | -| LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Converted from the file's WKT or GeoTIFF-key record; without one, coordinates are kept with a notice. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | +| LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | | GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | @@ -794,10 +794,10 @@ past where that system reaches (a UTM easting of a billion metres, say), or ever whose `.prj` or declared system doesn't fit its numbers. Shapefile, GeoJSON (with a `crs`), CSV and other delimited text, File Geodatabase, ArcGIS feature service answers, MapInfo, DXF, LandXML, CityJSON and CityGML, GML and GeoLibre projects keep such a feature as the file holds it, and one -notice counts them; so do GeoPackage, FlatGeobuf, GeoParquet, PostGIS and Shapefiles read in place, -and the files RustGIS reads through GDAL or DuckDB (a layer read a view at a time is counted by the -map, as it draws). When none of a Shapefile's, GeoJSON's, CSV's, MapInfo, DXF, LandXML or city -model's features has a place there, the notice says its system doesn't seem to fit, and Define +notice counts them; so do LiDAR point clouds, GeoPackage, FlatGeobuf, GeoParquet, PostGIS, MySQL, +SQL Server and Shapefiles read in place, and the files RustGIS reads through GDAL or DuckDB (a layer +read a view at a time is counted by the map, as it draws). When none of a Shapefile's, GeoJSON's, +CSV's, LiDAR cloud's, MapInfo, DXF, LandXML or city model's features has a place there, the notice says its system doesn't seem to fit, and Define Projection can set the one that does. Such a feature doesn't draw (the map says how many it leaves out), and each step that needs longitude/latitude (an export in WGS 84, a tool, an edit) leaves it out and says so, or refuses naming it where leaving it out would lose it (a write-back, a sync of an @@ -805,8 +805,8 @@ offline area holding it, a Field Package's list of changes) or a plugin tool tak written back in its own system, it is exact. A system that converts a place to beyond ±180.5° longitude or ±90.5° latitude (Web Mercator a billion metres east is 8983°) doesn't fit either: such a feature is kept and draws out of place. Shapefile, GeoJSON, CSV, MapInfo, DXF, LandXML, ArcGIS -feature service answers, city models and whole reads of GeoPackage, FlatGeobuf, GeoParquet and -PostGIS say so. +feature service answers, LiDAR point clouds, city models and whole reads of GeoPackage, FlatGeobuf, +GeoParquet and PostGIS say so. Coordinate systems of other bodies than the Earth (Mars, the Moon and the rest of the IAU's `IAU_2015` codes, or any datum whose ellipsoid isn't the Earth's) aren't read as such yet: every @@ -859,9 +859,9 @@ Edits already made to the layer are reinterpreted too. If the wrong CRS already clamped coordinates, import the original file again to recover them accurately. A feature whose `.prj` (or other declared system) gave it no place in longitude/latitude is kept -as the file holds it, so Define Projection places it once the right system is given. If a -reader still dropped geometry (a LiDAR file, a MySQL or SQL Server table), Define Projection -cannot restore it. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with +as the file holds it, so Define Projection places it once the right system is given. A layer +an older release read may have lost such features on import (it says so); Define Projection cannot +restore them. Choose **Import Original File…** in the dialog, or search for **Import Shapefile with Projection…**. Enter the correct CRS before choosing the file. In the browser, pick the `.shp` and `.dbf` together, with any sidecars, or choose a ZIP. The override replaces the `.prj` before any conversion and applies to every Shapefile in a ZIP; other formats keep their own CRS. From 2c91b96e8e635fd8b66654c3bea9a2b412dd9278 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Tue, 24 Nov 2026 13:08:25 +0100 Subject: [PATCH 2/2] Review: a sample counts the points it shows; places sized up front; doc and guide (#2032 C2f-4b-3) --- crates/data/src/lidar.rs | 12 +++++++++--- crates/data/src/source/mod.rs | 7 ++++--- docs/user-guide/data-formats.md | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/data/src/lidar.rs b/crates/data/src/lidar.rs index ffdf896ece..c5281101d2 100644 --- a/crates/data/src/lidar.rs +++ b/crates/data/src/lidar.rs @@ -399,7 +399,7 @@ fn read_points(mut r: R, name: &str, crs: Option(mut r: R, name: &str, crs: Option 1 { "points shown" } else { "points" }; + let notes = crate::io::kept_unplaced_note(what, unplaced, unplaced == kept, c).into_iter(); + report.messages.extend(notes.chain(crate::io::beyond_lonlat_note(what, beyond, c)).map(|m| format!("{name}: {m}"))); } Ok(Cloud { ds, report, count: total, places }) } @@ -705,6 +707,10 @@ mod tests { assert!(!ds.crs_incomplete); assert_eq!(report.skipped, 1); assert_eq!(report.messages.len(), 1, "{:?}", report.messages); + // The sample's places stay in step with its points past the one left out. + let around = Extent::new(4.0, -1.0, 5.0, 1.0); + let batch = src.read(&crate::source::Request { extent: Some(around), limit: 10, own: None }).unwrap(); + assert_eq!(batch.features.iter().map(|f| f.id).collect::>(), [0]); bytes.truncate(bytes.len() - usize::from(RECORD_LEN[0])); assert!(crate::io::read_bytes("truncated.las", &bytes).is_err()); let truncated = crate::source::open_bytes("truncated.las", bytes, None).unwrap(); diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index c605656840..787f07084e 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -1036,9 +1036,10 @@ impl Reproject { /// its box in longitude/latitude for a request's extent to test, for a source read by its /// rows (MySQL, SQL Server). A geometry with a place that can't be given in /// longitude/latitude is kept as well, with no box (#2032 C2f-4b): within a read with no - /// extent (a whole read) and outside any extent, as [`Reproject::place`] keeps it. `None` for - /// one with a coordinate that isn't a number, which the reader leaves out and counts. Each - /// coordinate is converted to be checked, none is kept converted. + /// extent (a whole read) and outside any extent, as [`Reproject::place`] keeps it. For a + /// source in another system than longitude/latitude, `None` for one with a coordinate that + /// isn't a number, which the reader leaves out and counts. Each coordinate is converted to be + /// checked, none is kept converted. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read(&self, g: Geometry) -> Option { let Some(t) = &self.t else { diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index d549e02bc2..1c0313d02e 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -37,7 +37,7 @@ export names its feature. | CityGML | `.gml`, or `.xml` | Add Data, drop the file, upload, or From URL… | CityGML 1.0, 2.0 and 3.0, read in 2D as CityJSON is (the same layers, fields, footprints, heights and notices). 3.0 is read by the names it keeps and by its own where they change (thematic surfaces in `boundary`, openings in `fillingSurface`, generic attributes named by `gen:name`, a group's member inside its `Role`), read only in 3.0's namespaces, so an extension of a 1.0 or 2.0 model that uses one of those names keeps its own meaning; its spaces (a `BuildingRoom`, a `Storey`) are objects like any other. The objects are the features of the model's members and those nested in them with a `gml:id` or a geometry (a `BuildingPart`, a `Room`), each with its parent's id in `parent`; thematic surfaces and their openings are their object's faces, and a `GroundSurface` its ground. A geometry's level of detail is the one its property names (`lod2Solid` is 2); one in another property (a group's) has none. Converted from the `srsName`, by its horizontal part for a compound system (the URN and URL forms of geographic systems are latitude first, CRS84 longitude first; heights are kept as they come, and a vertical part that isn't a height in metres, such as one in feet, a depth, or one RustGIS doesn't know, is said; when a vertical part is named, its unit is the heights', not the horizontal system's), or from the coordinate system given (`crs`), which takes the place of the one the file names; a file naming different systems (on its geometries or envelopes) is refused unless a system is given, which reads them all and says how many named another, and one system with its axes in different orders is refused either way. Picked by name (`layer`), a layer keeps the notices the file as a whole gives; zipped, a model keeps the system it names, and the one given applies only when it names none RustGIS knows. Generic attributes are typed by their element, `measuredHeight`, the storey counts, years and any property with a unit in metres are numbers (a measure in another unit than the metre is text with its unit), other simple properties are text (the code list a code names, `codeSpace`, a value's other attributes, such as its language, `xml:lang`, and a generic attribute set's members with no name and its own code list aren't kept, and notices say how many, generic attributes included), a property given twice is a list and a structured one its JSON. Each member of the model is parsed on its own, with the objects nested in it (each object of a `featureMembers` on its own), so no tree of the whole model is built; the file's text and the rows read stay in memory. On the desktop, Add Data reads a file added by its path in the background, with its progress counted a member at a time and Cancel (in a zip, from text, or listed, it is read as the command runs). A member nested too deep or too large to parse is left out whole, with a notice. A geometry given by a link (`xlink:href`) to one written in the file, in the same member or another, as a solid's faces are to its walls' and roof's polygons, is read where the link stands, once its object's own geometries are read, a ground surface's links first: one its object holds already at that level of detail isn't read again (a ground face stays its ground, and a face read as a wall that a ground surface links to is read as the ground too), through links each is read at most once per object and level, so links in a cycle end, and what a member's links read is bounded by the member's size, and what links copy and read from other members by four times the file's, past which the links left are said; a solid whose exterior is a link that is followed and reads something keeps its cavities; a link to a `gml:id` that several elements have reads the one in its member, else the first in the file, and a notice says how many geometries repeat one; a geometry whose coordinates can't be read is said once, whichever object or link reads it first. An implicit geometry is its prototype (`relativeGMLGeometry`, `relativeGeometry` in 3.0, written in place or given by a link, in its member or another) placed by its matrix at its reference point, in the file's axis order (latitude first where the system is), with its heights: the prototype is read once and placed for each instance, and rings its matrix flattens are left out and said for each instance; one whose prototype is in another file (`libraryObject`), can't be read or holds nothing to place, or whose matrix isn't 16 numbers ending in `0 0 0 1`, is drawn as a point at its reference point, with no height, as are those past what placing may cost (as many points, all instances together, as the file could write out), and a notice says how many. A part, a group's member or a group's parent given by a link (`consistsOfBuildingPart`, `buildingPart`, `bridgePart` and `tunnelPart` in 3.0, `groupMember`, a `CityObjectGroup`'s `parent`) makes the object it names a child of the other, as if written in it, so its heights go to it, wherever it is in the file (an object written in a group's `parent` is the group's parent too, not its child); the link stays an attribute too, a link naming no other object of the file is said, and a member's role in its group isn't kept, and is said. Not read, and said in a notice: geometries given by a link to another file, nothing or a member that can't be parsed, to what isn't a geometry, or to one where nothing is drawn (an appearance's, a terrain intersection's), a prototype's geometry linked from outside its implicit geometry, and links inside a prototype; thematic surfaces and openings given only by a link; rings given by one (a hole so given is left out, its face kept), lines and rings with a point or curve given by one, and an oriented curve whose base curve is, terrain intersection curves, appearances, addresses, and the properties of thematic surfaces and openings (a name, generic attributes: their faces are kept as their object's); arcs and splines are read as straight lines through their points (a curve given backwards, `orientation="-"`, in its direction, and one held in a ring counted like a standalone one); an arc given by its centre (`ArcByCenterPoint`, `CircleByCenterPoint`) isn't read as the curve's points, its centre is never a vertex, and an arc that is its curve's only segment leaves the geometry with nothing to read; a `gml:Point` written with more than one position keeps the first one, and is said; a solid with no exterior shell is left out, as is a solid whose exterior has nothing read (a link that isn't followed, an empty shell, or a shell whose surfaces are all links that lead nowhere), its cavities with it (read alone they would be drawn as a footprint), and one whose cavity can't be read is left out whole; a file cut short, even inside a tag, keeps completed members and completed direct children of the truncated member; a part nested inside an unfinished object is lost with that object; `TINRelief` objects aren't drawn; 3.0's relations between objects (`CityObjectRelation`) and the model's versions (`versionMember`, `versionTransitionMember`) aren't read. Added, a model comes in standing as a CityJSON one does, by the same types and by CityGML's own names for them: 2.0's `BridgeConstructionElement` and 3.0's `GenericOccupiedSpace` stand; 2.0's `Room`, `IntBuildingInstallation` and the other interior installations, and 3.0's `Storey`, `HollowSpace`, `GenericUnoccupiedSpace`, `GenericLogicalSpace` and `GenericThematicSurface` stay flat. | | AutoCAD DXF | `.dxf` (ASCII) | Add Data › DXF…, drop the file, or upload | Points, lines and polygons layers from the drawing's entities: POINT, LINE, LWPOLYLINE and POLYLINE (bulges drawn as arcs; closed ones stay lines; polyface meshes become polygons), CIRCLE, ARC, ELLIPSE, SPLINE, HELIX, LEADER, MLINE (its centre line), TEXT, MTEXT, ATTRIB and constant ATTDEF (points with their text, at the alignment point of justified text), HATCH boundaries (holes found by nesting), SOLID, TRACE and 3DFACE (polygons). Blocks (named in any case) are drawn where INSERTs place them (scaled, rotated, in arrays, nested up to 8 deep), and so are DIMENSIONs' blocks (a linear dimension without one draws its lines and measured text); `"blocks": false` leaves them out, with a notice of how many. Entities in an object's own coordinate system are turned into the drawing's. Fields: `layer`, `entity`, `color` (ACI, BYLAYER and BYBLOCK resolved), `linetype`, `text`, `height`, `rotation`, `block`, `elevation` and `paperspace`. `elevation` keeps the first placed vertex's height; varying heights are dropped with a counted notice. Unreadable POLYLINE XY vertices are left out with a counted notice. In a 3D POLYLINE, a vertex whose supplied Z cannot be read is also left out; an absent Z still means zero. Spline-path vertices without Y, short HATCH rings and coordinates beyond the per-entity limit in LWPOLYLINE/POLYLINE paths and bulged HATCH boundaries are left out with counted notices. The drawing's layouts (paper space: title blocks, viewport frames) are left out, with a notice, unless `"paperSpace": true`. A drawing never says its coordinate system: give `"crs"` (such as `EPSG:2263`) — the import dialog offers the map's — or its coordinates are kept as they are, with a notice. `"layer"` picks one of the drawing's own layers, and `info.fileLayers` lists them. Text is read as UTF-8, and otherwise in the drawing's `$DWGCODEPAGE` (GBK, Big5, Shift_JIS, Windows-1252…), so Chinese layer names and labels come through; an unknown or missing code page is read as Latin-1, with a notice. Up to 2 million features (500,000 in the web app). Not read: binary DXF, MULTILEADER, WIPEOUT, IMAGE and ACIS solids (3DSOLID, REGION), named in a notice. | | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | -| LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | +| LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | | GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Dates and times stored as 32- or 64-bit integers are read as those whole numbers (such as milliseconds since 1970). Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another names the date and time columns with their unit. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). |