diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9070f2437a..989c2a7aba 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1551,19 +1551,32 @@ fn delete_field(s: &mut Session, p: &Json) -> CmdResult { ); } // Nor a block's walls, when the depths of that water came from the field (#2317): the block's - // depth for all of it if it has one, else no water in the walls, said. + // depth for all of it if it has one, else its bed where it has heights (#2434), else no water + // in the walls, said. if let Some(t) = s.map_mut().view.terrain.as_mut() && t.water.as_ref().is_some_and(|w| w.layer.eq_ignore_ascii_case(&layer_name)) && let Some(b) = t.block.as_mut() && let Some(bw) = b.water.as_mut() && bw.field.as_deref().is_some_and(|f| f.eq_ignore_ascii_case(&removed)) { - let note = match bw.depth { - Some(d) => { + let note = match (bw.depth, bw.bed.clone()) { + (Some(d), Some(bed)) => { + bw.field = None; + format!( + "Block: its water's depths came from the deleted field {removed}, so its walls show the bed '{bed}' where it has heights and the water {d} m deep elsewhere" + ) + } + (Some(d), None) => { bw.field = None; format!("Block: its water's depths came from the deleted field {removed}, so its walls show all of it {d} m deep") } - None => { + (None, Some(bed)) => { + bw.field = None; + format!( + "Block: its water's depths came from the deleted field {removed}, so its walls show water only where the bed '{bed}' has heights" + ) + } + (None, None) => { b.water = None; format!("Block: its water's depths came from the deleted field {removed}, so its walls show no water") } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 0e80688dcc..df72d7c83f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7301,6 +7301,12 @@ fn references_follow_layer(s: &mut Session, old: &str, new: &str) { if let Some(walls) = s.map_mut().view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.walls_layer.as_mut()) { replace(walls); } + // And the raster its water's bed is read from (#2434). + if let Some(bed) = + s.map_mut().view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.water.as_mut()).and_then(|w| w.bed.as_mut()) + { + replace(bed); + } // And the polygons it is cut to (#2318). if let Some(rustgis_map::view::BlockShape::Polygon { layer, .. }) = s.map_mut().view.terrain.as_mut().and_then(|t| t.block.as_mut()).map(|b| &mut b.shape) @@ -7678,6 +7684,25 @@ fn terrain_follows_removal(s: &mut Session, names: &[String]) { false, ); } + // And the raster its water's bed is read from (#2434): the walls fall back to the water's + // depth or field meanwhile. + let bed = s + .map() + .view + .terrain + .as_ref() + .and_then(|t| t.block.as_ref()) + .and_then(|b| b.water.as_ref()) + .map(|w| (w.bed.clone(), w.depth.is_some() || w.field.is_some())); + if let Some((Some(bed), fallback)) = bed.filter(|(b, _)| { + dem.is_none() && b.as_ref().is_some_and(|b| names.iter().any(|n| n.eq_ignore_ascii_case(b)) && named_layers(s, b) == 0) + }) { + let shows = if fallback { "show the water down to its depth or field" } else { "show no water" }; + s.notify( + format!("Terrain: the block's water bed '{bed}' was removed, so the walls {shows} until a layer of that name comes back"), + false, + ); + } // And the layer of the polygons it is cut to (#2318): no block is drawn meanwhile. let cut = s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| match &b.shape { rustgis_map::view::BlockShape::Polygon { layer, .. } => Some(layer.clone()), diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 9d0bb036b8..4f9a3c557a 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -451,6 +451,35 @@ fn reset(s: &mut Session, p: Project) { false, ), } + // A block's water bed (#2434) that is missing, isn't a raster layer or shares its name with + // another layer gives no floor (`block::water_runs` reads it as the terrain command takes it): + // said, and kept, so a raster layer of that name brings it back. + let unread: Vec = s + .project + .maps + .iter() + .filter_map(|m| { + let bed = m.view.terrain.as_ref()?.block.as_ref()?.water.as_ref()?.bed.as_ref()?; + let mut named = m.layers.iter().filter(|l| l.name.eq_ignore_ascii_case(bed)); + let read = named.next().filter(|l| l.raster.is_some()).is_some() && named.next().is_none(); + (!read).then(|| format!("{} ('{bed}')", m.name)) + }) + .collect(); + match unread.as_slice() { + [] => {} + [one] => s.notify( + format!("{one}: the block's water bed is missing, isn't a raster layer, or shares its name with another layer, so its walls show the water down to its depth or field (none without either)"), + false, + ), + _ => s.notify( + format!( + "{} block diagrams have a water bed that is missing, isn't a raster layer, or shares its name with another layer, so their walls show the water down to its depth or field (none without either): {}", + unread.len(), + unread.join(", ") + ), + false, + ), + } // Water on a layer read a view at a time (#2305), which `map.terrain` refuses, would come // from the rows the view holds (the map draws none from it): dropped and said, as the project // opens. @@ -494,8 +523,12 @@ fn reset(s: &mut Session, p: Project) { 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))); + // The block's own depth, or its bed (#2434), takes the field's place; else no water. + 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, bw.bed.clone()))); let layer = l.name.clone(); let Some(t) = m.view.terrain.as_mut() else { continue }; if let Some(field) = level { @@ -504,18 +537,17 @@ fn reset(s: &mut Session, p: Project) { } levels.push((m.name.clone(), field, layer.clone())); } - if let Some((field, d)) = depth { + if let Some((field, d, bed)) = depth { if let Some(b) = t.block.as_mut() { - match d { - Some(_) => { - if let Some(bw) = b.water.as_mut() { - bw.field = None; - } + if d.is_some() || bed.is_some() { + if let Some(bw) = b.water.as_mut() { + bw.field = None; } - None => b.water = None, + } else { + b.water = None; } } - depths.push((m.name.clone(), field, layer, d)); + depths.push((m.name.clone(), field, layer, d, bed)); } } let lit = |s: &String| -> NoticeText { s.clone().into() }; @@ -543,13 +575,21 @@ fn reset(s: &mut Session, p: Project) { } match depths.as_slice() { [] => {} - [(map, field, layer, d)] => { - let (key, mut args) = match d { - Some(d) => ( + [(map, field, layer, d, bed)] => { + let (key, mut args) = match (d, bed) { + (Some(d), Some(bed)) => ( + "{map}: the block's water depth field '{field}' isn't a numeric field of '{layer}', so its walls show the bed '{bed}' where it has heights and the water {depth} m deep elsewhere", + vec![("bed", lit(bed)), ("depth", d.to_string().into())], + ), + (Some(d), None) => ( "{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 => ( + (None, Some(bed)) => ( + "{map}: the block's water depth field '{field}' isn't a numeric field of '{layer}', so its walls show water only where the bed '{bed}' has heights", + vec![("bed", lit(bed))], + ), + (None, None) => ( "{map}: the block's water depth field '{field}' isn't a numeric field of '{layer}', so its walls show no water", vec![], ), @@ -558,14 +598,22 @@ fn reset(s: &mut Session, p: Project) { s.notify_text(NoticeText::format(key, args), false); } _ => { - let maps = NoticeText::list(depths.iter().map(|(map, field, layer, d)| { + let maps = NoticeText::list(depths.iter().map(|(map, field, layer, d, bed)| { let args = [("map", lit(map)), ("field", lit(field)), ("layer", lit(layer))]; - match d { - Some(d) => NoticeText::format( + match (d, bed) { + (Some(d), Some(bed)) => NoticeText::format( + "{map} ('{field}' of '{layer}', its walls showing the bed '{bed}' where it has heights and the water {depth} m deep elsewhere)", + args.into_iter().chain([("bed", lit(bed)), ("depth", d.to_string().into())]), + ), + (Some(d), None) => 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), + (None, Some(bed)) => NoticeText::format( + "{map} ('{field}' of '{layer}', its walls showing water only where the bed '{bed}' has heights)", + args.into_iter().chain([("bed", lit(bed))]), + ), + (None, None) => NoticeText::format("{map} ('{field}' of '{layer}', its walls showing no water)", args), } })); s.notify_text( diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 2c932b1329..fa5894b649 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -49,7 +49,7 @@ pub fn commands() -> Vec { }).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) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons, each hole a well with its own walls and its floor at the base, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "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}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, 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) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons, each hole a well with its own walls and its floor at the base, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "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, "bed"?: a raster layer of the bed's heights in metres on the DEM's datum (the floor where it has data, never above the level; elsewhere the field's depth or the depth)} (one of them needed), or false}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, 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() @@ -367,8 +367,8 @@ fn terrain_block( None => base.and_then(|b| b.water.clone()), 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)")); + if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "depth" | "field" | "bed")) { + return Err(format!("block's water has no '{k}' (depth, field, bed)")); } let depth = match w.get("depth") { None | Some(Value::Null) => None, @@ -379,9 +379,15 @@ fn terrain_block( 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 }) + // A raster of the bed's heights (#2434), checked against the block's box in `terrain`. + let bed = match w.get("bed") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if !n.trim().is_empty() => Some(bed_layer(s, n)?), + Some(_) => return Err("block's water bed is a raster layer of the bed's heights".into()), + }; + Some(rustgis_map::view::BlockWater { depth, field, bed }) } - Some(_) => return Err("block's water is {\"depth\"?, \"field\"?}, or false".into()), + Some(_) => return Err("block's water is {\"depth\"?, \"field\"?, \"bed\"?}, or false".into()), }; // The outline inside the box (#2318): the box itself, or the circle in it. // A round block's radius is kept, as the shape is, when the call gives neither. @@ -428,6 +434,20 @@ fn terrain_block( Ok(block) } +/// The name of the raster layer `name` a block's water reads its bed's heights from (#2434), +/// checked: a raster layer of a name of its own. +fn bed_layer(s: &Session, name: &str) -> Result { + let name = name.trim(); + let l = s.map().layer_by_name(name).ok_or_else(|| format!("no layer '{name}' (the block's water bed)"))?; + if l.raster.is_none() { + return Err(format!("'{name}' isn't a raster layer (the block's water bed: heights of the bed in metres)")); + } + if s.map().layers.iter().filter(|o| o.name.eq_ignore_ascii_case(name)).count() > 1 { + return Err(format!("more than one layer is called '{name}': give the block's water bed a name of its own, then try again")); + } + Ok(l.name.clone()) +} + /// A block cut to polygons (#2318) from `"shape": {"layer", "where"?}`: a polygon layer as the /// water's ([`polygon_layer`]) and a `where` that reads and picks a polygon among the rows its /// definition query keeps. @@ -792,6 +812,18 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { } return Err(e); } + // And its water's bed (#2434): the map draws no bed with two layers of its name. + if let Some(l) = t.block.as_ref().and_then(|b| b.water.as_ref()).and_then(|w| w.bed.as_ref()) + && m.layers.iter().filter(|o| o.name.eq_ignore_ascii_case(l)).count() > 1 + { + let e = format!( + "more than one layer is called '{l}': give the block's water bed a name of its own, then try again (Terrain stays as it was)" + ); + if let Some(old) = old_terrain { + m.view.terrain = Some(old); + } + 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 @@ -816,6 +848,33 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { let n = if bw.depth.is_some() { 0 } else { l.dataset.features.column(i).enumerate().filter(missing).count() }; Ok((n > 0).then(|| (n, l.name.clone(), f.clone()))) })(); + // Its bed (#2434), when this call sets the block (its box can move off a bed it keeps): + // overlapping the block's box once the raster's data is there (a bed still being read + // gives no floor until it is, the walls showing the depth or field meanwhile). A bed kept + // from before whose layer went, or no longer is a raster, isn't refused: that was said, + // and a raster layer of that name brings it back. + let checked = checked.and_then(|n| { + let Some(bed) = bw.bed.as_deref().filter(|_| block.is_some()) else { return Ok(n) }; + let layer = m.layer_by_name(bed); + if !given("water") && layer.is_none_or(|l| l.raster.is_none()) { + return Ok(n); + } + let l = layer.ok_or_else(|| format!("no layer '{bed}' (the block's water bed){kept}"))?; + let raster = l.raster.as_ref().ok_or_else(|| format!("'{bed}' isn't a raster layer (the block's water bed){kept}"))?; + let boxed = t.block.as_ref().and_then(|b| b.extent.or(own)).or_else(|| dem_box.as_ref().and_then(|d| d.1)); + if let (Some(data), Some([x0, y0, x1, y1])) = (raster.data.as_ref(), boxed) { + let Some(f) = rustgis_render::terrain::raster_footprint(data) else { + return Err(format!("'{bed}' can't be placed on the map (the block's water bed){kept}")); + }; + if x1 <= f[0] || x0 >= f[2] || y1 <= f[1] || y0 >= f[3] { + return Err(format!( + "the block's water bed '{bed}' doesn't overlap the block's box: its footprint spans [{:.0}, {:.0}, {:.0}, {:.0}] in Web Mercator metres{kept}", + f[0], f[1], f[2], f[3] + )); + } + } + Ok(n) + }); match checked { Ok(n) => no_depth = n, Err(e) => { @@ -831,6 +890,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { TerrainSource::Tiles { .. } => None, }; let water_layer = t.water.as_ref().filter(|_| water.is_some()).map(|w| w.layer.clone()); + let t_bed = t.block.as_ref().and_then(|b| b.water.as_ref()).and_then(|w| w.bed.clone()); m.view.terrain = Some(t); // A polygon block's outline simplified past a third of the finest mesh cell, or short of its // smallest rings, to stay under 65 535 sides: said, with how far. @@ -846,7 +906,11 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { } 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); + let shows = match t_bed.as_deref() { + Some(bed) => format!("shows water only where the bed '{bed}' has heights"), + None => "shows no water".to_string(), + }; + s.notify(format!("Block: {polygons} of '{layer}' {have} no depth in '{field}', so a wall crossing them {shows}"), false); } // When the water is set, what its levels left out is said, with how many. if let Some(name) = water_layer { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 27179ae2e0..cf3179166a 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -80,6 +80,7 @@ pub const CAPABILITIES: &[&str] = &[ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-water-bed", "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 8003aa1b04..3a9d188f3c 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1008,7 +1008,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut polygon, mut svg) = (false, false); let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); - let mut crisp = false; + let (mut crisp, mut bed) = (false, false); for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. @@ -1036,6 +1036,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static 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()); + // Its bed read from a raster (#2434), which an older reader would save away. + bed |= t.block.as_ref().and_then(|b| b.water.as_ref()).is_some_and(|w| w.bed.is_some()); // The layer a block's walls are coloured by (#2173), which an older reader would save away. walls_layer |= t.block.as_ref().is_some_and(|b| b.walls_layer.is_some()); } @@ -1057,6 +1059,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (water, "terrain-water"), (shore, "terrain-water-shore"), (block_water, "terrain-block-water"), + (bed, "terrain-block-water-bed"), (walls_layer, "terrain-block-walls-layer"), (relief, "shaded-relief-effects"), (light, "shaded-relief-light"), @@ -1249,6 +1252,23 @@ mod tests { assert_eq!(serde_json::to_value(&plain).unwrap()["requires"], json!(["terrain-block"])); } + /// A block's water floor read from a bed raster (#2434) reads back by the raster's name, and + /// saving names it in `requires`; the same water without a bed doesn't. + #[test] + fn terrain_block_water_bed_fixture_requires_it() { + let fixture = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_water_bed_v2.rgis")).unwrap(); + let water = fixture.maps[0].view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.water.clone()); + assert_eq!(water, Some(rustgis_map::view::BlockWater { depth: Some(8.0), field: None, bed: Some("batimetria".into()) })); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["terrain-block", "terrain-water", "terrain-block-water", "terrain-block-water-bed"])); + assert_eq!(saved["maps"][0]["view"]["terrain"]["block"]["water"], json!({"depth": 8.0, "bed": "batimetria"})); + let mut plain = fixture; + if let Some(w) = plain.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.water.as_mut()) { + w.bed = None; + } + assert_eq!(serde_json::to_value(&plain).unwrap()["requires"], json!(["terrain-block", "terrain-water", "terrain-block-water"])); + } + /// A saved image marker reads back as the image it was, and saving names it again. #[test] fn picture_markers_fixture_reads_its_image() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index de68ca1e88..63c4f68d0a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -18065,7 +18065,7 @@ fn terrain_block_is_read_back_from_a_saved_project() { // 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()) })); + assert_eq!(block.water, Some(rustgis_map::view::BlockWater { depth: Some(8.0), field: Some("prof".into()), bed: None })); let again = serde_json::to_value(&saved).unwrap(); assert_eq!(again["requires"], json!(["terrain-block", "terrain-water", "terrain-block-water"])); // One cut to polygons (`terrain_block_polygon.rgis`), its layer and query kept by name. @@ -18371,7 +18371,7 @@ fn terrain_block_water_needs_the_terrains_water_and_a_depth() { 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!({"depth": 5, "floor": "x"}), json!({"layer": lagos}), "has no 'floor'"), (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"), @@ -18433,6 +18433,144 @@ fn terrain_block_water_needs_the_terrains_water_and_a_depth() { } } +/// A block's water floor read from a bed raster (#2434): `map.terrain` takes a raster layer over +/// the block's box, alone or with a depth, refuses anything else before the terrain changes, +/// saves it as a capability of its own, follows the layer's rename and says its removal. +#[test] +fn terrain_block_water_bed_is_a_raster_over_the_block() { + use base64::Engine; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + 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(); + // Beds of 150 m: one over the DEM, one 10° east of it. + for (name, lon) in [("batimetria.tif", 10.0), ("longe.tif", 20.0)] { + let gt = GeoTransform { origin_x: lon, origin_y: 45.04, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("bed", 40, 40, vec![vec![150.0; 1600]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": name, "data": data})).unwrap(); + } + let named = |s: &Session, start: &str| s.map().layers.iter().find(|l| l.name.starts_with(start)).map(|l| l.name.clone()).unwrap(); + let (bed, far) = (named(&s, "batimetria"), named(&s, "longe")); + let lake = json!([[[10.01, 45.01], [10.03, 45.01], [10.03, 45.03], [10.01, 45.03], [10.01, 45.01]]]); + let lakes = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"nome": "a"}, "geometry": {"type": "Polygon", "coordinates": lake}}, + ]}); + 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 = named(&s, "lagos"); + for (water, said) in [ + (json!({"depth": 5, "bed": lagos}), "isn't a raster layer"), + (json!({"depth": 5, "bed": "nada"}), "no layer 'nada'"), + (json!({"depth": 5, "bed": 3}), "a raster layer of the bed's heights"), + (json!({"depth": 5, "bed": far}), "doesn't overlap the block's box"), + ] { + let e = s.run("map.terrain", &json!({"layer": dem, "water": {"layer": lagos}, "block": {"water": water}})).unwrap_err(); + assert!(e.contains(said), "{water}: {e}"); + assert!(s.map().view.terrain.is_none(), "{water}: refused whole"); + } + // A bed alone is enough; reported and saved with the project, which requires it. + let v = s.run("map.terrain", &json!({"layer": dem, "water": {"layer": lagos}, "block": {"water": {"bed": bed}}})).unwrap(); + assert_eq!(v["block"]["water"], json!({"bed": bed})); + let saved = serde_json::to_value(&s.project).unwrap(); + assert!(saved["requires"].as_array().unwrap().contains(&json!("terrain-block-water-bed")), "{}", saved["requires"]); + // A block kept from before is checked again when set: a bed off its box is refused. + let before = s.map().view.terrain.clone(); + let e = s.run("map.terrain", &json!({"block": {"water": {"bed": far}}})).unwrap_err(); + assert!(e.contains("doesn't overlap") && e.contains("Terrain stays as it was"), "{e}"); + assert_eq!(s.map().view.terrain, before); + // The bed is kept by name through a rename, and its removal is said. + s.run("layer.rename", &json!({"layer": bed, "name": "fundo"})).unwrap(); + let kept = |s: &Session| s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.water.clone()).and_then(|w| w.bed); + assert_eq!(kept(&s).as_deref(), Some("fundo")); + let mark = s.notice_mark(); + s.run("layer.remove", &json!({"layer": "fundo"})).unwrap(); + let notes: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(notes.iter().any(|t| t.contains("water bed 'fundo' was removed") && t.contains("show no water")), "{notes:?}"); + assert_eq!(kept(&s).as_deref(), Some("fundo")); +} + +/// A block's water bed (#2434) that can't be read is said as a project opens; the notices for a +/// lost depth field name the bed when there is one; a block moved off a kept bed is refused; and a +/// rename giving another layer the bed's name is counted among the references it makes ambiguous. +#[test] +fn a_block_water_bed_is_said_where_it_cant_be_read() { + use base64::Engine; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + // A project saved with a bed and no layers at all: its bed can't be read, said; the name kept. + let saved = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_water_bed_v2.rgis")).unwrap(); + let mut opened = Session::new(Project::default()); + crate::cmd::project::reset_to(&mut opened, saved); + assert!(opened.notices.iter().any(|n| n.text.contains("('batimetria'): the block's water bed is missing")), "{:?}", opened.notices); + let bed_of = + |s: &Session| s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.water.clone()).and_then(|w| w.bed); + assert_eq!(bed_of(&opened).as_deref(), Some("batimetria")); + 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(); + // Beds of 150 m: one over the whole DEM, one over its east quarter, one 10° east of it. + for (name, lon, cols) in [("batimetria.tif", 10.0, 40), ("leste.tif", 10.03, 10), ("longe.tif", 20.0, 40)] { + let gt = GeoTransform { origin_x: lon, origin_y: 45.04, pixel_width: 0.001, pixel_height: -0.001 }; + let r = + Raster::new("bed", cols, 40, vec![vec![150.0; cols as usize * 40]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(geotiff::write(&r, 0).unwrap()); + s.run("layer.addDataBytes", &json!({"fileName": name, "data": data})).unwrap(); + } + let named = |s: &Session, start: &str| s.map().layers.iter().find(|l| l.name.starts_with(start)).map(|l| l.name.clone()).unwrap(); + let (bed, east, far) = (named(&s, "batimetria"), named(&s, "leste"), named(&s, "longe")); + let lake = json!([[[10.01, 45.01], [10.03, 45.01], [10.03, 45.03], [10.01, 45.03], [10.01, 45.01]]]); + let lakes = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"nome": "a", "prof": 4.0}, "geometry": {"type": "Polygon", "coordinates": lake}}, + ]}); + 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 = named(&s, "lagos"); + // The same project with its bed there opens without a word about it. + s.run("map.terrain", &json!({"layer": dem, "water": {"layer": lagos}, "block": {"water": {"bed": east}}})).unwrap(); + let mut opened = Session::new(Project::default()); + crate::cmd::project::reset_to(&mut opened, s.project.clone()); + assert!(!opened.notices.iter().any(|n| n.text.contains("water bed")), "{:?}", opened.notices); + // A block moved off a bed it keeps is refused, the terrain as it was. + let merc = |lon: f64, lat: f64| rustgis_geom::lonlat_to_merc(rustgis_geom::Coord::new(lon, lat)); + let (a, z) = (merc(10.002, 45.002), merc(10.02, 45.02)); + let before = s.map().view.terrain.clone(); + let e = s.run("map.terrain", &json!({"block": {"extent": [a.x, a.y, z.x, z.y]}})).unwrap_err(); + assert!(e.contains("doesn't overlap") && e.contains(&east) && e.contains("Terrain stays as it was"), "{e}"); + assert_eq!(s.map().view.terrain, before); + // A depth field lost with a depth and a bed: the bed still gives the floor where it has heights. + s.run("map.terrain", &json!({"block": {"water": {"bed": bed, "depth": 5, "field": "prof"}}})).unwrap(); + let mut wrong = s.project.clone(); + if let Some(w) = wrong.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.water.as_mut()) { + w.field = Some("nome".into()); + } + let mut opened = Session::new(Project::default()); + crate::cmd::project::reset_to(&mut opened, wrong); + let said = |notes: &[String]| { + notes.iter().any(|t| t.contains("'nome'") && t.contains(&format!("bed '{bed}'")) && t.contains("5 m deep elsewhere")) + }; + let notes: Vec = opened.notices.iter().map(|n| n.text.clone()).collect(); + assert!(said(¬es), "{notes:?}"); + let mark = s.notice_mark(); + s.run("edit.deleteField", &json!({"layer": lagos, "field": "prof"})).unwrap(); + let notes: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + notes.iter().any(|t| t.contains("prof") && t.contains(&format!("bed '{bed}'")) && t.contains("5 m deep elsewhere")), + "{notes:?}" + ); + // Another layer renamed to the bed's name: the bed is among the references the rename makes ambiguous. + let id = s.map().layer_by_name(&far).map(|l| l.id).unwrap(); + let mark = s.notice_mark(); + s.run("layer.rename", &json!({"layer": id, "name": bed})).unwrap(); + let notes: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(notes.iter().any(|t| t.contains(&format!("reference(s) already name '{bed}'"))), "{notes:?}"); + // With two layers of that name the map draws no bed: a block update is refused, the terrain as + // it was, though the first of them is a raster over the block. + let before = s.map().view.terrain.clone(); + let e = s.run("map.terrain", &json!({"block": {"extent": null}})).unwrap_err(); + assert!(e.contains(&format!("more than one layer is called '{bed}'")) && e.contains("Terrain stays as it was"), "{e}"); + assert_eq!(s.map().view.terrain, before); +} + /// A terrain's water on a layer read a view at a time (#2305), which `map.terrain` refuses: the /// map draws no water from the view's rows, and a project naming it opens without it, said. #[test] @@ -18493,7 +18631,7 @@ fn a_projects_water_fields_its_layer_lost_are_cleared_as_it_opens() { 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!(t.block.and_then(|b| b.water), Some(BlockWater { depth: Some(8.0), field: None, bed: 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); diff --git a/crates/map/src/view.rs b/crates/map/src/view.rs index 2bbd5a3eb1..fda47f120e 100644 --- a/crates/map/src/view.rs +++ b/crates/map/src/view.rs @@ -273,7 +273,8 @@ impl TerrainBlock { } /// How deep the water a block diagram's walls cut through is (#2317). A DEM holds the water's -/// surface, not its bed, so the depth is given: schematic unless it comes from a field. +/// surface, not its bed, so the depth is given: schematic unless it comes from a field, or the +/// bed is read from a raster of its heights (#2434). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BlockWater { /// Metres from the level down to the floor, before exaggeration: every water body's, or @@ -283,6 +284,11 @@ pub struct BlockWater { /// A numeric field of the terrain's water layer holding each water body's depth (metres). #[serde(default, skip_serializing_if = "Option::is_none")] pub field: Option, + /// A raster layer of the bed's heights (metres, on the DEM's vertical datum; the DEM itself + /// when it is topo-bathymetric), kept by name (#2434): the floor along the walls' water where + /// it has data, never above the level, else the field's depth or `depth`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bed: Option, } /// The least depth (metres, before exaggeration) of a block diagram's base below its lowest @@ -343,8 +349,13 @@ impl TerrainBlock { return Err("block's walls is an opaque colour, #RRGGBB".into()); } if let Some(w) = &self.water { - if w.depth.is_none() && w.field.is_none() { - return Err("block's water needs a depth (metres) or a field of the water layer holding them".into()); + if w.depth.is_none() && w.field.is_none() && w.bed.is_none() { + return Err( + "block's water needs a depth (metres), a field of the water layer holding them, or a bed raster of its heights".into(), + ); + } + if w.bed.as_deref().is_some_and(|b| b.trim().is_empty()) { + return Err("block's water bed is a raster layer of the bed's heights".into()); } if let Some(d) = w.depth && !(d.is_finite() && (0.0..=BLOCK_MAX_DEPTH).contains(&d)) diff --git a/crates/render/src/approximations.rs b/crates/render/src/approximations.rs index 4719f50950..5a47279947 100644 --- a/crates/render/src/approximations.rs +++ b/crates/render/src/approximations.rs @@ -324,6 +324,31 @@ pub(crate) fn walls_left_plain(name: &str, n: usize) { ); } +/// What a block diagram's walls drew of the water's bed raster `name` (#2434): it has no heights +/// along `n` stretches of the walls' water, in `bodies` water bodies, where the floor is the +/// water's depth or field instead (no water there without either). +pub(crate) fn bed_unread(name: &str, n: usize, bodies: usize) { + let stretches = if n == 1 { "1 stretch".to_string() } else { format!("{n} stretches") }; + let bodies = if bodies == 1 { "1 water body".to_string() } else { format!("{bodies} water bodies") }; + note( + format!("{name}\0bed"), + format!( + "{name}: the block's water bed has no heights along {stretches} of the walls' water, in {bodies}, so there the walls show the water down to its depth or field (none without either)" + ), + ); +} + +/// Notes a block's water bed (#2434) named by a layer `name` that isn't a raster (renamed or +/// added to the bed's name): the walls read no bed from it. +pub(crate) fn bed_not_raster(name: &str) { + note( + format!("{name}bed layer"), + format!( + "{name}: the block's water bed isn't a raster layer, so the walls show the water down to its depth or field (none without either) until a raster layer of that name is there" + ), + ); +} + /// What to say of a block diagram whose `share` (0 to 1) of the ground it read for its base /// had no height (off the DEM, the DEM's nodata, an elevation tile that failed), taken as 0 /// ([`crate::terrain::Block::without_height_notice`]). diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 10b483169c..f921f7c743 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -604,14 +604,26 @@ type Part = (usize, Vec>, Extent); /// A layer's [`Units`] along a block's outline, and for the water (#2317) the polygons reaching /// the box, whose shores shape the water's floor: each by its row and its place among the row's /// parts, read again from the layer's rows (the key holds them), so a large lake or sea crossing -/// the box is not kept twice. +/// the box is not kept twice. With a bed raster (#2434), the bed's heights along each piece of +/// water ([`bed_heights`]). struct Cut { units: Units, parts: Vec<(usize, usize)>, + beds: Beds, } -/// The rows, layer, query, query context, box, circle and outline a [`Cut`] was read for, and -/// whether for the water. +/// The bed's heights (metres, before exaggeration; NaN where the bed has none) along each piece +/// of [`Units`] under water (#2434), in their order: from its `lo` to its `hi` at even steps, so +/// only the heights are kept, 4 bytes a sample. Empty for a piece off the water and without a bed. +type Beds = Vec>>; + +/// The most heights read for a block's bed along all its walls' water (#2434): a bed whose cells +/// are finer than its share of the water's length is read at that share instead, so a national +/// bathymetry crossing a large box stays cheap (64 kB kept). +const MAX_BED_SAMPLES: usize = 16_384; + +/// The rows, layer, query, query context, box, circle and outline a [`Cut`] was read for, whether +/// for the water, and the bed raster (by name and data) read with it (#2434). struct Key { rows: Weak>, layer: String, @@ -621,6 +633,7 @@ struct Key { circle: Option<(Coord, f64)>, outline: Option>, water: bool, + bed: Option<(String, Weak)>, } impl Key { @@ -636,6 +649,10 @@ impl Key { (a, b) => a.is_none() && b.is_none(), } && self.water == o.water + && match (&self.bed, &o.bed) { + (Some((n, a)), Some((m, b))) => n == m && a.ptr_eq(b), + (a, b) => a.is_none() && b.is_none(), + } } } @@ -645,8 +662,15 @@ static LAST: Mutex)>> = Mutex::new(Vec::new()); /// How many cuts [`LAST`] keeps (maps drawn side by side, a layout's frames, walls and water). const KEPT: usize = 4; -/// `layer`'s [`Cut`] along block `b`'s outline, from [`LAST`] when it was read already. -fn layer_cut(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_data::query::Env) -> Arc { +/// `layer`'s [`Cut`] along block `b`'s outline, from [`LAST`] when it was read already, with the +/// heights of the `bed` raster (its name and data, #2434) along the water's pieces. +fn layer_cut( + layer: &rustgis_map::Layer, + b: &Block, + water: bool, + bed: Option<(&str, &Arc)>, + env: &rustgis_data::query::Env, +) -> Arc { let key = Key { rows: layer.dataset.features.allocation_key(), layer: layer.name.clone(), @@ -656,12 +680,17 @@ fn layer_cut(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_d circle: b.circle, outline: b.outline.as_ref().map(Arc::downgrade), water, + bed: bed.map(|(n, r)| (n.to_string(), Arc::downgrade(r))), }; let kept = LAST.lock().ok().and_then(|last| last.iter().find(|(k, _)| k.same(&key)).map(|(_, u)| u.clone())); kept.unwrap_or_else(|| { - let u = Arc::new(units(layer, b, water, env)); + let mut cut = units(layer, b, water, env); + if let Some((_, raster)) = bed { + cut.beds = bed_heights(raster, b, &cut.units); + } + let u = Arc::new(cut); if let Ok(mut last) = LAST.lock() { - last.retain(|(k, _)| k.rows.strong_count() > 0 && !k.same(&key)); + last.retain(|(k, _)| k.rows.strong_count() > 0 && k.bed.as_ref().is_none_or(|(_, r)| r.strong_count() > 0) && !k.same(&key)); if last.len() >= KEPT { last.remove(0); } @@ -700,7 +729,7 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: .and_then(|n| crate::terrain::walls_layer(map, n)); let Some(layer) = layer else { return (0..b.sides()).map(whole).collect() }; crate::note_held_read(layer); - let cut = layer_cut(layer, b, false, env); + let cut = layer_cut(layer, b, false, None, env); let styler = layer.styler_with(env.clone()); let grow = layer.size_factor(scale); // The rows along the walls whose gradients or shapebursts the walls leave off, said once @@ -876,33 +905,108 @@ fn units(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_data: out }; let units = (0..b.sides()).map(side_units).collect(); - Cut { units, parts: if water { ids } else { Vec::new() } } + Cut { units, parts: if water { ids } else { Vec::new() }, beds: Vec::new() } +} + +/// The heights of `bed` (#2434, [`crate::terrain::dem_height`]: bilinear, NaN off it or at its +/// no-data) along each piece of `units` under water, at even steps of its cell at the box's +/// centre, or of the water's length over [`MAX_BED_SAMPLES`] when that is longer: each piece from +/// its `lo` to its `hi`, both ends read. Reads at most `MAX_BED_SAMPLES` plus two a piece. +fn bed_heights(bed: &rustgis_data::raster::Raster, b: &Block, units: &Units) -> Beds { + let wet = |u: &(f64, f64, Option)| u.2.is_some(); + let length: f64 = units.iter().flatten().filter(|u| wet(u)).map(|u| (u.1 - u.0).abs()).sum(); + let step = bed_cell(bed, b).unwrap_or(0.0).max(length / MAX_BED_SAMPLES as f64); + units + .iter() + .enumerate() + .map(|(i, side)| { + let key = b.side(i).0; + side.iter() + .map(|u| { + if !wet(u) || step <= 0.0 || !step.is_finite() { + return Vec::new(); + } + let n = ((u.1 - u.0).abs() / step).ceil().clamp(1.0, MAX_BED_SAMPLES as f64) as usize; + (0..=n) + .map(|k| { + let t = u.0 + (u.1 - u.0) * k as f64 / n as f64; + crate::terrain::dem_height(bed, b.point(key, t)).map_or(f32::NAN, |h| h as f32) + }) + .collect() + }) + .collect() + }) + .collect() +} + +/// The side of one of `bed`'s cells at block `b`'s centre (Web Mercator), the shorter of across +/// and down; `None` where the centre can't be placed on its grid. +fn bed_cell(bed: &rustgis_data::raster::Raster, b: &Block) -> Option { + let c = Coord::new((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + let t = bed.transformer(); + let (px, py) = bed.transform.to_pixel(t.from_merc(c)?); + let at = |dx: f64, dy: f64| t.to_lonlat(bed.transform.to_world(px + dx, py + dy)).map(lonlat_to_merc); + let (o, x, y) = (at(0.0, 0.0)?, at(1.0, 0.0)?, at(0.0, 1.0)?); + let cell = (x.x - o.x).hypot(x.y - o.y).min((y.x - o.x).hypot(y.y - o.y)); + (cell.is_finite() && cell > 0.0).then_some(cell) } /// A stretch of one side of the outline inside a water body (#2317): from `lo` to `hi` along it -/// ([`Block::along`]), in the water layer's fill `color`, from the water's `level` down to -/// `depth` below it (metres, exaggerated as [`Ground::height`]'s are) where the shore is `ramp` -/// or more away (Web Mercator), less nearer it; `shore` holds the shore's edges near the side -/// (Web Mercator), and `dark` how dark the line along the floor is, as the shore band at its -/// outline. +/// ([`Block::along`]), in the water layer's fill `color`, from the water's `level` down to its +/// floor: the `bed`'s heights where it has them (#2434), else `fallback` below the level (the +/// field's depth or the block's; metres, exaggerated as [`Ground::height`]'s are) where the +/// shore is `ramp` or more away (Web Mercator), less nearer it, and no water where neither +/// gives a floor. `depth` is the deepest the floor lies below the level along it, which the +/// water's shading runs to. `shore` holds the shore's edges near the side (Web Mercator), and +/// `dark` how dark the line along the floor is, as the shore band at its outline. pub(crate) struct WaterRun { pub lo: f64, pub hi: f64, pub color: Rgba, pub level: f64, pub depth: f64, + fallback: Option, + /// The bed's heights along the stretch (exaggerated; `None` where it has none), by place + /// along the side, in order, with the places it crosses the level put in at the level. + /// Empty without a bed. + bed: Vec<(f64, Option)>, ramp: f64, shore: Vec<(Coord, Coord)>, dark: f64, } impl WaterRun { - /// The floor's height at `m` on the side: the level at the shore, falling evenly to the full - /// depth `ramp` in from it, so the section shows a basin and no cliff at the shoreline. + /// The floor's height at `m` on the side from the depth given: the level at the shore, + /// falling evenly to the full depth `ramp` in from it, so the section shows a basin and no + /// cliff at the shoreline. fn floor(&self, m: Coord) -> f64 { let near = self.shore.iter().map(|&(a, q)| segment_distance(m, a, q)).fold(f64::INFINITY, f64::min); let share = if self.ramp > 0.0 { (near / self.ramp).min(1.0) } else { 1.0 }; - self.level - self.depth * share + self.level - self.fallback.unwrap_or(0.0) * share + } + + /// The floor's height at `m`, `along` the side (#2434): the bed's there, when it has one, + /// none (no water) where that lies above the level; else [`WaterRun::floor`] with the depth + /// given, none without one. + fn floor_at(&self, along: f64, m: Coord) -> Option { + match self.bed_at(along) { + Some(h) => (h <= self.level).then_some(h), + None => self.fallback.map(|_| self.floor(m)), + } + } + + /// The bed's height `along` the side: between its two samples there, or the nearer's where + /// one of them has none. + fn bed_at(&self, along: f64) -> Option { + let i = self.bed.partition_point(|p| p.0 <= along); + let (Some(a), Some(z)) = (self.bed.get(i.saturating_sub(1)), self.bed.get(i.min(self.bed.len().saturating_sub(1)))) else { + return None; + }; + match (a.1, z.1) { + (Some(p), Some(q)) if z.0 > a.0 => Some(p + (q - p) * ((along - a.0) / (z.0 - a.0)).clamp(0.0, 1.0)), + _ if (along - a.0).abs() <= (z.0 - along).abs() => a.1, + _ => z.1, + } } } @@ -926,11 +1030,15 @@ const SECTION_WATER: Rgba = Rgba::rgb(0x8F, 0xB8, 0xDE); /// keeps) that has a level on `ground` and a depth (its row's value of the depth field, else the /// depth given), with the shore band's reach at the view centre's scale (`res`, map units a /// logical pixel) as the floor's ramp, styled at the view centre's drawing scale (`scale`, its -/// fill's `@map_scale`). Runs on the thread drawing the frame; the stretches are -/// kept as the walls' units are ([`layer_cut`]). Each frame keeps, once for each water body a stretch -/// lies in, the edges of its rings within the ramp of the box, then for each stretch those -/// within the ramp of it, a few comparisons an edge (the ramp follows the view's scale, so they -/// can't be kept with the stretches). +/// fill's `@map_scale`). With a bed raster (#2434, `BlockWater::bed`), its heights give the +/// floor where it has them, the depth only elsewhere, and a stretch with neither has no water; the +/// stretches where the bed has no heights are counted, said once with the water bodies they lie +/// in (see `crate::approximations`). Runs on the thread drawing the frame; the stretches and the +/// bed's heights along them are kept as the walls' units are ([`layer_cut`]). Each frame keeps, +/// once for each water body a stretch lies in, the edges of its rings within the ramp of the box, +/// then for each stretch those within the ramp of it, a few comparisons an edge (the ramp follows +/// the view's scale, so they can't be kept with the stretches), and goes once over the bed's +/// heights along it. pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: f64, env: &rustgis_data::query::Env) -> WaterRuns { let mut out: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); let Some(t) = map.view.terrain.as_ref() else { return out }; @@ -940,7 +1048,17 @@ pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: let Some(layer) = crate::terrain::walls_layer(map, &tw.layer) else { return out }; crate::note_held_read(layer); let field = bw.field.as_deref().and_then(|f| layer.dataset.field_index(f)); - let cut = layer_cut(layer, b, true, env); + // The bed's raster, while a layer of that name holds one (#2434): else the depth alone, and + // a layer of that name that isn't a raster (renamed or added to it) said. + let named = bw.bed.as_deref().and_then(|n| { + let mut named = map.layers.iter().filter(|l| l.name.eq_ignore_ascii_case(n)); + named.next().filter(|_| named.next().is_none()) + }); + if let Some(l) = named.filter(|l| l.raster.is_none()) { + crate::approximations::bed_not_raster(&l.name); + } + let bed = named.and_then(|l| Some((l.name.as_str(), l.raster.as_ref()?.data.as_ref()?))); + let cut = layer_cut(layer, b, true, bed, env); // Styled at the view centre's drawing scale, as the water layer is drawn on the surface. let styler = layer.styler_with(env.at_scale(Some(scale))); let x = ground.exaggeration(); @@ -950,16 +1068,44 @@ pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: let mut near_box: std::collections::HashMap> = std::collections::HashMap::new(); // The layer's conversion to longitude/latitude, as the cut's parts were read (`units`). let to = layer.dataset.shown_conversion().ok(); + // The stretches where the bed has no heights, and the water bodies they lie in (#2434). + let (mut unread, mut bodies) = (0usize, std::collections::BTreeSet::new()); for (i, runs) in out.iter_mut().enumerate() { let (side, _, _) = b.side(i); let Some(units) = cut.units.get(i) else { continue }; - for &(lo, hi, part) in units { + for (j, &(lo, hi, part)) in units.iter().enumerate() { let Some(p) = part else { continue }; let Some(&(row, k)) = cut.parts.get(p) else { continue }; let given = field.and_then(|f| layer.dataset.features.value(row, f).as_f64()).filter(|d| d.is_finite() && *d > 0.0); - let Some(depth) = given.or(bw.depth).filter(|d| *d > 0.0) else { continue }; + let fallback = given.or(bw.depth).filter(|d| *d > 0.0); let mid = b.point(side, (lo + hi) / 2.0); let Some(level) = water.level(mid) else { continue }; + let level = level * x; + let heights = cut.beds.get(i).and_then(|side| side.get(j)).map_or(&[][..], Vec::as_slice); + let bed = bed_samples(heights, lo, hi, level, x); + // How many stretches the bed has no heights along. + let gaps = bed.windows(2).filter(|w| w[0].1.is_some() && w[1].1.is_none()).count() + + usize::from(bed.first().is_some_and(|p| p.1.is_none())); + if gaps > 0 { + unread += gaps; + bodies.insert(p); + } + // The deepest the floor lies: the bed's lowest under the level, and the depth given + // where the bed has none (all along without one). + let bed_deep = bed + .iter() + .filter_map(|p| p.1) + .filter(|h| *h <= level) + .map(|h| level - h) + .fold(None, |d: Option, h| Some(d.map_or(h, |d| d.max(h)))); + let fallback = fallback.map(|d| d * x).filter(|_| bed.is_empty() || gaps > 0); + let depth = match (bed_deep, fallback) { + (Some(d), Some(f)) => d.max(f), + (d, f) => match d.or(f) { + Some(d) => d, + None => continue, + }, + }; // Its topmost solid fill, as the walls' units take theirs, laid over a light blue by its // opacity: a section is opaque. let (sym, _, fills) = styler.style_and_fills(row); @@ -994,10 +1140,33 @@ pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, scale: (da.abs() <= ramp || dq.abs() <= ramp || (da > 0.0) != (dq > 0.0)) && sa.max(sq) >= lo - ramp && sa.min(sq) <= hi + ramp }) .collect(); - let (level, depth) = (level * x, depth * x); - runs.push(WaterRun { lo, hi, color, level, depth, ramp, shore, dark: tw.shore }); + runs.push(WaterRun { lo, hi, color, level, depth, fallback, bed, ramp, shore, dark: tw.shore }); } } + if let (Some((name, _)), true) = (bed, unread > 0) { + crate::approximations::bed_unread(name, unread, bodies.len()); + } + out +} + +/// The bed's `heights` along a stretch from `lo` to `hi` (#2434, [`bed_heights`]: even steps, +/// NaN where it has none) as places along the side and heights exaggerated `x` times, with the +/// places where it crosses the water's `level` (exaggerated) put in at the level, so the water +/// ends there and not at the sample beyond it. Empty without heights. +fn bed_samples(heights: &[f32], lo: f64, hi: f64, level: f64, x: f64) -> Vec<(f64, Option)> { + let n = heights.len().saturating_sub(1).max(1) as f64; + let mut out: Vec<(f64, Option)> = Vec::with_capacity(heights.len() + 2); + for (k, h) in heights.iter().enumerate() { + let at = (lo + (hi - lo) * k as f64 / n, Some(f64::from(*h) * x).filter(|h| h.is_finite())); + if let Some(&(s, Some(p))) = out.last() + && let Some(q) = at.1 + && (p <= level) != (q <= level) + && q != p + { + out.push((s + (at.0 - s) * (level - p) / (q - p), Some(level))); + } + out.push(at); + } out } @@ -1552,12 +1721,14 @@ pub(crate) fn draw_walls( } } // The water the side cuts through (#2317), over the wall and its contacts: from its level - // down to the floor, sampled along each stretch so the floor follows the shore. + // down to the floor, sampled along each stretch so the floor follows the shore, and at + // each of the bed's samples too where it is read (#2434), so the floor follows the bed. for wr in water.get(s).into_iter().flatten() { // Along the run: each point's place along the side, its level and floor on screen, - // and the floor at the full depth there, for the shading. + // and the floor at the full depth there, for the shading; and the places with no + // water (the bed above the level, or no floor known), where the band breaks. type Sample = (f64, (f64, f64), (f64, f64), (f64, f64)); - let mut samples: Vec = Vec::new(); + let (mut samples, mut dry): (Vec, Vec) = (Vec::new(), Vec::new()); for (ends, _, [ta, tz]) in &quads { let (ca, cz) = (b.along(side, ends[0]), b.along(side, ends[1])); let span = cz - ca; @@ -1566,26 +1737,43 @@ pub(crate) fn draw_walls( } let (u, v) = ((wr.lo - ca) / span, (wr.hi - ca) / span); let (t0, t1) = (u.min(v).max(0.0), u.max(v).min(1.0)); - for i in (t1 > t0).then_some(0..=WATER_STEPS).into_iter().flatten() { - let t = t0 + (t1 - t0) * f64::from(i) / f64::from(WATER_STEPS); + let steps = (t1 > t0).then_some(0..=WATER_STEPS).into_iter().flatten(); + let steps = steps.map(|i| t0 + (t1 - t0) * f64::from(i) / f64::from(WATER_STEPS)); + // The bed's samples within the stretch's part of the run, by binary search: those + // with a height; without a depth to fall back on those without one too, where the + // water stops; and with one those without one next to one with, where the floor + // steps to the depth's (elsewhere it is sampled as without a bed). + let (blo, bhi) = (ca + span * t0, ca + span * t1); + let (blo, bhi) = (blo.min(bhi), blo.max(bhi)); + let has = |i: Option| i.and_then(|i| wr.bed.get(i)).is_some_and(|p| p.1.is_some()); + let keep = |i: usize| has(Some(i)) || wr.fallback.is_none() || has(i.checked_sub(1)) || has(Some(i + 1)); + let range = wr.bed.partition_point(|p| p.0 < blo)..wr.bed.partition_point(|p| p.0 <= bhi); + let beds = range.filter(|&i| t1 > t0 && keep(i)).filter_map(|i| wr.bed.get(i)).map(|p| (p.0 - ca) / span); + for t in steps.chain(beds) { let m = Coord::new(ends[0].x + (ends[1].x - ends[0].x) * t, ends[0].y + (ends[1].y - ends[0].y) * t); + let along = b.along(side, m); + let Some(floor) = wr.floor_at(along, m) else { + dry.push(along); + continue; + }; let (gu, gv) = cam.ground_px(m); let raised = |height: f64| { let up = (height.max(b.base) / ground.per_unit(m) / res).clamp(-1e7, 1e7); cam.project_raised(gu, gv, up, w, h).map(|(x, y)| (x * k, y * k)).filter(|p| p.0.is_finite() && p.1.is_finite()) }; - if let (Some(floor), Some(deep)) = (raised(wr.floor(m)), raised(wr.level - wr.depth)) { + if let (Some(floor), Some(deep)) = (raised(floor), raised(wr.level - wr.depth)) { // The water's level, or the ground's edge where that runs lower: the mesh // draws a stretch reaching past the shore partly at the land's heights // (up is up the screen in a tilted view). let edge = lerp(*ta, *tz, t); let top = raised(wr.level).filter(|l| l.1 > edge.1).unwrap_or(edge); - samples.push((b.along(side, m), top, floor, deep)); + samples.push((along, top, floor, deep)); } } } samples.sort_by(|p, q| p.0.total_cmp(&q.0)); samples.dedup_by(|p, q| (p.0 - q.0).abs() < 1e-9); + dry.sort_by(f64::total_cmp); // The wall's stretches within the run, joined where they meet or overlap: a band of // ground that failed to draw (`render_tilted` goes on without it) leaves the wall in // pieces, and the water keeps to each, crossing no gap where no wall stands. @@ -1607,8 +1795,20 @@ pub(crate) fn draw_walls( _ => pieces.push((lo, hi)), } } - for (lo, hi) in pieces { - let mut samples: Vec = samples.iter().filter(|p| p.0 >= lo - tol && p.0 <= hi + tol).copied().collect(); + // Each piece's samples, broken where a place with no water lies between two of them + // (#2434): one band each. + let dry_between = |a: f64, z: f64| dry.partition_point(|d| *d <= a) < dry.partition_point(|d| *d < z); + let bands = pieces.into_iter().flat_map(|(lo, hi)| { + let mut bands: Vec> = Vec::new(); + for p in samples.iter().filter(|p| p.0 >= lo - tol && p.0 <= hi + tol) { + match bands.last_mut() { + Some(band) if band.last().is_some_and(|q| !dry_between(q.0, p.0)) => band.push(*p), + _ => bands.push(vec![*p]), + } + } + bands + }); + for mut samples in bands { if samples.len() < 2 { continue; } @@ -2609,7 +2809,7 @@ mod tests { use rustgis_map::view::BlockWater; // #2317: the east side crosses a lake from y −300 to 300; another lake lies inside the box. let lakes: [(&[[f64; 4]], _); 2] = [(&[[500.0, -300.0, 1500.0, 300.0]], None), (&[[-500.0, -500.0, -200.0, -200.0]], None)]; - let (m, b, g, res) = block_over_lakes(&lakes, Some(BlockWater { depth: Some(10.0), field: None })); + let (m, b, g, res) = block_over_lakes(&lakes, Some(BlockWater { depth: Some(10.0), field: None, bed: None })); let w = water_runs(&m, &b, &g, res, 1.0, &Default::default()); assert!(w[0].is_empty() && w[2].is_empty() && w[3].is_empty(), "only the east side crosses water"); let [r] = &w[1][..] else { panic!("one stretch of water on the east side") }; @@ -2623,7 +2823,7 @@ mod tests { // Each lake its own depth from the field; one without a value has none, unless a depth is // given for those. let lakes: [(&[[f64; 4]], _); 2] = [(&[[500.0, -300.0, 1500.0, 300.0]], Some(4.0)), (&[[-300.0, 600.0, 300.0, 1500.0]], None)]; - let field = |depth| Some(BlockWater { depth, field: Some("prof".into()) }); + let field = |depth| Some(BlockWater { depth, field: Some("prof".into()), bed: None }); let (m, b, g, res) = block_over_lakes(&lakes, field(None)); let w = water_runs(&m, &b, &g, res, 1.0, &Default::default()); assert_eq!((w[1].len(), w[2].len()), (1, 0)); @@ -2642,7 +2842,7 @@ mod tests { // One row of two parts meeting on y 0 across the east side: a stretch each, each floor // shaped by its own part's shore. let halves: [[f64; 4]; 2] = [[500.0, -300.0, 1500.0, 0.0], [500.0, 0.0, 1500.0, 300.0]]; - let (mut m, b, g, res) = block_over_lakes(&[(&halves, None)], Some(BlockWater { depth: Some(10.0), field: None })); + let (mut m, b, g, res) = block_over_lakes(&[(&halves, None)], Some(BlockWater { depth: Some(10.0), field: None, bed: None })); let w = water_runs(&m, &b, &g, res, 1.0, &Default::default()); let [south, north] = &w[1][..] else { panic!("a stretch a part: {}", w[1].len()) }; assert!((south.hi - 0.0).abs() < 1e-6 && (north.lo - 0.0).abs() < 1e-6); @@ -2676,7 +2876,7 @@ mod tests { // The circle of radius 1000 crosses the lake (y −300 to 300 east of x 500) on the sides // round its east point, and nowhere else. let lakes: [(&[[f64; 4]], _); 1] = [(&[[500.0, -300.0, 1500.0, 300.0]], None)]; - let water = Some(BlockWater { depth: Some(10.0), field: None }); + let water = Some(BlockWater { depth: Some(10.0), field: None, bed: None }); let (m, b, g, res) = block_over_lakes_shaped(&lakes, water, BlockShape::Circle { radius: None }); let w = water_runs(&m, &b, &g, res, 1.0, &Default::default()); assert_eq!(w.len(), ROUND_SIDES); @@ -2747,7 +2947,7 @@ mod tests { // failed to draw left its wall only at x −1000 to −300 and 300 to 1000: water on each // piece, none in the gap between them. let lakes: [(&[[f64; 4]], _); 1] = [(&[[-800.0, -1500.0, 800.0, -500.0]], None)]; - let (m, b, g, res) = block_over_lakes(&lakes, Some(BlockWater { depth: Some(50.0), field: None })); + let (m, b, g, res) = block_over_lakes(&lakes, Some(BlockWater { depth: Some(50.0), field: None, bed: None })); let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; let view = View { width: 600.0, height: 500.0, pixels_per_point: 1.0, camera, sky: false }; @@ -2803,4 +3003,274 @@ mod tests { assert_eq!(pixel(&wet, x, 950.0).alpha(), 0, "{x}: {:?}", pixel(&wet, x, 950.0)); } } + + /// The lake across the south side of [`block_over_lakes`] from x −300 to 300, `water` in its + /// walls with its bed read from "batimetria": a Web Mercator raster of 20 m cells over the + /// DEM's ±5000 m, `bed(x, y)` metres at each cell's centre (NaN: no height). + fn lake_over_bed(depth: Option, bed: impl Fn(f64, f64) -> f32) -> (Map, Block, Ground, f64) { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_map::view::BlockWater; + let lakes: [(&[[f64; 4]], _); 1] = [(&[[-300.0, -1500.0, 300.0, -500.0]], None)]; + let water = BlockWater { depth, field: None, bed: Some("batimetria".into()) }; + let (mut m, b, g, res) = block_over_lakes(&lakes, Some(water)); + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let cells: Vec = + (0..500 * 500).map(|i| bed(-4990.0 + 20.0 * f64::from(i % 500), 4990.0 - 20.0 * f64::from(i / 500))).collect(); + let raster = Raster::new("batimetria", 500, 500, vec![cells], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + m.add_raster("batimetria", rustgis_map::RasterLayer::from_path(raster, "batimetria.tif")); + (m, b, g, res) + } + + /// The lake's bed of [`lake_over_bed`]: 40 m below the DEM's 500 m in the middle of the lake, + /// rising evenly to it at its shores (x ±300). + fn dipping(x: f64, _: f64) -> f32 { + (500.0 - 40.0 * (1.0 - x.abs() / 300.0).max(0.0)) as f32 + } + + /// The south wall of `b` as stretches 100 m long, seen as [`a_wall_in_pieces_keeps_its_water_to_each_piece`] + /// sees it, drawn with `water`, and where on screen `metres` (exaggerated) at `x` lands. + fn south_wall(m: &Map, b: &Block, g: &Ground, res: f64, water: &WaterRuns) -> (Pixmap, impl Fn(f64, f64) -> (u32, u32)) { + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; + let view = View { width: 600.0, height: 500.0, pixels_per_point: 1.0, camera, sky: false }; + let (w, h) = (view.width, view.height); + let raised = move |x: f64, up: f64| { + let (u, v) = camera.ground_px(Coord::new(x, -1000.0)); + camera.project_raised(u, v, up, w, h).expect("in view") + }; + let top = |x: f64| raised(x, g.up_px(Coord::new(x, -1000.0), &camera)); + let edges: Vec = (0..20) + .map(|i| { + let (x0, x1) = (-1000.0 + 100.0 * f64::from(i), -900.0 + 100.0 * f64::from(i)); + Edge { + side: u16::from(SOUTH), + ends: [Coord::new(x0, -1000.0), Coord::new(x1, -1000.0)], + top: [top(x0), top(x1)], + depth: 1.0, + } + }) + .collect(); + let mut pm = Pixmap::new(600, 500).unwrap(); + let runs = runs(m, b, 1.0, &Default::default()); + draw_walls(&mut pm, &view, g, b, &edges, &runs, water, Rgba::rgb(255, 255, 255), rustgis_map::camera::FAR, |_, _| true); + let per = g.per_unit(Coord::new(0.0, -1000.0)); + (pm, move |x: f64, metres: f64| { + let (px, py) = raised(x, metres / per / res); + (px as u32, py as u32) + }) + } + + /// Whether `c` is the water's colour `water` shaded, by its shares of red, green and blue. + fn is_water(c: tiny_skia::ColorU8, water: Rgba) -> bool { + let shares = |p: [u8; 3]| { + let sum = p.iter().map(|v| f64::from(*v)).sum::().max(1.0); + p.map(|v| f64::from(v) / sum) + }; + let (p, q) = (shares([c.red(), c.green(), c.blue()]), shares([water.r(), water.g(), water.b()])); + c.alpha() == 255 && p.iter().zip(q).map(|(a, b)| (a - b).abs()).sum::() < 0.05 + } + + #[test] + fn a_wall_across_a_lake_shows_its_floor_on_the_bed_raster() { + // #2434: a flat DEM at 500 m, its lake's bed 40 m deeper in its middle: along the south + // wall the floor lies at the bed's heights (doubled, as the level is), not the depth's + // basin, and the water reaches down to it. + let (m, b, g, res) = lake_over_bed(Some(5.0), dipping); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let [r] = &water[0][..] else { panic!("one stretch of water on the south side") }; + // The shading runs to its deepest sample, about 40 m (doubled) down. + assert!((r.level - 1000.0).abs() < 1e-6 && (r.depth - 80.0).abs() < 3.0, "{} {}", r.level, r.depth); + let key = b.side(0).0; + for x in [-150.0, 100.0, 200.0] { + let at = Coord::new(x, -1000.0); + let floor = r.floor_at(b.along(key, at), at).expect("water there"); + assert!((floor - 2.0 * f64::from(dipping(x, 0.0))).abs() < 1e-3, "{x}: {floor}"); + } + // Drawn: water 20 m (doubled) under the level in the middle and 12 m at x −100, where the + // depth's 5 m basin would show the wall; the wall just under the bed near the shore. + let (pm, at) = south_wall(&m, &b, &g, res, &water); + let (plain, _) = south_wall(&m, &b, &g, res, &(0..b.sides()).map(|_| Vec::new()).collect()); + let pixel = |pm: &Pixmap, x: f64, metres: f64| { + let (px, py) = at(x, metres); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + assert!(is_water(pixel(&pm, 0.0, 960.0), r.color), "{:?}", pixel(&pm, 0.0, 960.0)); + assert!(is_water(pixel(&pm, -100.0, 975.0), r.color), "{:?}", pixel(&pm, -100.0, 975.0)); + // (3.5 px under the floor's line, at 10 m a pixel.) + let under = 2.0 * f64::from(dipping(250.0, 0.0)) - 35.0; + let below = pixel(&pm, 250.0, under); + assert!(!is_water(below, r.color) && below == pixel(&plain, 250.0, under), "{below:?}"); + } + + #[test] + fn a_bed_covering_half_a_lake_falls_back_to_the_depth_on_the_other_half() { + // #2434: the bed has heights east of x 0 only: the east half's floor follows it, the west + // half's is the depth's basin with its shore ramp (4 px of 10 m), and one stretch without + // the bed is said. + let half = |x: f64, y: f64| if x > 0.0 { dipping(x, y) } else { f32::NAN }; + let (m, b, g, res) = lake_over_bed(Some(10.0), half); + let before = crate::approximations::keep(); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + let [r] = &water[0][..] else { panic!("one stretch of water on the south side") }; + let key = b.side(0).0; + let floor = |x: f64| { + let at = Coord::new(x, -1000.0); + r.floor_at(b.along(key, at), at) + }; + for x in [100.0, 200.0, 280.0] { + assert!((floor(x).unwrap() - 2.0 * f64::from(dipping(x, 0.0))).abs() < 1e-3, "{x}: {:?}", floor(x)); + } + for (x, f) in [(-290.0, 995.0), (-280.0, 990.0), (-150.0, 980.0)] { + assert!((floor(x).unwrap() - f).abs() < 1e-6, "{x}: {:?}", floor(x)); + } + // The shading runs to the deepest of them: the bed's deepest sample, a cell or so east of + // x 0 (its first with a height), over 30 m (doubled) down, deeper than the depth's 10 m. + assert!(r.depth > 60.0 && r.depth < 80.0, "{}", r.depth); + assert!(said.iter().any(|t| t.contains("batimetria") && t.contains("1 stretch") && t.contains("1 water body")), "{said:?}"); + // Without a depth, no water where the bed has none. + let (m, b, g, res) = lake_over_bed(None, half); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let [r] = &water[0][..] else { panic!("one stretch of water on the south side") }; + let at = Coord::new(-150.0, -1000.0); + assert_eq!(r.floor_at(b.along(key, at), at), None); + let at = Coord::new(150.0, -1000.0); + assert!(r.floor_at(b.along(key, at), at).is_some()); + } + + #[test] + fn the_floor_steps_to_the_depth_at_the_beds_last_sample_with_no_height() { + // #2434: a bed 300 m deep east of x 160 only, the depth 2.5 m elsewhere: the bed's samples + // (every 20 m from the shore at −300) have no height up to x 160 and one from x 180, the + // wall's samples (every 25 m) none between x 150 and 175. The floor up to x 160 is the + // depth's, so the wall shows just under the level at x 155, not water reaching down + // towards the bed's floor at x 175. + let deep = |x: f64, _: f64| if x > 160.0 { 300.0 } else { f32::NAN }; + let (m, b, g, res) = lake_over_bed(Some(2.5), deep); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let [r] = &water[0][..] else { panic!("one stretch of water on the south side") }; + let key = b.side(0).0; + let floor = |x: f64| { + let at = Coord::new(x, -1000.0); + r.floor_at(b.along(key, at), at) + }; + assert!((floor(160.0).unwrap() - 995.0).abs() < 1e-6 && (floor(180.0).unwrap() - 600.0).abs() < 1e-3); + let (pm, at) = south_wall(&m, &b, &g, res, &water); + let (plain, _) = south_wall(&m, &b, &g, res, &(0..b.sides()).map(|_| Vec::new()).collect()); + let pixel = |pm: &Pixmap, x: f64, metres: f64| { + let (px, py) = at(x, metres); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + assert!(is_water(pixel(&pm, 200.0, 950.0), r.color), "{:?}", pixel(&pm, 200.0, 950.0)); + let gap = pixel(&pm, 155.0, 950.0); + assert!(!is_water(gap, r.color) && gap == pixel(&plain, 160.0, 950.0), "{gap:?}"); + } + + #[test] + fn a_bed_above_the_level_holds_no_water() { + // #2434: a shoal rising to 520 m round x 100 in a lake at 500 m: no water over it, the + // water either side of it. + let shoal = |x: f64, _: f64| if (x - 100.0).abs() < 50.0 { 520.0 } else { 470.0 }; + let (m, b, g, res) = lake_over_bed(Some(10.0), shoal); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let [r] = &water[0][..] else { panic!("one stretch of water on the south side") }; + let key = b.side(0).0; + let floor = |x: f64| { + let at = Coord::new(x, -1000.0); + r.floor_at(b.along(key, at), at) + }; + assert_eq!(floor(100.0), None); + assert!((floor(-100.0).unwrap() - 940.0).abs() < 1e-3 && (floor(250.0).unwrap() - 940.0).abs() < 1e-3); + let (pm, at) = south_wall(&m, &b, &g, res, &water); + let (plain, _) = south_wall(&m, &b, &g, res, &(0..b.sides()).map(|_| Vec::new()).collect()); + let pixel = |pm: &Pixmap, x: f64, metres: f64| { + let (px, py) = at(x, metres); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + assert_eq!(pixel(&pm, 100.0, 990.0), pixel(&plain, 100.0, 990.0), "the wall over the shoal"); + assert!(!is_water(pixel(&pm, 100.0, 990.0), r.color)); + for x in [-100.0, 250.0] { + assert!(is_water(pixel(&pm, x, 970.0), r.color), "{x}: {:?}", pixel(&pm, x, 970.0)); + } + } + + #[test] + fn a_bed_with_no_heights_draws_the_walls_as_without_one() { + // #2434: no bed, a bed layer that isn't there, and a bed with no heights over the lake + // draw the wall's water alike, pixel for pixel: the depth's basin of #2317. + let frame = |bed: Option<&str>, heights: fn(f64, f64) -> f32| { + let (mut m, b, g, res) = lake_over_bed(Some(50.0), heights); + if let Some(w) = m.view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.water.as_mut()) { + w.bed = bed.map(str::to_string); + } + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + south_wall(&m, &b, &g, res, &water).0 + }; + let plain = frame(None, dipping); + assert!(plain.pixels().iter().any(|p| p.alpha() > 0)); + assert!(frame(Some("nenhuma"), dipping).data() == plain.data(), "a bed layer that isn't there"); + assert!(frame(Some("batimetria"), |_, _| f32::NAN).data() == plain.data(), "a bed with no heights"); + assert!(frame(Some("batimetria"), dipping).data() != plain.data(), "a bed with heights"); + } + + #[test] + fn a_bed_named_by_a_layer_that_isnt_a_raster_is_said() { + // #2434: the bed's raster gone and a polygon layer given its name (a rename, or one added): + // the walls show the depth's basin as without a bed, and the frame says why. + let (mut m, b, g, res) = lake_over_bed(Some(50.0), dipping); + m.layers.retain(|l| l.name != "batimetria"); + m.add_dataset(rustgis_data::Dataset::new("batimetria", rustgis_data::GeometryType::Polygon, Vec::new())); + let before = crate::approximations::keep(); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + assert!(!water[0].is_empty(), "the depth's water"); + assert!(said.iter().any(|t| t.contains("batimetria") && t.contains("isn't a raster layer")), "{said:?}"); + } + + #[test] + fn a_bed_still_being_read_draws_the_walls_as_without_one() { + // #2434: a bed layer whose data hasn't come yet gives the depth's basin, as no bed does, + // and says nothing (its frame is drawn again when the data lands). + let (mut m, b, g, res) = lake_over_bed(Some(50.0), dipping); + let plain = { + let mut m = m.clone(); + if let Some(w) = m.view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.water.as_mut()) { + w.bed = None; + } + south_wall(&m, &b, &g, res, &water_runs(&m, &b, &g, res, 1.0, &Default::default())).0 + }; + if let Some(r) = m.layers.iter_mut().find(|l| l.name == "batimetria").and_then(|l| l.raster.as_mut()) { + r.data = None; + } + let before = crate::approximations::keep(); + let water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + assert!(said.is_empty(), "{said:?}"); + assert!(south_wall(&m, &b, &g, res, &water).0.data() == plain.data()); + } + + #[test] + fn a_bed_without_heights_between_two_mesh_steps_breaks_the_water() { + // #2434: with no depth to fall back on, the bed's one sample without a height lies between + // two of the mesh's steps (every 25 m along the 100 m stretches), whose nearer samples have + // heights: the water still stops there. + let (m, b, g, res) = lake_over_bed(None, dipping); + let mut water = water_runs(&m, &b, &g, res, 1.0, &Default::default()); + let key = b.side(0).0; + let along = |x: f64| b.along(key, Coord::new(x, -1000.0)); + let [r] = &mut water[0][..] else { panic!("one stretch of water on the south side") }; + r.bed = (-15..=15).map(|k| f64::from(k) * 20.0 - 10.0).map(|x| (along(x), (x != 10.0).then_some(940.0))).collect(); + r.bed.sort_by(|p, q| p.0.total_cmp(&q.0)); + let floor = |x: f64| r.floor_at(along(x), Coord::new(x, -1000.0)); + assert_eq!((floor(0.0), floor(10.0), floor(25.0)), (Some(940.0), None, Some(940.0))); + let color = r.color; + let (pm, at) = south_wall(&m, &b, &g, res, &water); + let (px, py) = at(10.0, 970.0); + let c = pm.pixel(px, py).expect("in the picture").demultiply(); + assert!(!is_water(c, color), "{c:?}"); + let (px, py) = at(-100.0, 970.0); + assert!(is_water(pm.pixel(px, py).expect("in the picture").demultiply(), color)); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d082a8c9de..c0598c7610 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13149,7 +13149,7 @@ mod tests { m.view.terrain = Some(rustgis_map::view::Terrain { source: rustgis_map::view::TerrainSource::Layer("dem".into()), exaggeration: 1.0, - block: Some(block(Some(rustgis_map::view::BlockWater { depth: Some(300.0), field: None }))), + block: Some(block(Some(rustgis_map::view::BlockWater { depth: Some(300.0), field: None, bed: None }))), water: Some(rustgis_map::view::TerrainWater { layer: "lagos".into(), level: None, glint: 0.0, shore: 0.35 }), }); let frame = render(&mut m, &view).expect("a frame"); diff --git a/docs/maintaining.md b/docs/maintaining.md index d4c03b4e49..2e9f3b686c 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -113,6 +113,7 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `terrain-water`, `terrain-water-shore` (a terrain water's shore band other than the default), `terrain-block-water` (water in a block diagram's walls), +`terrain-block-water-bed` (that water's floor read from a bed raster), `terrain-block-walls-layer` (the layer a block diagram's walls are coloured by), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light), diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index a472d9c6cf..b384e3e51e 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -202,6 +202,30 @@ block takes the water out of the walls (the rest of the block stays as it was); it a layer without the depth field, is refused. Deleting the depth field keeps the water's own `depth` for all the water, or takes the water out of the walls when there is none, and says so. +When the bed is measured, `"bed": "Bathymetry"` in the block's water names a raster layer of the +bed's heights (metres on the DEM's vertical datum, stretched by the exaggeration as the level is; +a topo-bathymetric DEM can be named as its own bed, and a raster of depths turns into heights with +the raster calculator, `level − depth`). Along each wall's water the floor is then the bed's height, +read at steps of the bed's cell at the block's centre, longer where that would take more than +16 384 heights along all the walls' water (read once and kept until the layer, its data or the box +change), with +no shore ramp, as the bed reaches the shore itself; where the bed lies above the level there is +no water. Where the bed has no data (off the raster, its no-data cells) the floor is the field's +depth or the `"depth"`, with the ramp, as without a bed, and no water without either; one notice +says along how many stretches and in how many water bodies. The bed alone is enough, without a +depth or field. The water's shading runs from the level to the deepest point of each stretch. +`map.terrain` refuses a bed that isn't a raster layer, or a name more than one layer has, before +the terrain changes, and so a new box for the block that moves it off the bed it keeps. The bed's +footprint is checked against the block's box when its data is there as the command runs; a bed +still being read gives no floor until it is, and one whose data lands later off the box is kept, +the frame then saying it has no heights along the walls' water. The bed is kept by name and +follows its renames; removing it says the walls fall back to the depth or field meanwhile, and so +does a project that opens without it, and a layer of its name that isn't a raster (renamed or +added to it) is said by the frame. A bed deeper +than the block's base is drawn at the base: give the block a larger `"depth"`. Only the walls show +the bed: the ground over the water stays flat at its level. Saved projects require +`terrain-block-water-bed`. + **Water** on the terrain lies flat: `map.terrain` with `{"water": {"layer": "Lakes"}}` names a polygon layer of water bodies, and inside each polygon the ground is level, at the lowest height of the DEM along its shore, instead of rising and falling with a surface model that is noisy or diff --git a/schema/fixtures/terrain_block_water_bed_v2.rgis b/schema/fixtures/terrain_block_water_bed_v2.rgis new file mode 100644 index 0000000000..3a8a73bdd9 --- /dev/null +++ b/schema/fixtures/terrain_block_water_bed_v2.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Terrain block water bed","maps":[{"name":"Map","layers":[],"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,"bed":"batimetria"}},"water":{"layer":"lagos","level":"nivel"}}},"animation":[],"next_layer_id":1}],"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","terrain-block-water-bed"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 987e8deb7f..e7bc28bba7 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1242,6 +1242,7 @@ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-water-bed", "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls", @@ -1359,6 +1360,7 @@ "terrain-water", "terrain-water-shore", "terrain-block-water", + "terrain-block-water-bed", "terrain-block-walls-layer", "shaded-relief-effects", "normalized-legend-urls",