Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
813a5bb
Keep layers in their own coordinate system and draw them directly (#2…
pick2510 Nov 21, 2026
26212f5
Review round 1: wasm dead code gated, GML keeps unconvertible places …
pick2510 Nov 21, 2026
f2a2698
Review: GML says places kept missing, identity test expects a zero co…
pick2510 Nov 21, 2026
e6543f7
Review round 2: per-drawing unplaced counts, GeoLibre relabel checks …
pick2510 Nov 21, 2026
de5fe63
Review round 2 follow-up: notices said when a count rises, GeoLibre k…
pick2510 Nov 21, 2026
6fd0840
Review: unplaced notice said again only for a larger count at a versi…
pick2510 Nov 21, 2026
15653f8
Review: a topology check read ahead is dropped when the datum grids c…
pick2510 Nov 21, 2026
264841a
Review round 3: export says only its own drawings' omissions, labels …
pick2510 Nov 21, 2026
159b8cd
Review: to_geojson writes coordinates as they are (callers convert he…
pick2510 Nov 21, 2026
ed699b9
Rename the drawings-made flags DrawnBy (Drawn is the map's stack entry)
pick2510 Nov 21, 2026
6de44bd
Review round 4: GeoLibre relabels only to a system that converts (els…
pick2510 Nov 21, 2026
a47a5f2
GeoLibre: the notice for a system that can't be converted gives the f…
pick2510 Nov 21, 2026
00d6204
Review round 5: a moved label's annotation lands where the label was …
pick2510 Nov 21, 2026
74b7d23
Round 5: the Source tab converts a geographic layer's box, not every …
pick2510 Nov 21, 2026
f78dc52
Round 6: a streamed layer read whole for labels.convert keeps the map…
pick2510 Nov 21, 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
22 changes: 16 additions & 6 deletions apps/rustgis-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,13 +201,23 @@ impl Engine {
}
let mut ds = rustgis_engine::data::Dataset::new(found.name.clone(), found.geometry_type(), found.dataset.fields.clone());
ds.zm_dropped = found.dataset.zm_dropped;
// Copied in longitude/latitude, the system a new dataset holds its coordinates in.
// Copied in longitude/latitude, the system a new dataset holds its coordinates in:
// exactly through WGS 84, as the whole layer's GeoJSON is, whatever map it is shown on.
// A layer whose system can't be converted fails only with a geometry to convert, as
// it did when each geometry was converted on its own.
let to = found.dataset.lonlat_conversion();
for r in found.selection.iter().filter_map(|&i| found.dataset.features.row(i)) {
let g = r
.geometry()
.map(|g| found.dataset.geometry_to_lonlat(g).map(std::borrow::Cow::into_owned))
.transpose()
.map_err(|e| format!("{}: feature {}: {e}", found.name, r.id()))?;
let g = match r.geometry() {
Some(g) => {
let to = to.as_ref().map_err(|e| format!("{}: {e}", found.name))?;
Some(
rustgis_engine::data::Dataset::geometry_to_lonlat_by(to, g)
.map_err(|e| format!("{}: feature {}: {e}", found.name, r.id()))?
.into_owned(),
)
}
None => None,
};
ds.push(g, r.values().cloned().collect());
}
let text = rustgis_engine::data::io::to_geojson(&ds).to_string();
Expand Down
58 changes: 51 additions & 7 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ const GRAPH_CACHE_BYTES: usize = 256 << 20;

struct CachedNetwork {
features: Weak<Vec<Feature>>,
/// The system the rows held their coordinates in, and the datum grids there were, when the
/// graph was built: a relabel (Define Projection keeps the rows) or a grid downloaded since
/// gives another graph from the same rows.
held: (rustgis_data::raster::Crs, u64),
rows: Vec<usize>,
cost_field: Option<usize>,
graph: Arc<Network>,
Expand All @@ -141,21 +145,37 @@ fn network_for(
ds: &Dataset,
rows: &[usize],
cost_field: Option<usize>,
) -> Result<Arc<Network>, String> {
network_keyed(cache, ds, rows, cost_field, || Network::build(ds, rows, cost_field))
}

/// [`network_for`] kept under `ds`'s rows as it holds them (its system, and the datum grids
/// there are), the rows the graph stands for, and built by `build` only when the one kept isn't
/// theirs.
fn network_keyed(
cache: &Mutex<Option<CachedNetwork>>,
ds: &Dataset,
rows: &[usize],
cost_field: Option<usize>,
build: impl FnOnce() -> Result<Network, String>,
) -> Result<Arc<Network>, String> {
crate::control::check()?;
let features = ds.features.allocation_key();
let held = (ds.coord_crs(), rustgis_data::raster::crs::grid_generation());
{
let cached = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(cached) = cached.as_ref().filter(|c| c.features.ptr_eq(&features) && c.rows == rows && c.cost_field == cost_field) {
if let Some(cached) =
cached.as_ref().filter(|c| c.features.ptr_eq(&features) && c.held == held && c.rows == rows && c.cost_field == cost_field)
{
return Ok(cached.graph.clone());
}
}
// Build outside the lock: another run can check Cancel while this one builds its graph.
let graph = Arc::new(Network::build(ds, rows, cost_field)?);
let graph = Arc::new(build()?);
let bytes = graph.bytes().saturating_add(rows.len().saturating_mul(size_of::<usize>()));
crate::control::check()?;
let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
*cached = (bytes <= GRAPH_CACHE_BYTES).then(|| CachedNetwork { features, rows: rows.to_vec(), cost_field, graph: graph.clone() });
*cached = (bytes <= GRAPH_CACHE_BYTES).then(|| CachedNetwork { features, held, rows: rows.to_vec(), cost_field, graph: graph.clone() });
Ok(graph)
}

Expand Down Expand Up @@ -185,22 +205,46 @@ pub fn shortest_route(
shortest_route_with(&NETWORK, ds, rows, from, to, cost_field, snap_m)
}

/// Keeps endpoint validation, graph reuse and search on the same path for any cache owner.
fn shortest_route_with(
cache: &Mutex<Option<CachedNetwork>>,
ds: &Dataset,
/// [`shortest_route`] over `held`, a layer held in another system than longitude/latitude: the
/// graph is built from `lonlat`, the layer in longitude/latitude, only when the one kept isn't
/// for `held`'s rows as they are, and is kept under them. Later routes over the same layer then
/// reuse it without converting the layer again; the converted copy isn't kept.
pub fn shortest_route_held<'a>(
held: &Dataset,
lonlat: impl FnOnce() -> Result<std::borrow::Cow<'a, Dataset>, String>,
rows: &[usize],
from: Coord,
to: Coord,
cost_field: Option<usize>,
snap_m: f64,
) -> Result<Route, String> {
check_route_ends(from, to, snap_m)?;
let graph = network_keyed(&NETWORK, held, rows, cost_field, || Network::build(&*lonlat()?, rows, cost_field))?;
route_on(&graph, held, from, to, snap_m)
}

/// Refuses a snap distance or route end a route can't be found from.
fn check_route_ends(from: Coord, to: Coord, snap_m: f64) -> Result<(), String> {
if !snap_m.is_finite() {
return Err("the snap distance must be finite".into());
}
if [from, to].iter().any(|c| !c.is_finite() || c.y.abs() > 90.0) {
return Err("a route end has invalid coordinates".into());
}
Ok(())
}

/// Keeps endpoint validation, graph reuse and search on the same path for any cache owner.
fn shortest_route_with(
cache: &Mutex<Option<CachedNetwork>>,
ds: &Dataset,
rows: &[usize],
from: Coord,
to: Coord,
cost_field: Option<usize>,
snap_m: f64,
) -> Result<Route, String> {
check_route_ends(from, to, snap_m)?;
let graph = network_for(cache, ds, rows, cost_field)?;
route_on(&graph, ds, from, to, snap_m)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/data/src/citygml/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ fn a_compound_system_is_read_by_its_horizontal_part() {
let out = read("model.gml", &bytes, None).unwrap();
let ds = &out[0].0;
assert_eq!(ds.crs, Some(Crs::Epsg(25832)));
let e = ds.extent();
let e = ds.lonlat_extent();
assert!((e.min_x - 9.0).abs() < 0.01 && (e.min_y - 49.6).abs() < 0.1, "{e:?}");
// One naming another system is refused.
let other = inner.replace("EPSG:25832", "EPSG:25833");
Expand Down Expand Up @@ -1055,7 +1055,7 @@ fn a_system_given_reads_the_coordinates_as_written() {
let ground = square(500_000.0, 5_500_000.0, 10.0, 0.0);
let bytes = model("urn:ogc:def:crs:EPSG::4258", &building("b1", &surface("GroundSurface", &[polygon("g", &ground)])));
let out = read("model.gml", &bytes, Some(Crs::Epsg(25832))).unwrap();
let e = out[0].0.extent();
let e = out[0].0.lonlat_extent();
assert!((e.min_x - 9.0).abs() < 0.01 && (e.min_y - 49.6).abs() < 0.1, "{e:?}");
// Latitude 10 to 12, longitude 0 to 4, given as the system the file names.
let inner = surface("GroundSurface", &[polygon("g", "10 0 0 10 4 0 12 4 0 12 0 0 10 0 0")]);
Expand Down
3 changes: 2 additions & 1 deletion crates/data/src/cityjson/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,8 @@ fn a_compound_system_is_read_by_its_horizontal_part() {
for urn in ["https://www.opengis.net/def/crs/EPSG/0/7415", "urn:ogc:def:crs:EPSG::7415"] {
v["metadata"]["referenceSystem"] = json!(urn);
let out = read("m.city.json", v.to_string().as_bytes(), None).unwrap();
let ds = &out[0].0;
// Held in its horizontal system; placed in longitude/latitude.
let ds = &out[0].0.in_lonlat().unwrap().into_owned();
let Some(Geometry::Polygon(p)) = geometry(ds, 0) else { panic!("{:?}", geometry(ds, 0)) };
let c = p[0][0][0];
assert!((c.x - 4.32).abs() < 0.05 && (c.y - 52.0).abs() < 0.05, "{urn}: {c:?}");
Expand Down
5 changes: 4 additions & 1 deletion crates/data/src/citymodel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,8 +566,10 @@ pub(crate) fn finish(
let to_lonlat = crs.transformer().map_err(|e| DataError::Format(format!("{file_name}: {e}")))?;
let mut objects = HashSet::new();
for row in &mut rows {
// Kept as the file holds it, in its system, when it has a place in longitude/latitude
// (as `geometry_to_lonlat` would give it).
if let Some(g) = row.geometry.take() {
row.geometry = crate::io::geometry_to_lonlat(&g, &to_lonlat);
row.geometry = crate::io::lonlat_box(&g, &to_lonlat).map(|_| g);
if row.geometry.is_none() {
(row.unconverted, row.draws) = (true, false);
objects.insert(row.object);
Expand Down Expand Up @@ -1060,6 +1062,7 @@ fn layers(stem: &str, rows: Vec<Row>, built: &[Built], crs: Crs, counts: &mut Co
report.extrusion = Some(crate::SuggestedExtrusion { height_field: HEIGHT.into(), base_field: BASE_HEIGHT.into() });
}
ds.crs = (crs != Crs::LonLat).then_some(crs);
ds.held_in = crs;
ds.drop_zm(&mut report, z_dropped);
out.push((ds, report));
}
Expand Down
13 changes: 7 additions & 6 deletions crates/data/src/dxf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1529,15 +1529,15 @@ pub fn read(file_name: &str, bytes: &[u8], opts: &Options) -> Result<Vec<(Datase
// What the drawing as a whole said goes with its first layer only.
let mut rep = if layers.is_empty() { report.clone() } else { ReadReport::default() };
if let Some((t, c)) = &transformer {
// Kept as the drawing holds them, in its system, where they have a place in
// longitude/latitude.
ds.held_in = *c;
let mut lost = 0usize;
for f in &mut ds.features {
crate::progress::check()?;
if let Some(g) = f.geometry.take() {
let moved = g.map_coords(&|p| t.to_lonlat(p).unwrap_or(Coord::new(f64::NAN, f64::NAN)));
let mut ok = true;
moved.for_each_coord(|p| ok &= p.is_finite());
if ok {
f.geometry = Some(moved);
if crate::io::places_in_lonlat(&g, t) {
f.geometry = Some(g);
} else {
lost += 1;
}
Expand Down Expand Up @@ -1859,7 +1859,8 @@ mod tests {
let utm = dxf(&[(0, "SECTION"), (2, "ENTITIES"), (0, "POINT"), (10, "500000"), (20, "4649776"), (0, "ENDSEC"), (0, "EOF")]);
let l = read("u.dxf", &utm, &Options { crs: Some(crs), ..Options::default() }).unwrap();
assert!(l[0].1.messages.is_empty(), "{:?}", l[0].1.messages);
if let Some(Geometry::Point(c)) = &l[0].0.features[0].geometry {
assert_eq!(l[0].0.held_in, crs, "held in the drawing's system");
if let Some(Geometry::Point(c)) = &l[0].0.in_lonlat().unwrap().features[0].geometry {
assert!((c.x - 15.0).abs() < 1e-6 && (c.y - 42.0).abs() < 0.01, "{c:?}");
}
}
Expand Down
12 changes: 9 additions & 3 deletions crates/data/src/esripbf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,11 +347,13 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
})?;
any_geometry |= geometry.is_some();
with_zm += usize::from(geometry.is_some() && (has_z || has_m));
// Kept as the answer holds it, in its own system, when it has a place in longitude/latitude
// (as `geometry_to_lonlat` would give it).
let geometry = match (geometry, &to_lonlat) {
(Some(g), Some(t)) => {
let g = crate::io::geometry_to_lonlat(&g, t);
unprojected += usize::from(g.is_none());
g
let ok = crate::io::lonlat_box(&g, t).is_some();
unprojected += usize::from(!ok);
ok.then_some(g)
}
(g, _) => g,
};
Expand All @@ -361,6 +363,10 @@ pub fn read_page_within(bytes: &[u8], name: &str, limit: usize) -> Result<Page>
ds.geometry_type = layer_type;
}
ds.crs = crs;
// Held as the answer gives its coordinates, in its own system, when RustGIS converts it.
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
ds.held_in = c;
}
// What couldn't be converted can't come back by defining the projection again.
ds.crs_incomplete = unprojected > 0;
let losses = Losses {
Expand Down
5 changes: 3 additions & 2 deletions crates/data/src/esripbf/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ fn web_mercator_answers_are_turned_to_longitude_latitude() {
feature(&[geometry(&[], &[1_113_195, 0])]),
]);
let (ds, report) = read(&bytes, "t").unwrap();
let Some(Geometry::Point(p)) = ds.features[0].geometry else { panic!("not a point") };
assert_eq!(ds.held_in, Crs::WebMercator, "held as the answer gives it");
let Some(Geometry::Point(p)) = ds.in_lonlat().unwrap().features[0].geometry else { panic!("not a point") };
assert!((p.x - 10.0).abs() < 1e-4 && p.y.abs() < 1e-9, "{p:?}");
assert_eq!(ds.crs, Some(Crs::WebMercator));
assert!(report.messages.is_empty());
Expand Down Expand Up @@ -458,7 +459,7 @@ fn a_wkts_own_shift_wins_over_its_wkid() {
|reference: Vec<u8>| answer(&[message(8, &reference), transform(false, 1.0, xy.x, xy.y), feature(&[geometry(&[], &[0, 0])])]);
let at = |bytes: &[u8]| {
let (ds, report) = read(bytes, "t").unwrap();
match &ds.features[0].geometry {
match &ds.in_lonlat().unwrap().features[0].geometry {
Some(Geometry::Point(p)) => (*p, report.messages),
g => panic!("{g:?}"),
}
Expand Down
7 changes: 6 additions & 1 deletion crates/data/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,12 @@ fn write_chunks_as(
let mut utc_dates = Vec::new();
let mut fine_dates = Vec::new();
let mut written_values = Vec::new();
let mut scratch = query.map(|expr| (expr, Cow::<Dataset>::Owned(layer.clone())));
// Measured ($area, $length) in the system the source gives its features in.
let mut scratch = query.map(|expr| {
let mut input = layer.clone();
input.held_in = held;
(expr, Cow::<Dataset>::Owned(input))
});
let mut feed = |add: &mut dyn FnMut(&[Feature]) -> Result<()>| -> Result<()> {
// A GeoPackage export that starts again feeds the features again, and counts them again.
total = 0;
Expand Down
5 changes: 3 additions & 2 deletions crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ fn a_streamed_web_mercator_export_counts_what_it_writes_at_85_degrees() {
assert_eq!(e.beyond_web_mercator, n, ".{ext} in {}", crs.label());
// As many as the file holds at 85.05°.
let mut at_edge = 0;
for g in read_back(&path).features.iter().filter_map(|f| f.geometry.as_ref()) {
let back = read_back(&path);
for g in back.in_lonlat().unwrap().features.iter().filter_map(|f| f.geometry.as_ref()) {
g.for_each_coord(|c| at_edge += usize::from((c.y.abs() - rustgis_geom::MAX_LAT).abs() < 1e-6));
}
assert_eq!(at_edge, n, ".{ext} in {}", crs.label());
Expand Down Expand Up @@ -687,7 +688,7 @@ fn a_streamed_export_is_written_from_the_system_its_source_gives() {
assert_eq!(e.written, 302, "{name}");
// Northings in the millions: only the square at 86° N is past 85.05°.
assert_eq!(e.beyond_web_mercator, beyond, "{name}");
let p = first(&read_back(&d.join(name)));
let p = first(&read_back(&d.join(name)).in_lonlat().unwrap());
assert!((p.x - want.x).abs() < 1e-7 && (p.y - want.y).abs() < 1e-7, "{name}: {p:?} {want:?}");
}
}
19 changes: 8 additions & 11 deletions crates/data/src/filegdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,10 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
// A multipatch's heights are kept as fields and noted below; its measures aren't.
let zm = table.geometry.is_some() && (table.has_m || (table.has_z && table.shape != Shape::Multipatch));
ds.crs = crs;
// Held as the file holds its coordinates, in its own system, when RustGIS converts it.
if let Some(c) = crs.filter(|_| to_lonlat.is_some()) {
ds.held_in = c;
}
let geometry_at = table.fields.iter().position(|f| f.kind == Kind::Geometry);
let (mut curves, mut wall_hulls, mut unmerged, mut unprojected) = (0usize, 0usize, 0usize, 0usize);
// Multipatches with points but no footprint: too few, all on one line, or not finite numbers.
Expand Down Expand Up @@ -406,11 +410,12 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
Err(()) => report.skipped += 1,
}
}
// Kept as the file holds it, in its own system, when it has a place in longitude/latitude.
let geometry = match (geometry, &to_lonlat) {
(Some(g), Some(t)) => {
let g = to_lonlat_geometry(g, t);
unprojected += usize::from(g.is_none());
g
let ok = crate::io::places_in_lonlat(&g, t);
unprojected += usize::from(!ok);
ok.then_some(g)
}
(g, _) => g,
};
Expand Down Expand Up @@ -458,14 +463,6 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option<u32>) -> Result<Optio
Ok(Some((ds, report)))
}

/// Projects a geometry to longitude/latitude; `None` when a point can't be.
fn to_lonlat_geometry(g: Geometry, t: &Transformer) -> Option<Geometry> {
let mut ok = true;
let out = g.map_coords(&|c| t.to_lonlat(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)));
out.for_each_coord(|c: Coord| ok &= c.is_finite());
ok.then_some(out)
}

// ---------------------------------------------------------------------------------------------
// Bytes

Expand Down
1 change: 1 addition & 0 deletions crates/data/src/filegdb/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,7 @@ fn placement_cases_are_placed() {
let layers = read_files(&files).unwrap();
let (ds, report) = &layers[0];
assert!(report.messages.is_empty(), "{what}: {:?}", report.messages);
let ds = ds.in_lonlat().unwrap().into_owned();
let Some(Geometry::Polygon(p)) = &ds.features[0].geometry else { panic!("{what}: {:?}", ds.features[0].geometry) };
// The corner at the point (stored to the millimetre) is within a centimetre of it.
let off = p[0][0].iter().map(|c| metres_apart(*c, lonlat)).fold(f64::INFINITY, f64::min);
Expand Down
Loading
Loading