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
9 changes: 7 additions & 2 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,7 @@ pub fn project(ds: &Dataset, crs: Crs) -> Result<Dataset> {
let mut out = ds.clone();
let to = from.to(crs).map_err(DataError::Format)?;
project_features(&mut out.features, &to)?;
out.held_in = crs;
Ok(out)
}

Expand Down Expand Up @@ -685,6 +686,9 @@ pub fn define_projection(ds: &Dataset, crs: Crs) -> Result<Dataset> {
f.geometry = Some(g);
}
}
// Its coordinates read in `crs` and are held in longitude/latitude, as every dataset's are
// until #2032 C2 lets a layer hold its own system (defining one then only relabels it).
out.held_in = Crs::LonLat;
out.crs = Some(crs);
Ok(out)
}
Expand Down Expand Up @@ -7894,7 +7898,7 @@ mod tests {
let at = utm.transformer().unwrap().from_lonlat(lonlat).unwrap();
let mut ds = Dataset::new("held", GeometryType::Point, vec![]);
ds.push(Some(Geometry::Point(at)), vec![]);
let _held = crate::tests::HeldIn::new(utm);
ds.held_in = utm;
assert_eq!(ds.coord_crs(), utm);
// GeoJSON: longitude/latitude.
let (bytes, _) = write_bytes_in(&ds, "geojson", Crs::LonLat).unwrap();
Expand Down Expand Up @@ -7937,14 +7941,15 @@ mod tests {
}
let want = export_losses_notes(&lonlat, "csv", None, "out.csv").unwrap();
let held = project(&lonlat, utm).unwrap();
let _held = crate::tests::HeldIn::new(utm);
assert_eq!(held.coord_crs(), utm);
assert_eq!(export_losses_notes(&held, "csv", None, "out.csv").unwrap(), want);
// A line with a missing coordinate: its vertex is left out of a Shapefile written as
// held, and noted; in any other system the export's conversion refuses the line instead
// (`project`), so there is nothing to note.
let mut line = Dataset::new("line", GeometryType::Polyline, vec![]);
let parts = vec![vec![Coord::new(500_000.0, 5_400_000.0), Coord::new(f64::NAN, 5_400_100.0), Coord::new(500_100.0, 5_400_200.0)]];
line.push(Some(Geometry::Line(parts)), vec![]);
line.held_in = utm;
let own = shapefile_geometry_notes(&line, "out.shp", utm);
assert!(own.iter().any(|n| n.contains("1 vertex with a missing or infinite coordinate")), "{own:?}");
assert!(shapefile_geometry_notes(&line, "out.shp", Crs::Epsg(25832)).is_empty());
Expand Down
236 changes: 186 additions & 50 deletions crates/data/src/lib.rs

Large diffs are not rendered by default.

30 changes: 27 additions & 3 deletions crates/data/src/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,12 +300,15 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result<Published
cpg: original.cpg.as_ref().map(|(_, b)| b.clone()),
};
let (read_back, _) = crate::io::read_shapefile_parts(back, &name, crs)?;
if let Some(why) = same_rows(ds, &read_back, if crs.is_some() { PROJECTED_TOLERANCE } else { 0.0 }) {
// Read back in longitude/latitude, so compared with the layer in it, whatever system the
// layer holds its coordinates in.
let in_lonlat = ds.in_lonlat().map_err(|e| refused(path, e))?;
if let Some(why) = same_rows(&in_lonlat, &read_back, if crs.is_some() { PROJECTED_TOLERANCE } else { 0.0 }) {
return Err(refused(path, format!("the file couldn't hold the layer as it is: {why}")));
}

if crs.is_some()
&& let Some(note) = projection_note(ds, &read_back)?
&& let Some(note) = projection_note(&in_lonlat, &read_back)?
{
notes.push(format!("{}: {note}", path.display()));
}
Expand Down Expand Up @@ -454,6 +457,7 @@ fn in_file<'a>(ds: &'a Dataset, crs: Option<Crs>, as_held: Option<(&Dataset, &Da
}
let mut out = ds.clone();
out.features = rows.into();
out.held_in = c;
Ok(std::borrow::Cow::Owned(out))
}

Expand Down Expand Up @@ -793,11 +797,12 @@ mod tests {
let at = Coord::new(500_000.0, 5_400_000.0);
let mut ds = Dataset::new("held", GeometryType::Point, vec![]);
ds.push(Some(Geometry::Point(at)), vec![]);
let _held = crate::tests::HeldIn::new(utm);
ds.held_in = utm;
let same = in_file(&ds, Some(utm), None).unwrap();
assert!(matches!(same, std::borrow::Cow::Borrowed(_)));
let other = in_file(&ds, Some(etrs), Some((&ds, &ds))).unwrap();
assert_eq!(other.features[0].geometry, Some(Geometry::Point(utm.to(etrs).unwrap().point(at).unwrap())));
assert_eq!(other.coord_crs(), etrs);
}

/// A small polygon layer of parcels with an owner, an area with decimals and a count.
Expand Down Expand Up @@ -1564,6 +1569,25 @@ mod tests {
assert_eq!(back.features.iter().next().unwrap().attrs[0], Value::Text("Smith and Jones Holdings".into()));
}

/// A layer held in the file's system (#2032 C2) is compared with what the file reads back as
/// in longitude/latitude, not its metres with degrees: an edit of its table is written.
#[test]
fn a_layer_held_in_the_files_system_publishes_an_edit() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("parcels.shp");
let crs = Crs::parse("EPSG:32616").unwrap();
crate::io::write_path_in(&parcels(), &path, crs).unwrap();
let (mut ds, sync) = read(&path);
ds.hold_in(crs).unwrap();
let mut rows: Vec<_> = ds.features.iter().cloned().collect();
rows[0].attrs[0] = Value::Text("Smyth".into());
ds.features = rows.into();
let published = shapefile(&ds, &path, &sync).unwrap();
assert!(published.notes.is_empty(), "{:?}", published.notes);
let (back, _) = crate::io::read_path(&path).unwrap();
assert_eq!(back.features.iter().next().unwrap().attrs[0], Value::Text("Smyth".into()));
}

/// A projected file's unedited shapes stay where they were, to the tolerance.
#[test]
fn a_projected_file_keeps_its_unedited_shapes() {
Expand Down
27 changes: 24 additions & 3 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,19 @@ fn report_resampled_classes(s: &mut Session, source: &Raster, out: &Raster, meth
/// The largest whole number a raster's 32-bit float pixels hold exactly.
const EXACT_WHOLE: f64 = 16_777_216.0;

/// The conversion of a layer's own coordinates to longitude/latitude, for polygons read one by
/// one ([`rasterops::transform_feature_polygons_to_lonlat`]): none while they are
/// longitude/latitude, as they are unless the layer holds another system. The same operation
/// as [`rustgis_data::Dataset::lonlat_conversion`]'s: a conversion to longitude/latitude is the
/// system's own, never a direct one between two others.
fn held_transformer(ds: &rustgis_data::Dataset) -> Result<Option<rustgis_data::raster::Transformer>, String> {
let crs = ds.coord_crs();
if crs == Crs::LonLat {
return Ok(None);
}
crs.transformer().map(Some).map_err(|e| format!("{}: {e}", ds.name))
}

/// `raster.rasterize`: a polygon layer's selected (or all) features burned onto a grid given as
/// `raster.project`'s is, each cell whose centre falls in a polygon taking its field's value, a
/// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and
Expand Down Expand Up @@ -491,10 +504,12 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult {
rows.dedup();
let (mut no_value, mut no_polygon) = (0, 0);
let mut burns: Vec<(Vec<Vec<Vec<Coord>>>, rustgis_data::Value)> = Vec::new();
// Burned from longitude/latitude, whatever system the layer holds its coordinates in.
let own = held_transformer(ds)?;
for row in rows {
let Some(feature) = ds.features.get(row) else { continue };
let parts = match &feature.geometry {
Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, None).ok(),
Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()).ok(),
_ => None,
};
let Some(parts) = parts else {
Expand Down Expand Up @@ -1035,7 +1050,11 @@ fn zone_rings(s: &Session, z: &str) -> Result<Vec<Vec<Coord>>, String> {
let l =
s.map().layer_by_name(z).filter(|l| l.geometry_type() == GeometryType::Polygon).ok_or_else(|| format!("no polygon layer '{z}'"))?;
let row = l.selection.first().copied().unwrap_or(0);
let Some(Geometry::Polygon(polys)) = l.dataset.features.get(row).and_then(|f| f.geometry.as_ref()) else {
let Some(g) = l.dataset.features.get(row).and_then(|f| f.geometry.as_ref()) else {
return Err("the zone has no polygon".into());
};
// In longitude/latitude, whatever system the layer holds its coordinates in.
let Geometry::Polygon(polys) = &*l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{z}: {e}"))? else {
return Err("the zone has no polygon".into());
};
polys.first().cloned().ok_or_else(|| "the zone has no polygon".into())
Expand Down Expand Up @@ -1230,10 +1249,12 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result<super::workflows::W
}
let mut polygons: Vec<Vec<Vec<Coord>>> = Vec::new();
let mut failed_features = Vec::new();
// In longitude/latitude, whatever system the layer holds its coordinates in.
let own = held_transformer(&l.dataset)?;
for &row in &rows {
let Some(f) = l.dataset.features.get(row) else { continue };
match &f.geometry {
Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, None) {
Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()) {
Ok(transformed) => {
polygons.extend(transformed);
}
Expand Down
22 changes: 13 additions & 9 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,11 @@ fn package_map(s: &mut Session, mobile: bool, tol: f64) -> Result<Vec<u8>, Strin
if l.is_raster() || tol <= 0.0 {
continue;
}
// Simplified in longitude/latitude, as the package saves it, whatever system the
// layer holds its coordinates in.
if let std::borrow::Cow::Owned(ds) = l.dataset.in_lonlat()? {
l.dataset = ds;
}
for f in &mut l.dataset.features {
if let Some(g) = &f.geometry {
let (simple, said) = rustgis_analysis::simplify_geometry(g, tol * 111_320.0);
Expand Down Expand Up @@ -1253,9 +1258,9 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
rustgis_data::progress::check().map_err(|e| e.to_string())?;
}
// A feature with no geometry draws nothing, so its height is neither used nor reported.
if rows.get(row) != Some(&true) || ft.geometry.is_none() {
continue;
}
let Some(g) = ft.geometry.as_ref().filter(|_| rows.get(row) == Some(&true)) else { continue };
// Placed from longitude/latitude, whatever system the layer holds its coordinates in.
let g = l.dataset.geometry_to_lonlat(g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id))?;
// A height that isn't a finite number takes the default, and is counted.
let height = match hf {
Some(fi) => match l.dataset.value(row, fi).as_f64().filter(|h| h.is_finite()) {
Expand All @@ -1273,13 +1278,13 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
let below = h < 0.0;
let orient = |o: Orient| if below { o.reversed() } else { o };
// A solid of zero height would be two coincident caps facing apart: STL leaves it out.
if !mesh.keep_lines && h == 0.0 && !matches!(ft.geometry, Some(Geometry::Line(_))) {
if !mesh.keep_lines && h == 0.0 && !matches!(&*g, Geometry::Line(_)) {
mesh.flat += 1;
continue;
}
let before = mesh.vertices;
match &ft.geometry {
Some(Geometry::Polygon(polys)) => {
match &*g {
Geometry::Polygon(polys) => {
for rings in polys {
// Each ring open (no closing vertex), outer first then holes.
let mut open: Vec<Vec<(f64, f64)>> = rings
Expand Down Expand Up @@ -1344,7 +1349,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
}
}
}
Some(Geometry::Line(parts)) => {
Geometry::Line(parts) => {
for part in parts {
let n = part.len();
if n < 2 {
Expand All @@ -1363,7 +1368,7 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
mesh.face(Item::Polyline((0..n).map(|i| v + i).collect()))?;
}
}
Some(g @ (Geometry::Point(_) | Geometry::MultiPoint(_))) => {
g @ (Geometry::Point(_) | Geometry::MultiPoint(_)) => {
let pts: Vec<rustgis_geom::Coord> = match g {
Geometry::Point(c) => vec![*c],
Geometry::MultiPoint(c) => c.clone(),
Expand All @@ -1386,7 +1391,6 @@ fn layer_mesh(s: &Session, p: &Value, keep_lines: bool) -> Result<Mesh, String>
}
}
}
None => {}
}
if mesh.vertices > before {
s.constructions.count_feature(s.map().instance_id(), l, ft, &mut mesh.constructions);
Expand Down
13 changes: 8 additions & 5 deletions crates/engine/src/cmd/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,11 +867,14 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult {
out_fields,
);
let mut moved = Vec::new();
for (row, ft) in l.dataset.features.iter().enumerate() {
for (row, ft) in l.dataset.features.rows().enumerate() {
if rows.get(row) != Some(&true) {
continue;
}
let Some(at) = ft.geometry.as_ref().and_then(Geometry::label_point) else { continue };
// In longitude/latitude, as the annotation layer holds its points and moved labels are.
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 Some(at) = g.label_point() else { continue };
for (i, class) in matcher.classes_of(&l.dataset, row).filter(|(_, c)| c.visible) {
let text = match by_text(i).and_then(|e| e.text_cut(&l.dataset, row)) {
Some(Some((t, was_cut))) => {
Expand All @@ -894,7 +897,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult {
}
// A label moved by hand becomes an annotation where it was put, and stays moved there
// (its class's offset leaves it).
let put = class.moved_to(ft.id);
let put = class.moved_to(ft.id());
let at = put.map_or(at, |[x, y]| Coord::new(x, y));
let e = exprs.get(i).and_then(Option::as_ref);
let number = |v: Option<f32>| v.map_or(Attr::Null, |v| Attr::Float(f64::from(v)));
Expand All @@ -906,11 +909,11 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult {
attrs.push(c.map_or(Attr::Null, |c| Attr::Text(format!("{},{},{},{}", c.r(), c.g(), c.b(), c.a()))));
}
if by_angle {
let turns = class.by.angle.is_some() && !along(class, ft.geometry.as_ref());
let turns = class.by.angle.is_some() && !along(class, ft.geometry());
attrs.push(number(e.filter(|_| turns).and_then(|e| e.angle(&l.dataset, row))));
}
ds.push(Some(Geometry::Point(at)), attrs);
let flat = put.is_none() && along(class, ft.geometry.as_ref());
let flat = put.is_none() && along(class, ft.geometry());
flattened += usize::from(flat);
repeated += usize::from(flat && class.repeat.is_some());
if let (Some(put), Some(new)) = (put, ds.features.last()) {
Expand Down
8 changes: 7 additions & 1 deletion crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1831,8 +1831,14 @@ pub(crate) fn add_photos_to(s: &mut Session, name: &str, zoom: Option<bool>, fee
let id = match existing {
Some(id) => {
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
// Read in longitude/latitude, held in the layer's system.
let mut photos = Vec::new();
for f in ds.features.into_iter().take(added) {
l.dataset.push(f.geometry, f.attrs);
let g = f.geometry.map(|g| l.dataset.geometry_from_lonlat(g)).transpose().map_err(|e| format!("{}: {e}", l.name))?;
photos.push((g, f.attrs));
}
for (g, attrs) in photos {
l.dataset.push(g, attrs);
}
l.touch_geometry();
s.active_layer = Some(id);
Expand Down
11 changes: 7 additions & 4 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2032,8 +2032,11 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult {
layer.gpkg = None;
layer.postgis = None;
layer.synced = None;
layer.dataset.features = l
.dataset
// Sketched in longitude/latitude, whatever system the layer holds its
// coordinates in.
let lonlat = l.dataset.in_lonlat()?;
layer.dataset.held_in = rustgis_data::raster::Crs::LonLat;
layer.dataset.features = lonlat
.features
.iter()
.map(|f| {
Expand All @@ -2045,9 +2048,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult {
layer.touch_geometry();
layer.selection.clear();
layer.labels.enabled = false;
layer
Ok(layer)
})
.collect();
.collect::<Result<_, String>>()?;
// All but reaching beyond 85.05°, which any world map does (`without_polar`).
warnings.extend(notes.get().without_polar().messages("the globe locator, simplifying its polygons"));
let name = m.name.clone();
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,7 @@ impl Bridge<'_> {
crs_incomplete: false,
zm_dropped: false,
windowed: false,
held_in: rustgis_data::raster::Crs::LonLat,
};
let mut ds = ds;
let mut member = None;
Expand Down
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ pub fn commands() -> Vec<C> {
return Err("nothing is selected in this layer".into());
}
let mut ds = rustgis_data::Dataset::new(format!("{} selection", l.name), l.geometry_type(), l.dataset.fields.clone());
// Its coordinates as they are, held in the layer's system.
ds.held_in = l.dataset.held_in;
for r in &l.selection {
if let Some(f) = l.dataset.features.get(*r) {
ds.push(f.geometry.clone(), f.attrs.clone());
Expand Down
Loading
Loading