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
96 changes: 96 additions & 0 deletions crates/engine/src/cmd/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::path::PathBuf;
use serde_json::{Value, json};

use super::ps;
use crate::notice_text::NoticeText;
use crate::{CmdResult, CommandSpec as C, Project, Session, Tool};

pub fn commands() -> Vec<C> {
Expand Down Expand Up @@ -449,6 +450,101 @@ fn reset(s: &mut Session, p: Project) {
);
}
}
// The water's level field (#1915) and the block's water depth field (#2317) are numeric fields
// of the water layer, as `map.terrain` checks them: one the layer lost, or holds as text, since
// the project was saved (its data replaced outside RustGIS) is cleared and said, as
// `edit.deleteField` does. A field matching but for case is kept; a water layer that isn't
// there is left alone (the water keeps its name for a layer of that name).
let (mut levels, mut depths) = (Vec::new(), Vec::new());
for m in s.project.maps.iter_mut() {
let Some(t) = m.view.terrain.as_ref() else { continue };
let Some(w) = t.water.as_ref() else { continue };

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.

Question (low confidence, possibly intended): the block-water depth check is skipped whenever the terrain has no water (let Some(w) = t.water.as_ref() else { continue };). That includes the case where the streamed-water drop just above has cleared t.water in the same open pass. The block's water field then survives the open unchecked and unsaid. The renderer is inert without terrain water (water_runs returns early), and map.terrain re-checks the field when water is set again, so nothing visible breaks. Could you confirm that is the intent, and maybe note it in the doc comment or add a test that a stale block water field with no water is left as it is?

let Some(l) = m.layer_by_name(&w.layer) else { continue };
let numeric = |f: &str| l.dataset.field_index(f).and_then(|i| l.dataset.fields.get(i)).is_some_and(|f| f.ty.is_numeric());
let level = w.level.clone().filter(|f| !numeric(f));
let depth =
t.block.as_ref().and_then(|b| b.water.as_ref()).and_then(|bw| bw.field.clone().filter(|f| !numeric(f)).map(|f| (f, bw.depth)));
let layer = l.name.clone();
let Some(t) = m.view.terrain.as_mut() else { continue };
if let Some(field) = level {
if let Some(w) = t.water.as_mut() {
w.level = None;
}
levels.push((m.name.clone(), field, layer.clone()));
}
if let Some((field, d)) = depth {
if let Some(b) = t.block.as_mut() {
match d {
Some(_) => {
if let Some(bw) = b.water.as_mut() {
bw.field = None;
}
}
None => b.water = None,
}
}
depths.push((m.name.clone(), field, layer, d));
}
}
let lit = |s: &String| -> NoticeText { s.clone().into() };

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.

Nits, grouped for the release quality pass:

  • lit can be NoticeText::from(s.clone()), which is what the From<String> impl is for.
  • The "numeric field of the water layer" rule is now written in three places (this loop, cmd/view.rs level check and block-water check). A shared helper would stop them drifting apart.
  • The per-map lists here are unbounded. NoticeText::source_errors caps listed names at five with "N more". The streamed-water notice above is also unbounded, so this follows precedent, but a hostile project with thousands of maps gives one very long notice.

match levels.as_slice() {
[] => {}
[(map, field, layer)] => s.notify_text(
NoticeText::format(
"{map}: the terrain's water level field '{field}' isn't a numeric field of '{layer}', so its lakes lie at their shores' lowest heights",
[("map", lit(map)), ("field", lit(field)), ("layer", lit(layer))],
),
false,
),
_ => {
let maps = NoticeText::list(levels.iter().map(|(map, field, layer)| {
NoticeText::format("{map} ('{field}' of '{layer}')", [("map", lit(map)), ("field", lit(field)), ("layer", lit(layer))])
}));
s.notify_text(
NoticeText::format(
"{count} maps have a terrain water level field that isn't a numeric field of their water layer, so their lakes lie at their shores' lowest heights: {maps}",
[("count", levels.len().to_string().into()), ("maps", maps)],
),
false,
);
}
}
match depths.as_slice() {
[] => {}
[(map, field, layer, d)] => {
let (key, mut args) = match d {
Some(d) => (
"{map}: the block's water depth field '{field}' isn't a numeric field of '{layer}', so its walls show all the water {depth} m deep",
vec![("depth", d.to_string().into())],
),
None => (
"{map}: the block's water depth field '{field}' isn't a numeric field of '{layer}', so its walls show no water",
vec![],
),
};
args.extend([("map", lit(map)), ("field", lit(field)), ("layer", lit(layer))]);
s.notify_text(NoticeText::format(key, args), false);
}
_ => {
let maps = NoticeText::list(depths.iter().map(|(map, field, layer, d)| {
let args = [("map", lit(map)), ("field", lit(field)), ("layer", lit(layer))];
match d {
Some(d) => NoticeText::format(
"{map} ('{field}' of '{layer}', its walls showing all the water {depth} m deep)",
args.into_iter().chain([("depth", d.to_string().into())]),
),
None => NoticeText::format("{map} ('{field}' of '{layer}', its walls showing no water)", args),
}
}));
s.notify_text(
NoticeText::format(
"{count} maps have a block water depth field that isn't a numeric field of their water layer: {maps}",
[("count", depths.len().to_string().into()), ("maps", maps)],
),
false,
);
}
}
// A terrain saved on a DEM name two layers share draws the first of them: said, as the
// project opens (its layers keep their names).
let shared: Vec<(String, String)> = s
Expand Down
78 changes: 78 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13862,6 +13862,84 @@ fn a_projects_water_on_a_streamed_layer_is_dropped_as_it_opens() {
let _ = std::fs::remove_file(path);
}

#[test]
fn a_projects_water_fields_its_layer_lost_are_cleared_as_it_opens() {
use rustgis_data::FieldType;
use rustgis_map::view::BlockWater;
let said = |s: &Session, t: &str| s.notices.iter().filter(|n| n.text.contains(t)).count();
// The fixture: its water layer lost the level field and holds the depth field as text.
let saved = Project::from_json(include_str!("../../../schema/fixtures/terrain_water_fields_lost.rgis")).unwrap();
let mut opened = Session::new(Project::default());
crate::cmd::project::reset_to(&mut opened, saved);
let t = opened.map().view.terrain.clone().unwrap();
assert!(t.water.as_ref().is_some_and(|w| w.level.is_none()), "{t:?}");
assert_eq!(t.block.and_then(|b| b.water), Some(BlockWater { depth: Some(8.0), field: None }));
assert_eq!(said(&opened, "Map: the terrain's water level field 'nivel' isn't a numeric field of 'lagos'"), 1, "{:?}", opened.notices);
let depth = "the block's water depth field 'prof' isn't a numeric field of 'lagos', so its walls show all the water 8 m deep";
assert_eq!(said(&opened, depth), 1, "{:?}", opened.notices);
// A project whose water layer holds them.
let mut s = Session::new(Project::default());
s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap();
let dem = s.map().layers.iter().find(|l| l.is_raster()).map(|l| l.name.clone()).unwrap();
let gj = json!({"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"nome": "a", "nivel": 500.0, "prof": 5.0},
"geometry": {"type": "Polygon", "coordinates": [[[10.01, 45.01], [10.02, 45.01], [10.02, 45.02], [10.01, 45.02], [10.01, 45.01]]]}}]});
s.run("layer.addDataText", &json!({"fileName": "lagos.geojson", "text": gj.to_string()})).unwrap();
let lagos = s.map().layers.iter().find(|l| !l.is_raster()).map(|l| l.name.clone()).unwrap();
s.run("map.terrain", &json!({"layer": dem, "water": {"layer": lagos, "level": "nivel"}, "block": {"water": {"field": "prof"}}}))
.unwrap();
let open = |p: &Project| {
let mut o = Session::new(Project::default());
crate::cmd::project::reset_to(&mut o, p.clone());
o
};
let edit = |p: &mut Project, from: &str, f: &dyn Fn(&mut rustgis_data::Field)| {
let l = p.maps.first_mut().and_then(|m| m.layers.iter_mut().find(|l| l.name == lagos)).unwrap();
f(l.dataset.fields.iter_mut().find(|x| x.name == from).unwrap());
};
let clean = open(&s.project);
assert_eq!(clean.map().view.terrain, s.map().view.terrain);
assert_eq!(said(&clean, "isn't a numeric field"), 0, "{:?}", clean.notices);
// Case only.
let mut p = s.project.clone();
edit(&mut p, "nivel", &|f| f.name = "NIVEL".into());
let o = open(&p);
assert_eq!(o.map().view.terrain.as_ref().and_then(|t| t.water.as_ref()).and_then(|w| w.level.clone()), Some("nivel".into()));
assert_eq!(said(&o, "isn't a numeric field"), 0, "{:?}", o.notices);
// Text, no depth.
let mut p = s.project.clone();
edit(&mut p, "prof", &|f| f.ty = FieldType::Text);
let o = open(&p);
assert_eq!(o.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).map(|b| b.water.clone()), Some(None));
assert_eq!(said(&o, "so its walls show no water"), 1, "{:?}", o.notices);
// Several maps.
let mut p = s.project.clone();
let mut second = p.maps[0].clone();
second.name = "Map 2".into();
p.maps.push(second);
for m in p.maps.iter_mut() {
if let Some(f) = m.layers.iter_mut().find(|l| l.name == lagos).and_then(|l| l.dataset.fields.iter_mut().find(|x| x.name == "nivel"))
{
f.name = "cota".into();
}
}
for m in p.maps.iter_mut() {
if let Some(f) = m.layers.iter_mut().find(|l| l.name == lagos).and_then(|l| l.dataset.fields.iter_mut().find(|x| x.name == "prof"))
{
f.ty = FieldType::Text;
}
}
let o = open(&p);
assert_eq!(said(&o, "2 maps have a terrain water level field"), 1, "{:?}", o.notices);
let list = "2 maps have a block water depth field that isn't a numeric field of their water layer: Map ('prof' of 'lagos', its walls showing no water), Map 2 ('prof' of 'lagos', its walls showing no water)";
assert_eq!(said(&o, list), 1, "{:?}", o.notices);
// Water layer missing: left alone.
let mut p = s.project.clone();
p.maps[0].layers.retain(|l| l.name != lagos);
let o = open(&p);
assert_eq!(o.map().view.terrain.as_ref().and_then(|t| t.water.as_ref()).and_then(|w| w.level.clone()), Some("nivel".into()));
assert_eq!(said(&o, "isn't a numeric field"), 0, "{:?}", o.notices);
}

/// A 40×40 lon/lat DEM near (10°E, 45°N): a hill in the middle, with a wall to its east.
fn dem_b64() -> String {
use base64::Engine;
Expand Down
7 changes: 6 additions & 1 deletion docs/user-guide/maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,12 @@ to about 4 million heights in all (and one a ring); when the water layer's shore
longer, all of them are read at one wider step, and a notice says how
many polygons were. A layer read a view at a time (in chunks, by range) can't be the water. `{"water": false}` takes the water off;
left out (or `null`), it stays as it was. The water layer is kept by name, follows its renames, and can stay
hidden; its own symbology still draws it. Rivers stay lines. Over elevation tiles, the levels are
hidden; its own symbology still draws it. A project that opens with a water layer that no longer holds
its `"level"` field as a number (the layer's data replaced outside RustGIS, a field renamed other than
only in case, or turned to text) clears it, as deleting the field does, and says so: its lakes lie at
their shores' lowest heights.
So does the block's water `"field"`: its walls show all the water at the block water's `"depth"`, or no
water without one. Rivers stay lines. Over elevation tiles, the levels are
read again until the tiles along the shores have come. A Shaded Relief layer draws the water's
cells at their level with the even light of flat ground, flat or tilted: no hillshade, cast
shadow, sky, fill light or rock on the water, so a semi-transparent water fill over it shows one
Expand Down
1 change: 1 addition & 0 deletions schema/fixtures/terrain_water_fields_lost.rgis
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"format":2,"name":"Terrain water fields lost","maps":[{"name":"Map","layers":[{"id":1,"name":"lagos","visible":true,"dataset":{"name":"lagos","geometry_type":"Polygon","fields":[{"name":"nome","ty":"Text","alias":null},{"name":"prof","ty":"Text","alias":null}],"features":[]},"renderer":{"Single":{"fill":[224,123,57,170],"stroke":[134,74,34,255],"stroke_width":0.7,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"nome","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":{"source":{"Layer":"dem"},"exaggeration":2.0,"block":{"extent":[-500000.0,1500000.0,500000.0,2500000.0],"depth":150.0,"walls":[200,184,154,255],"water":{"depth":8.0,"field":"prof"}},"water":{"layer":"lagos","level":"nivel"}}},"animation":[],"next_layer_id":2}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["terrain-block","terrain-water","terrain-block-water"]}
Loading