Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
daabd91
feat(data): read CityGML 1.0 and 2.0 city models (#1536)
jgregoriorincon Nov 8, 2026
81b3e76
Merge branch 'main' into feat/1536-citygml-reader-2b
jgregoriorincon Nov 8, 2026
9dadf28
fix(data): CityGML axis order for compound CRS84 and a system given, …
jgregoriorincon Nov 8, 2026
46bdd43
fix(data): say when a CityGML file ends between objects, its city mod…
jgregoriorincon Nov 8, 2026
fa2a660
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
0a269e6
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
19d2050
fix(data): a blank CityGML unit of measure is no unit (#1536)
jgregoriorincon Nov 8, 2026
2315319
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
3df07fb
fix(data): read each object of CityGML feature members on its own, an…
jgregoriorincon Nov 8, 2026
7b969ba
fix(data): CityGML links, nested objects, heights per position and de…
jgregoriorincon Nov 8, 2026
e478e1d
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
dacae05
fix(data): CityGML links in feature members, units and codeSpace said…
jgregoriorincon Nov 8, 2026
aaa36de
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
d9d8d87
fix(data): CityGML curve orientation, gml:coord, gml:id, cut characte…
jgregoriorincon Nov 8, 2026
3991208
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 8, 2026
cf6337a
fix(data): CityGML points keep their own height, arc centres are not …
jgregoriorincon Nov 9, 2026
fa07873
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 9, 2026
0bfeaaf
fix(data): CityGML geometries left out leave no point in the file's r…
jgregoriorincon Nov 9, 2026
04b7f57
fix(data): CityGML keeps objects finished before a cut, says a linked…
jgregoriorincon Nov 9, 2026
2d6967f
Merge remote-tracking branch 'upstream/main' into feat/1536-citygml-r…
jgregoriorincon Nov 9, 2026
2b180ef
fix(data): read city models off the window, say what CityGML leaves o…
jgregoriorincon Nov 9, 2026
502d8d8
fix(data): exact GML namespaces, archive wording for mixed systems (#…
jgregoriorincon Nov 10, 2026
10a0ad8
fix(data): say CityGML value attributes and non-features left out (#1…
jgregoriorincon Nov 10, 2026
efeb3fd
fix(data): say CityGML linked rings and generic value attributes (#1536)
jgregoriorincon Nov 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ base64 = "0.23"
# Deflate for PDF image streams.
miniz_oxide = "0.9"
roxmltree = "0.21"
# CityGML: where each city object lies in a document, found without building its tree (already in
# the tree through calamine).
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
quick-xml = "0.42"
url = "2.5.8"
epaint_default_fonts = "0.37"
# Vector data providers: GeoParquet (pure Rust, so the browser reads it too), FlatGeobuf and
Expand Down
1 change: 1 addition & 0 deletions crates/data/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ proj4rs = { workspace = true }
crs-definitions = { workspace = true }
miniz_oxide = { workspace = true }
roxmltree = { workspace = true }
quick-xml = { workspace = true }
# zstd, the usual compression of GeoParquet, compiles to WebAssembly like the GeoTIFF one above.
parquet = { workspace = true, features = ["zstd"] }
url = { workspace = true }
Expand Down
1,258 changes: 1,258 additions & 0 deletions crates/data/src/citygml.rs

Large diffs are not rendered by default.

1,082 changes: 1,082 additions & 0 deletions crates/data/src/citygml/tests.rs

Large diffs are not rendered by default.

18 changes: 8 additions & 10 deletions crates/data/src/cityjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,9 @@ fn read_with(file_name: &str, bytes: &[u8], given: Option<Crs>, keep_named: bool
let mut notes = Vec::new();
let named = named_system(doc.metadata.as_ref());
let given = given.filter(|_| !keep_named || named.and_then(known_system).is_none());
let crs = coordinate_system(file_name, given, named, &vertices, &mut notes)?;
let mut reach = Reach::default();
vertices.iter().for_each(|v| reach.add(v));
let crs = coordinate_system(file_name, given, named, &reach, &mut notes)?;
notes.extend(doc.appearance.and_then(appearance_note));
let Some(objects) = doc.objects else {
return Err(DataError::Format(format!("{file_name}: no CityObjects")));
Expand All @@ -220,7 +222,11 @@ fn read_with(file_name: &str, bytes: &[u8], given: Option<Crs>, keep_named: bool
let mut budget = MAX_FILE_FACES;
let mut built: Vec<Built> = Vec::with_capacity(objects.len());
let mut rows: Vec<Row> = Vec::new();
// Counted an object at a time, and stopped between objects when its run is cancelled (in the
// desktop app's background read); parsing the document before is one step, with no check.
crate::progress::begin(objects.len());
for (id, raw) in &objects {
crate::progress::step(1)?;
let Ok(object) = serde_json::from_str::<RawObject>(raw.get()) else {
counts.skipped += 1;
continue;
Expand All @@ -244,15 +250,7 @@ fn read_with(file_name: &str, bytes: &[u8], given: Option<Crs>, keep_named: bool
if made.rows.is_empty() {
// Its attributes stay: its children, in their own rows, are where it is drawn.
counts.no_geometry += 1;
rows.push(Row {
family: Family::Polygon,
geometry: None,
object: at_row,
lod: None,
z_dropped: false,
unconverted: false,
draws: false,
});
rows.push(Row::without_geometry(at_row));
}
rows.extend(made.rows);
built.push(Built {
Expand Down
20 changes: 20 additions & 0 deletions crates/data/src/cityjson/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1357,3 +1357,23 @@ fn a_line_starting_at_nan_is_said_when_lost() {
assert_eq!(made.rows.first().and_then(|r| r.lod.as_deref()), Some("2"));
assert_eq!(counts.unusable_lost, 0);
}

/// A read counts its objects and stops between them once its run is cancelled; without a run to
/// answer to it reads them all.
#[test]
fn a_cancelled_read_stops_between_objects() {
use crate::progress::tests::Counted;
use std::sync::atomic::Ordering;
let objects: serde_json::Map<String, Json> = (0..5)
.map(|i| (format!("b{i}"), json!({"type": "Building", "geometry": [{"type": "Solid", "lod": "1", "boundaries": box_shell()}]})))
.collect();
let bytes = doc(box_vertices(), Json::Object(objects));
let probe = Counted::cancelling_after(2);
let res = {
let _g = crate::progress::install(Some(probe.clone()));
read("model.city.json", &bytes, None)
};
assert!(matches!(res, Err(DataError::Cancelled)), "{:?}", res.map(|o| o.len()));
assert_eq!(probe.total.load(Ordering::Relaxed), 5);
assert_eq!(read("model.city.json", &bytes, None).unwrap()[0].0.features.len(), 5);
}
42 changes: 35 additions & 7 deletions crates/data/src/citymodel.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! City models (the CityGML data model, whatever its encoding) read as 2D, the part each reader shares:
//! from an object's faces, lines and points to its rows, from the rows to a layer per object type
//! and geometry family, and the notices. A reader turns its own encoding into [`Faces`] and parts
//! ([`ObjectParts`]) and its objects into [`Built`]; see [`crate::cityjson`].
//! ([`ObjectParts`]) and its objects into [`Built`]; see [`crate::cityjson`] and [`crate::citygml`].
//!
//! Surfaces and solids become footprints, from the first source that gives one: LoD 0, the surfaces
//! marked `GroundSurface`, then the union of the faces of the highest LoD (see [`crate::footprint`]).
Expand Down Expand Up @@ -68,6 +68,14 @@ pub(crate) struct Row {
pub(crate) draws: bool,
}

impl Row {
/// The row of an object with no geometry of its own: its attributes stay, and its children, in
/// their own rows, are where it is drawn.
pub(crate) fn without_geometry(object: usize) -> Row {
Row { family: Family::Polygon, geometry: None, object, lod: None, z_dropped: false, unconverted: false, draws: false }
}
}

/// An object's values, one per object whatever rows it makes.
pub(crate) struct Built {
pub(crate) id: String,
Expand Down Expand Up @@ -324,17 +332,37 @@ pub(crate) fn known_system(system: &str) -> Option<Crs> {
crate::ogc::warp::epsg_of(system).and_then(|c| Crs::from_epsg(horizontal_epsg(c)))
}

/// How far a file's X and Y go from 0, taken in as its points are read, so a reader that streams its
/// objects needs no list of every vertex. A coordinate that isn't a number goes past every bound.
#[derive(Clone, Copy, Default)]
pub(crate) struct Reach {
x: f64,
y: f64,
}

impl Reach {
/// Takes in a point's X and Y.
pub(crate) fn add(&mut self, p: &P3) {
let far = |reach: f64, v: f64| if v.is_nan() { f64::INFINITY } else { reach.max(v.abs()) };
(self.x, self.y) = (far(self.x, p[0]), far(self.y, p[1]));
}

/// Whether every X is within `x` of 0 and every Y within `y`.
fn within(&self, x: f64, y: f64) -> bool {
self.x <= x && self.y <= y
}
}

/// The coordinate system: the one given, the one the file names (`named`), or longitude/latitude
/// when it names none and every vertex can be one. Anything else is an error, not a guess. A file
/// only names EPSG codes: what it says is never registered as a new definition.
/// when it names none and every point (`reach`) can be one. Anything else is an error, not a guess.
/// A file only names EPSG codes: what it says is never registered as a new definition.
pub(crate) fn coordinate_system(
file_name: &str,
given: Option<Crs>,
named: Option<&str>,
vertices: &[P3],
reach: &Reach,
notes: &mut Vec<String>,
) -> Result<Crs> {
let within = |x: f64, y: f64| vertices.iter().all(|p| p[0].abs() <= x && p[1].abs() <= y);
let crs = match (given, named) {
(Some(crs), named) => {
// What the file names is said whenever the system given takes its place, known or not.
Expand All @@ -357,7 +385,7 @@ pub(crate) fn coordinate_system(
let system: String = system.chars().take(80).collect();
DataError::Format(format!("{file_name}: it names a coordinate system RustGIS doesn't know ({system}); give one with the crs parameter of layer.addData (from the command line, Python or the AI Assistant)"))
})?,
(None, None) if within(180.0, 90.0) => {
(None, None) if reach.within(180.0, 90.0) => {
notes.push("the file names no coordinate system: its coordinates are read as longitude/latitude".into());
return Ok(Crs::LonLat);
}
Expand All @@ -370,7 +398,7 @@ pub(crate) fn coordinate_system(
if crs.is_geocentric() {
return Err(DataError::Format(format!("{file_name}: {} is a geocentric coordinate system, which isn't a map's", crs.label())));
}
if crs == Crs::LonLat && !within(180.5, 90.5) {
if crs == Crs::LonLat && !reach.within(180.5, 90.5) {
notes.push("coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place".into());
}
if let Some(unit) = crs.height_unit_not_metre() {
Expand Down
28 changes: 23 additions & 5 deletions crates/data/src/gml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub fn is_gml_name(name: &str) -> bool {
EXTENSIONS.contains(&ext.as_str())
}

fn local<'a>(n: &Node<'a, '_>) -> &'a str {
pub(crate) fn local<'a>(n: &Node<'a, '_>) -> &'a str {
n.tag_name().name()
}

Expand All @@ -51,10 +51,28 @@ fn srs(name: &str) -> Option<(Crs, bool)> {
}
let code: u32 = n.rsplit([':', '/', '#']).next()?.trim().parse().ok()?;
let crs = Crs::from_epsg(code)?;
// `EPSG:4326` and the old `…epsg.xml#4326` are longitude first; URNs and the
// opengis.net/def URLs follow the EPSG axis order, latitude first for geographic systems.
let official = up.starts_with("URN:") || up.contains("OPENGIS.NET/DEF/CRS");
Some((crs, official && crs.is_geographic()))
Some((crs, lat_first(n, crs)))
}

/// Whether coordinates named by `name`, a name of `crs`, are latitude first. `EPSG:4326` and the
/// old `…epsg.xml#4326` are longitude first; URNs and the opengis.net/def URLs follow the EPSG axis
/// order, latitude first for geographic systems, but for OGC's CRS84, longitude first by definition.
/// A compound system's order is its horizontal part's.
pub(crate) fn lat_first(name: &str, crs: Crs) -> bool {
let up = name.trim().to_ascii_uppercase();
(up.starts_with("URN:") || up.contains("OPENGIS.NET/DEF/CRS")) && crs.is_geographic() && !crate::ogc::warp::is_crs84(horizontal(name))
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}

/// The horizontal system of a compound URN (`urn:ogc:def:crs,crs:EPSG::25832,crs:EPSG::5783`, its
/// first part), or the name as it is.
pub(crate) fn horizontal(name: &str) -> &str {
let name = name.trim();
match name.get(..16) {
Some(head) if head.eq_ignore_ascii_case("urn:ogc:def:crs,") => {
name.get(16..).and_then(|rest| rest.split(',').next()).unwrap_or(name)
}
_ => name,
}
}

/// GML geometry elements read.
Expand Down
51 changes: 48 additions & 3 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,34 @@ pub fn is_cityjson(file_name: &str, bytes: &[u8]) -> bool {
&& (crate::cityjson::is_cityjson_name(file_name) || std::str::from_utf8(bytes).is_ok_and(crate::cityjson::looks_like_cityjson))
}

/// Whether a `.gml` or `.xml` file is a CityGML city model, by its root.
pub fn is_citygml(file_name: &str, bytes: &[u8]) -> bool {
let ext = Path::new(file_name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
matches!(ext.as_str(), "gml" | "xml") && crate::citygml::looks_like_citygml(bytes)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Whether a file is a city model, CityJSON or CityGML: its layers all come from one reading, which
/// takes the coordinate system a caller gives ([`read_city_model`]).
pub fn is_city_model(file_name: &str, bytes: &[u8]) -> bool {
is_cityjson(file_name, bytes) || is_citygml(file_name, bytes)
}

/// Reads a city model's layers (see [`is_city_model`]); `crs`, when given, goes over the system it
/// names.
pub fn read_city_model(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Vec<(Dataset, ReadReport)>> {
if is_citygml(file_name, bytes) { crate::citygml::read(file_name, bytes, crs) } else { crate::cityjson::read(file_name, bytes, crs) }
}

/// As [`read_city_model`], for a member of an archive: a model that names a system RustGIS knows
/// keeps it over `crs`.
fn read_city_member(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Vec<(Dataset, ReadReport)>> {
if is_citygml(file_name, bytes) {
crate::citygml::read_member(file_name, bytes, crs)
} else {
crate::cityjson::read_member(file_name, bytes, crs)
}
}

/// Reads every layer of a file held in memory: the Shapefiles and other files of a zip, a KML or
/// KMZ's points, lines and polygons (with their styles), or a GPX's waypoints, routes, tracks and
/// track points. Other files give their one layer.
Expand All @@ -96,7 +124,9 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result<Vec<LayerRead>> {
// Plain XML: whichever of the XML formats its contents say.
"xml" => {
let text = String::from_utf8_lossy(bytes.get(..bytes.len().min(8192)).unwrap_or(bytes));
if crate::landxml::looks_like_landxml(&text) {
if crate::citygml::looks_like_citygml(bytes) {
plain(crate::citygml::read(file_name, bytes, None)?)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else if crate::landxml::looks_like_landxml(&text) {
plain(crate::landxml::read(file_name, bytes, None)?)
} else if crate::georss::looks_like_georss(&text) {
plain(crate::georss::read(file_name, bytes)?)
Expand All @@ -109,10 +139,12 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result<Vec<LayerRead>> {
.collect()
} else {
return Err(DataError::Format(format!(
"{file_name}: an XML file RustGIS doesn't read (it reads GeoRSS, LandXML, KML and GPX)"
"{file_name}: an XML file RustGIS doesn't read (it reads GeoRSS, LandXML, CityGML, KML and GPX)"
)));
}
}
// A CityGML city model, or the features of a collection.
"gml" if crate::citygml::looks_like_citygml(bytes) => plain(crate::citygml::read(file_name, bytes, None)?),
"gml" => plain(crate::gml::read(file_name, bytes)?),
"dxf" => plain(crate::dxf::read(file_name, bytes, &crate::dxf::Options::default())?),
// OpenStreetMap PBF, not a vector tile (`.pbf` too).
Expand Down Expand Up @@ -185,6 +217,8 @@ pub fn sniff_extension(bytes: &[u8]) -> Option<&'static str> {
// extension), read by content under `.pbf`.
_ if crate::esripbf::is_esripbf(bytes) => "pbf",
_ if start.starts_with('{') || start.starts_with('[') => "geojson",
// A CityGML city model, by its root.
_ if start.starts_with('<') && crate::citygml::looks_like_citygml(bytes) => "gml",
_ if start.starts_with('<') && text.contains("<kml") => "kml",
_ if start.starts_with('<') && text.contains("<gpx") => "gpx",
// Text whose first two lines a separator splits alike, and no control characters.
Expand Down Expand Up @@ -236,6 +270,7 @@ pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport)
return Err(DataError::Unsupported(format!("{ext} on its own: it is part of a Shapefile; add it together with its .shp")));
}
// The first layer (`read_layers` reads them all), saying what else the file holds.
"xml" if is_citygml(file_name, bytes) => return first_layer(file_name, bytes),
"zip" | "kml" | "kmz" | "gpx" | "gml" | "dxf" | "pbf" | "topojson" => return first_layer(file_name, bytes),
"las" | "laz" => crate::lidar::read_bytes(bytes, &name, None)?,
// A copy, since only borrowed bytes are given; `read_owned` takes them without one.
Expand Down Expand Up @@ -298,6 +333,14 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> {
check_size(path)?;
read_bytes(&path.display().to_string(), &std::fs::read(path)?)?
}
"xml" => {
check_size(path)?;
let bytes = std::fs::read(path)?;
if !is_citygml(&path.display().to_string(), &bytes) {
return Err(DataError::Unsupported("xml".into()));
}
read_bytes(&path.display().to_string(), &bytes)?
}
// With its .mid beside it (spelt mid, MID or Mid).
"mif" => {
check_size(path)?;
Expand Down Expand Up @@ -2076,7 +2119,7 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Ve
}
let leaf = n.rsplit('/').next().unwrap_or(&n);
// A city model has many layers.
let read = if is_cityjson(leaf, &b) { crate::cityjson::read_member(leaf, &b, crs) } else { read_bytes(leaf, &b).map(|r| vec![r]) };
let read = if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs) } else { read_bytes(leaf, &b).map(|r| vec![r]) };
match read {
Ok(layers) => {
for (mut ds, report) in layers {
Expand All @@ -2088,6 +2131,8 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<Ve
out.push((ds, report));
}
}
// A run cancelled while a member was read stops the archive, not just that member.
Err(DataError::Cancelled) => return Err(DataError::Cancelled),
Err(e) => skipped.push(format!("{n} ({e})")),
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]

pub mod address;
pub mod citygml;
pub mod cityjson;
mod citymodel;
pub mod color;
Expand Down
Loading
Loading