Skip to content
Draft
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
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/terrain_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ mod tests {
s.map_mut().view.terrain = Some(Terrain {
source: TerrainSource::Layer("DEM".into()),
exaggeration: 1.0,
block: Some(TerrainBlock { extent: Some(extent), depth: None, walls: BLOCK_WALLS, walls_layer: None }),
block: Some(TerrainBlock { extent: Some(extent), depth: None, walls: BLOCK_WALLS, walls_layer: None, water: None }),
water: None,
});
s.notices.clear();
Expand Down
72 changes: 66 additions & 6 deletions crates/engine/src/cmd/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn commands() -> Vec<C> {
}).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"mode": "none"|"distance", "distance"?: metres from the view's centre}"#),
C::new("map.terrain", "Terrain", "View › Scene", terrain).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params(
r##"{"layer"?: a DEM raster layer (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A)}, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##,
r##"{"layer"?: a DEM raster layer (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A), "water"?: the terrain's water shown in the walls' section {"depth"?: metres from the level to the floor, "field"?: a numeric field of the water layer holding each one's depth} (one of them needed), or false}, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##,
),
C::new("map.exportOrbit", "Export Orbit", "View › Scene", |s, p| super::exports::write_here(s, p, "map.exportOrbit")).inputs(orbit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
Expand Down Expand Up @@ -307,8 +307,8 @@ fn walk(s: &mut Session, p: &Value) -> CmdResult {
/// the values checked by [`rustgis_map::view::TerrainBlock::check`] (as a saved project's are),
/// and the walls' layer as the water's is ([`polygon_layer`]).
fn terrain_block(s: &Session, b: &serde_json::Map<String, Value>) -> Result<rustgis_map::view::TerrainBlock, String> {
if let Some(k) = b.keys().find(|k| !matches!(k.as_str(), "extent" | "depth" | "walls")) {
return Err(format!("block has no '{k}' (extent, depth, walls)"));
if let Some(k) = b.keys().find(|k| !matches!(k.as_str(), "extent" | "depth" | "walls" | "water")) {
return Err(format!("block has no '{k}' (extent, depth, walls, water)"));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
let extent = match b.get("extent") {
None | Some(Value::Null) => None,
Expand Down Expand Up @@ -346,7 +346,28 @@ fn terrain_block(s: &Session, b: &serde_json::Map<String, Value>) -> Result<rust
}
other => (color(other)?, None),
};
let block = rustgis_map::view::TerrainBlock { extent, depth, walls, walls_layer };
// The water in the walls' section (#2317): its depth, or the water layer's field holding it
// (checked against the terrain's water once that is known, in `terrain`).
let water = match b.get("water") {
None | Some(Value::Null | Value::Bool(false)) => None,
Some(Value::Object(w)) => {
if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "depth" | "field")) {
return Err(format!("block's water has no '{k}' (depth, field)"));
}
let depth = match w.get("depth") {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_f64().ok_or("block's water depth is metres, 0 to 20000")?),
};
let field = match w.get("field") {
None | Some(Value::Null) => None,
Some(Value::String(f)) if !f.trim().is_empty() => Some(f.trim().to_string()),
Some(_) => return Err("block's water field is a numeric field of the water layer".into()),
};
Some(rustgis_map::view::BlockWater { depth, field })
}
Some(_) => return Err("block's water is {\"depth\"?, \"field\"?}, or false".into()),
};
let block = rustgis_map::view::TerrainBlock { extent, depth, walls, walls_layer, water };
block.check()?;
Ok(block)
}
Expand Down Expand Up @@ -424,7 +445,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult {
Some(Value::Null | Value::Bool(false)) => Some(None),
Some(Value::Bool(true)) => Some(Some(terrain_block(s, &serde_json::Map::new())?)),
Some(Value::Object(b)) => Some(Some(terrain_block(s, b)?)),
Some(_) => return Err("block is an object {\"extent\"?, \"depth\"?, \"walls\"?}, or false to take it off".into()),
Some(_) => return Err("block is an object {\"extent\"?, \"depth\"?, \"walls\"?, \"water\"?}, or false to take it off".into()),
};
// Left out (or null, as for the exaggeration), the water stays as it was; false takes it off
// (#1915).
Expand Down Expand Up @@ -581,7 +602,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult {
Some(l) => json!({"color": b.walls.hex(), "layer": l}),
None => json!(b.walls.hex()),
};
json!({"extent": extent, "extent_from": from, "depth": b.depth, "walls": walls})
json!({"extent": extent, "extent_from": from, "depth": b.depth, "walls": walls, "water": b.water})
});
if matches!(t.source, TerrainSource::Layer(_)) && t.block.is_some() && dem_box.is_none() {
out["block"]["pendingDem"] = json!(true);
Expand Down Expand Up @@ -625,6 +646,41 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult {
}
return Err(e);
}
// The water a block's walls cut (#2317), when this call sets the block or the terrain's water
// (a block kept from before is checked against new water too): the terrain's water, and the
// depth field a numeric field of its layer. How many of the polygons its definition query
// keeps have no depth is said.
let mut no_depth = None;
let block_water = t.block.as_ref().and_then(|b| b.water.as_ref()).filter(|_| block.is_some() || water.is_some());
if let Some(bw) = block_water {
let checked = (|| {
let w = t.water.as_ref().ok_or(
"block's water shows the terrain's water in the walls: give the terrain a water layer, or take the block's water off (\"block\": {\"water\": false})",
)?;
let l = m.layer_by_name(&w.layer).ok_or_else(|| format!("no layer '{}'", w.layer))?;
let Some(f) = &bw.field else { return Ok(None) };
let i = l.dataset.field_index(f).ok_or_else(|| format!("'{}' has no field '{f}' (the block's water depths)", l.name))?;
if !l.dataset.fields.get(i).is_some_and(|field| field.ty.is_numeric()) {
return Err(format!("block's water field '{f}' isn't numeric (depths in metres)"));
}
let keep = l.query_rows(&l.dataset);
let missing = |(row, ft): &(usize, &rustgis_data::Feature)| {
keep.as_ref().is_none_or(|k| k.get(*row).copied().unwrap_or(false))
&& ft.attrs.get(i).and_then(rustgis_data::Value::as_f64).is_none_or(|d| !d.is_finite() || d <= 0.0)
};
let n = if bw.depth.is_some() { 0 } else { l.dataset.features.iter().enumerate().filter(missing).count() };
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
Ok((n > 0).then(|| (n, l.name.clone(), f.clone())))
})();
match checked {
Ok(n) => no_depth = n,
Err(e) => {
if let Some(old) = old_terrain {
m.view.terrain = Some(old);
}
return Err(format!("{e} (Terrain stays as it was)"));
}
}
}
let heights_from = match &t.source {
TerrainSource::Layer(n) => Some(n.clone()),
TerrainSource::Tiles { .. } => None,
Expand All @@ -638,6 +694,10 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult {
false,
);
}
if let Some((n, layer, field)) = no_depth {
let (polygons, have) = if n == 1 { ("1 polygon".to_string(), "has") } else { (format!("{n} polygons"), "have") };
s.notify(format!("Block: {polygons} of '{layer}' {have} no depth in '{field}', so a wall crossing them shows no water"), false);
}
// When the water is set, what its levels left out is said, with how many.
if let Some(name) = water_layer {
use rustgis_render::terrain::Ground;
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ pub const CAPABILITIES: &[&str] = &[
"terrain-block",
"terrain-water",
"terrain-water-shore",
"terrain-block-water",
"shaded-relief-effects",
"normalized-legend-urls",
"field-origin",
Expand Down
7 changes: 5 additions & 2 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,16 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
}

fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static str> {
let (mut block, mut water, mut shore, mut relief, mut light, mut legends, mut sized, mut pictures) =
(false, false, false, false, false, false, false, false);
let (mut block, mut water, mut shore, mut block_water, mut relief, mut light, mut legends, mut sized, mut pictures) =
(false, false, false, false, false, false, false, false, false);
for map in maps {
if let Some(t) = &map.view.terrain {
block |= t.block.is_some();
water |= t.water.is_some();
// A shore band other than the default, which an older reader would save away.
shore |= t.water.as_ref().is_some_and(|w| w.shore != rustgis_map::view::WATER_SHORE);
// The water in a block's walls (#2317), which an older reader would save away.
block_water |= t.block.as_ref().is_some_and(|b| b.water.is_some());
}
relief |= map.layers.iter().any(relief_effects);
light |= map.layers.iter().any(relief_light);
Expand All @@ -281,6 +283,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(block, "terrain-block"),
(water, "terrain-water"),
(shore, "terrain-water-shore"),
(block_water, "terrain-block-water"),
(relief, "shaded-relief-effects"),
(light, "shaded-relief-light"),
(legends, "normalized-legend-urls"),
Expand Down
77 changes: 77 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8846,6 +8846,7 @@ fn terrain_block_is_checked_kept_and_taken_off() {
depth: None,
walls: rustgis_map::view::BLOCK_WALLS,
walls_layer: None,
water: None,
}),
water: None,
});
Expand Down Expand Up @@ -8956,6 +8957,7 @@ fn terrain_is_set_from_a_dem_or_tiles() {
depth: None,
walls: rustgis_map::view::BLOCK_WALLS,
walls_layer: None,
water: None,
}),
water: None,
});
Expand All @@ -8976,6 +8978,7 @@ fn terrain_is_set_from_a_dem_or_tiles() {
depth: None,
walls: rustgis_map::view::BLOCK_WALLS,
walls_layer: None,
water: None,
}),
water: None,
});
Expand All @@ -9000,6 +9003,7 @@ fn terrain_is_set_from_a_dem_or_tiles() {
depth: None,
walls: rustgis_map::view::BLOCK_WALLS,
walls_layer: None,
water: None,
}),
water: None,
});
Expand Down Expand Up @@ -13182,12 +13186,19 @@ fn terrain_block_is_read_back_from_a_saved_project() {
depth: Some(150.0),
walls: rustgis_map::view::BLOCK_WALLS,
walls_layer: None,
water: None,
})
);
// Its walls coloured by a polygon layer (`terrain_block_walls.rgis`), the layer kept by name.
let saved = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_walls.rgis")).unwrap();
let block = saved.maps[0].view.terrain.as_ref().and_then(|t| t.block.clone()).unwrap();
assert_eq!((block.walls, block.walls_layer.as_deref()), (rustgis_map::Rgba::rgb(128, 96, 64), Some("geologia")));
// With the water in its walls (#2317, `terrain_block_water_v2.rgis`), which it requires.
let saved = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_water_v2.rgis")).unwrap();
let block = saved.maps[0].view.terrain.as_ref().and_then(|t| t.block.clone()).unwrap();
assert_eq!(block.water, Some(rustgis_map::view::BlockWater { depth: Some(8.0), field: Some("prof".into()) }));
let again = serde_json::to_value(&saved).unwrap();
assert_eq!(again["requires"], json!(["terrain-block", "terrain-water", "terrain-block-water"]));
}

/// A block's walls coloured by a polygon layer (#1914): the layer checked before anything changes,
Expand Down Expand Up @@ -13272,6 +13283,72 @@ fn terrain_block_walls_follow_a_polygon_layer() {
assert!(s.map().view.terrain.is_none());
}

#[test]
fn terrain_block_water_needs_the_terrains_water_and_a_depth() {
// #2317: the water a block's walls cut through, deep by a number or a numeric field.
use base64::Engine;
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 square = |x: f64| json!([[[x, 45.0], [x + 0.01, 45.0], [x + 0.01, 45.01], [x, 45.01], [x, 45.0]]]);
let lakes = json!({"type": "FeatureCollection", "features": [
{"type": "Feature", "properties": {"prof": 12.0, "nome": "a"}, "geometry": {"type": "Polygon", "coordinates": square(10.0)}},
{"type": "Feature", "properties": {"prof": null, "nome": "b"}, "geometry": {"type": "Polygon", "coordinates": square(10.02)}},
]});
let data = base64::engine::general_purpose::STANDARD.encode(lakes.to_string().as_bytes());
s.run("layer.addDataBytes", &json!({"fileName": "lagos.geojson", "data": data})).unwrap();
let lagos = s.map().layers.iter().find(|l| !l.is_raster()).map(|l| l.name.clone()).unwrap();
for (water, terrain_water, said) in [
(json!({}), json!({"layer": lagos}), "needs a depth"),
(json!({"depth": -1}), json!({"layer": lagos}), "0 to 20000"),
(json!({"depth": 5, "bed": "x"}), json!({"layer": lagos}), "has no 'bed'"),
(json!({"field": "nome"}), json!({"layer": lagos}), "isn't numeric"),
(json!({"field": "x"}), json!({"layer": lagos}), "has no field 'x'"),
(json!({"depth": 5}), json!(null), "give the terrain a water layer"),
(json!(3), json!({"layer": lagos}), "or false"),
] {
let e = s.run("map.terrain", &json!({"layer": dem, "water": terrain_water, "block": {"water": water}})).unwrap_err();
assert!(e.contains(said), "{water}: {e}");
assert!(s.map().view.terrain.is_none(), "{water}: refused whole");
}
// By a field: the lake with no value is said; reported and saved with the project.
let mark = s.notice_mark();
let v = s.run("map.terrain", &json!({"layer": dem, "water": {"layer": lagos}, "block": {"water": {"field": "prof"}}})).unwrap();
assert_eq!(v["block"]["water"], json!({"field": "prof"}));
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert!(said.iter().any(|t| t.contains("1 polygon of") && t.contains("no depth in 'prof'")), "{said:?}");
let saved = serde_json::to_value(&s.project).unwrap();
assert!(saved["requires"].as_array().unwrap().contains(&json!("terrain-block-water")), "{}", saved["requires"]);
// With a depth for those, nothing is said; `false` takes the water out of the walls.
let mark = s.notice_mark();
s.run("map.terrain", &json!({"block": {"water": {"field": "prof", "depth": 5}}})).unwrap();
assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("no depth")));
// Nor when the layer's definition query leaves the lake without a value out: it draws no water.
if let Some(l) = s.map_mut().layers.iter_mut().find(|l| l.name == lagos) {
l.definition_query = Some("nome = 'a'".into());
}
let mark = s.notice_mark();
s.run("map.terrain", &json!({"block": {"water": {"field": "prof"}}})).unwrap();
assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("no depth")));
// The terrain's water can't go, or become a layer without the field, under the block's water:
// refused, the terrain as it was.
let sea = json!({"type": "FeatureCollection", "features": [
{"type": "Feature", "properties": {"nome": "c"}, "geometry": {"type": "Polygon", "coordinates": square(10.03)}},
]});
let data = base64::engine::general_purpose::STANDARD.encode(sea.to_string().as_bytes());
s.run("layer.addDataBytes", &json!({"fileName": "mar.geojson", "data": data})).unwrap();
let before = s.map().view.terrain.clone();
for (water, said) in [(json!(false), "take the block's water off"), (json!({"layer": "mar"}), "has no field 'prof'")] {
let e = s.run("map.terrain", &json!({"water": water})).unwrap_err();
assert!(e.contains(said), "{water}: {e}");
assert_eq!(s.map().view.terrain, before, "{water}");
}
let v = s.run("map.terrain", &json!({"block": {"water": false}})).unwrap();
assert_eq!(v["block"]["water"], json!(null));
let saved = serde_json::to_value(&s.project).unwrap();
assert!(!saved["requires"].as_array().unwrap().contains(&json!("terrain-block-water")));
}

/// 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
Loading
Loading