Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 11 additions & 4 deletions apps/rustgis-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,11 @@ impl Engine {
if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{name} as GeoJSON")) {
session.notify(note, false);
}
return Ok(rustgis_engine::data::io::to_geojson(&ds).to_string());
// GeoJSON is longitude/latitude, whatever system the source holds its coordinates in.
return Ok(rustgis_engine::data::io::to_geojson(&*ds.in_lonlat()?).to_string());
}
if !selected {
let text = rustgis_engine::data::io::to_geojson(&found.dataset).to_string();
let text = rustgis_engine::data::io::to_geojson(&*found.dataset.in_lonlat()?).to_string();
let note = rustgis_engine::data::zm_export_note([&found.dataset], &format!("{} as GeoJSON", found.name));
if let Some(note) = note {
session.notify(note, false);
Expand All @@ -200,8 +201,14 @@ 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;
for f in found.selection.iter().filter_map(|r| found.dataset.features.get(*r)) {
ds.push(f.geometry.clone(), f.attrs.clone());
// Copied in longitude/latitude, the system a new dataset holds its coordinates in.
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()))?;
ds.push(g, r.values().cloned().collect());
}
let text = rustgis_engine::data::io::to_geojson(&ds).to_string();
if let Some(note) = rustgis_engine::data::zm_export_note([&ds], &format!("{} as GeoJSON", ds.name)) {
Expand Down
4 changes: 3 additions & 1 deletion crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,9 @@ fn package_gp(s: &mut Session) -> Result<Vec<u8>, String> {
k += 1;
file = format!("results/{base}_{k}.geojson");
}
entries.push((file, rustgis_data::io::to_geojson(&l.dataset).to_string().into_bytes()));
// GeoJSON is longitude/latitude, whatever system the result holds its coordinates in.
let ds = l.dataset.in_lonlat()?;
entries.push((file, rustgis_data::io::to_geojson(&ds).to_string().into_bytes()));
}
rustgis_data::zip::write(&entries)
}
Expand Down
17 changes: 16 additions & 1 deletion crates/engine/src/cmd/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,11 +587,26 @@ impl Bridge<'_> {
let target = asked_crs(self.s.map(), l, p)?;
let limit = uint(p, "limit").and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX);
let rows: Vec<usize> = if b(p, "selected") == Some(true) { l.selection.clone() } else { (0..l.dataset.features.len()).collect() };
// In longitude/latitude, which a response holds unless `crs` asks for another system,
// whatever system the layer holds its coordinates in.
let mut features = rustgis_data::Features::default();
for r in rows.iter().take(limit).filter_map(|&i| l.dataset.features.row(i)) {
let n = features.len();
features.push_row(r.to_feature());
if let Some(g) = r.geometry()
&& let std::borrow::Cow::Owned(g) =
l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, r.id()))?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (latent): Dataset::geometry_to_lonlat calls self.coord_crs().to(LonLat) on every call. For a layer in another system, that builds a Crs::transformer() per feature. ogc_warp::transformer caches the same construction for this reason. The per-feature loops here (also sharing.rs styled_features and the Python layer_geojson selection branch) would pay that cost once per feature.

Behaviour is unchanged today, since coord_crs() is always LonLat and the call returns early. Before a layer can hold another system, build the Reprojection once per layer (Dataset::lonlat_conversion() is already public) and convert each row with it, or add a helper that does so. No change is needed in this PR if the follow-up is tracked for C2.

Confidence: medium. The mechanism is clear from the code. The cost depends on how expensive Crs::transformer is for the systems in use.

{
features.set_geometry(n, Some(g));
}
}
// Its geometry is longitude/latitude (above); `crs` stays the layer's, as the system it
// was read in, which `export_error` reads.
let ds = rustgis_data::Dataset {
name: l.name.clone(),
geometry_type: l.dataset.geometry_type,
fields: l.dataset.fields.clone(),
features: rows.iter().take(limit).filter_map(|&i| l.dataset.features.get(i).cloned()).collect(),
features,
source: None,
crs: l.dataset.crs,
crs_incomplete: false,
Expand Down
22 changes: 13 additions & 9 deletions crates/engine/src/cmd/sharing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,33 +506,36 @@ fn css(c: Rgba) -> String {
format!("rgba({},{},{},{:.3})", c.r(), c.g(), c.b(), f64::from(c.a()) / 255.0)
}

/// A layer's visible features as GeoJSON, each with its drawn style.
fn styled_features(l: &Layer, budget: &mut usize) -> Vec<Value> {
/// A layer's visible features as GeoJSON, each with its drawn style: in longitude/latitude,
/// whatever system the layer holds its coordinates in; refused, naming the feature, when one of
/// its places can't be given there.
fn styled_features(l: &Layer, budget: &mut usize) -> Result<Vec<Value>, String> {
let rows = l.visible_rows();
let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0;
let mut out = Vec::new();
// Its symbol by expression (no map scale: the page zooms on its own).
let styler = l.styler(None);
for (row, ft) in l.dataset.features.iter().enumerate() {
for (row, ft) in l.dataset.features.rows().enumerate() {
if *budget == 0 {
break;
}
if rows.get(row) != Some(&true) {
continue;
}
let Some(g) = &ft.geometry else { continue };
let Some(g) = ft.geometry() else { continue };
let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?;
let sym = styler.symbol(row);
let props: serde_json::Map<String, Value> =
l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect();
out.push(json!({
"type": "Feature",
"geometry": rustgis_data::io::geometry_to_geojson(g),
"geometry": rustgis_data::io::geometry_to_geojson(&g),
"properties": props,
"style": {"fill": css(sym.fill), "stroke": css(sym.stroke), "width": sym.stroke_width, "size": sym.size, "opacity": opacity},
}));
*budget -= 1;
}
out
Ok(out)
}

/// A self-contained web map page: the map's layers (rasters as images) drawn on a canvas in Web
Expand Down Expand Up @@ -571,7 +574,7 @@ fn web_map_html(m: &Map, title: &str) -> Result<String, String> {
json!({"name": l.name, "image": base64::engine::general_purpose::STANDARD.encode(png), "bounds": [a.x, a.y, b.x, b.y]}),
);
} else {
layers.push(json!({"name": l.name, "features": styled_features(l, &mut budget)}));
layers.push(json!({"name": l.name, "features": styled_features(l, &mut budget)?}));
}
}
let c = m.center_lonlat();
Expand Down Expand Up @@ -864,7 +867,8 @@ fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec<u8>)]) -> Res
json!({"spatial": {"bbox": [[e.min_x, e.min_y, e.max_x, e.max_y]], "crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84"}});
}
entries.push((format!("collections/{id}.json"), serde_json::to_vec_pretty(&col).map_err(|e| e.to_string())?));
let mut fc = rustgis_data::io::to_geojson(ds);
// GeoJSON is longitude/latitude, whatever system the layer holds its coordinates in.
let mut fc = rustgis_data::io::to_geojson(&*ds.in_lonlat()?);
fc["numberReturned"] = json!(ds.features.len());
entries.push((format!("collections/{id}/items.json"), serde_json::to_vec(&fc).map_err(|e| e.to_string())?));
cols.push(col);
Expand All @@ -882,7 +886,7 @@ fn ogc_zip(title: &str, layers: &[&Dataset], extra: &[(String, Vec<u8>)]) -> Res
/// A web layer: the layer as an OGC API Features collection, its style, and a viewer page.
fn web_layer_zip(s: &Session, l: &Layer) -> Result<Vec<u8>, String> {
let style = serde_json::to_vec_pretty(&web_style(l)).map_err(|e| e.to_string())?;
let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&l.dataset)).map_err(|e| e.to_string())?;
let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&*l.dataset.in_lonlat()?)).map_err(|e| e.to_string())?;
let mut m = s.map().clone();
m.layers = vec![l.clone()];
let e = l.extent();
Expand Down
14 changes: 8 additions & 6 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2089,14 +2089,16 @@ fn converted(ds: &Dataset, p: &Value) -> Result<(String, Vec<String>), String> {
let name_field =
ps(p, "nameField").and_then(|n| ds.field_index(n)).or_else(|| ds.fields.iter().position(|f| f.name.eq_ignore_ascii_case("name")));
let format = conversion_format(p)?;
// Every format here is longitude/latitude, whatever system the layer holds its coordinates
// in; the notes below read the layer itself, converting as they need.
let lonlat = ds.in_lonlat()?;
let text = match format {
"geojson" => rustgis_data::io::to_geojson_text(ds).map_err(|e| e.to_string())?,
"csv" => rustgis_data::io::to_csv(ds).map_err(|e| e.to_string())?,
"kml" => rustgis_data::interop::to_kml(ds, name_field).map_err(|e| e.to_string())?,
"gpx" => rustgis_data::interop::to_gpx(ds, name_field).map_err(|e| e.to_string())?,
_ => rustgis_data::interop::to_wkt_csv(ds).map_err(|e| e.to_string())?,
"geojson" => rustgis_data::io::to_geojson_text(&lonlat).map_err(|e| e.to_string())?,
"csv" => rustgis_data::io::to_csv(&lonlat).map_err(|e| e.to_string())?,
"kml" => rustgis_data::interop::to_kml(&lonlat, name_field).map_err(|e| e.to_string())?,
"gpx" => rustgis_data::interop::to_gpx(&lonlat, name_field).map_err(|e| e.to_string())?,
_ => rustgis_data::interop::to_wkt_csv(&lonlat).map_err(|e| e.to_string())?,
};
// Every format here is longitude/latitude.
let target = ps(p, "path").unwrap_or(&ds.name);
let mut notes = rustgis_data::export_notes([(ds, ds.lonlat_extent())], target, rustgis_data::raster::Crs::LonLat);
notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target).map_err(|e| e.to_string())?);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory: the CSV branch converts the layer twice once a layer holds another system. lonlat (line 2094) lives until the function returns, and export_losses_notes calls ds.in_lonlat() again for CSV (crates/data/src/io.rs:4324), so the peak is about 2× the layer, not the "≈1×, nothing converted twice" the PR body states. Today this is the identity path, so there is no cost yet.

Passing the already-converted copy here avoids the second copy. The losses notes only read coordinates in longitude/latitude, so the notes do not change. export_notes must keep ds, since it reads ds.crs.

Suggested change
notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target).map_err(|e| e.to_string())?);
notes.extend(rustgis_data::io::export_losses_notes(&lonlat, format, name_field, target).map_err(|e| e.to_string())?);

Confidence: high on the code path, medium on how much this matters before a layer can hold another system.

Expand Down
2 changes: 1 addition & 1 deletion xtask/row-uses.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
# down: new code reads and changes rows through the accessors on `Features`
# (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and
# commit this file with it.
count = 839
count = 833
Loading