diff --git a/crates/engine/src/cmd/terrain_blocks.rs b/crates/engine/src/cmd/terrain_blocks.rs index 84338b774..ef0b3a663 100644 --- a/crates/engine/src/cmd/terrain_blocks.rs +++ b/crates/engine/src/cmd/terrain_blocks.rs @@ -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(); diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index c565e1b5b..d9d70917e 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)}, 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() @@ -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) -> Result { - 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)")); } let extent = match b.get("extent") { None | Some(Value::Null) => None, @@ -346,7 +346,28 @@ fn terrain_block(s: &Session, b: &serde_json::Map) -> Result (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) } @@ -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). @@ -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); @@ -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() }; + 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, @@ -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; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 1c4ce1a61..483afaaf7 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -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", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 7ce39dd3a..fc1983b3d 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -260,14 +260,16 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { } fn map_capabilities<'a>(maps: impl IntoIterator) -> 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); @@ -281,6 +283,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> 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"), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 20412f21e..04f9a8789 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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, }); @@ -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, }); @@ -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, }); @@ -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, }); @@ -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, @@ -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 = 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; diff --git a/crates/map/src/view.rs b/crates/map/src/view.rs index 3fda0de3d..d76d11598 100644 --- a/crates/map/src/view.rs +++ b/crates/map/src/view.rs @@ -225,6 +225,24 @@ pub struct TerrainBlock { /// straight down (schematic: no dip or thickness). None: the walls are `walls` all along. #[serde(default, skip_serializing_if = "Option::is_none")] pub walls_layer: Option, + /// The terrain's water in the walls' section (#2317): where the box's edge runs inside a + /// water polygon, a band of water from its level down to its floor. None: the walls rise to + /// the water's level as ground. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub water: Option, +} + +/// 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. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct BlockWater { + /// Metres from the level down to the floor, before exaggeration: every water body's, or + /// those with no value of `field`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub depth: Option, + /// 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, } /// The least depth (metres, before exaggeration) of a block diagram's base below its lowest @@ -269,6 +287,16 @@ impl TerrainBlock { if self.walls.a() != 255 { 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 let Some(d) = w.depth + && !(d.is_finite() && (0.0..=BLOCK_MAX_DEPTH).contains(&d)) + { + return Err(format!("block's water depth is metres, 0 to {BLOCK_MAX_DEPTH:.0}")); + } + } Ok(()) } } diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 400617b0a..e83bd1421 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -145,27 +145,68 @@ pub(crate) type Runs = [Vec; 4]; /// under no polygon), in [`SIDES`]' order. type Units = [Vec<(f64, f64, Option)>; 4]; -/// The rows, layer, query, query context and box a [`Units`] was read for. +/// A polygon reaching a block's box, each part of a multipolygon on its own: its row, its rings +/// (Web Mercator) and their box. +type Part = (usize, Vec>, Extent); + +/// A layer's [`Units`] along a block's box, and for the water (#2317) the polygons reaching the +/// box, whose shores shape the water's floor. +struct Cut { + units: Units, + parts: Vec, +} + +/// The rows, layer, query, query context and box a [`Cut`] was read for, and whether for the water. struct Key { rows: Weak>, layer: String, query: Option, page: Option>, sides: [f64; 4], + water: bool, } impl Key { fn same(&self, o: &Key) -> bool { - self.rows.ptr_eq(&o.rows) && self.layer == o.layer && self.query == o.query && self.page == o.page && self.sides == o.sides + self.rows.ptr_eq(&o.rows) + && self.layer == o.layer + && self.query == o.query + && self.page == o.page + && self.sides == o.sides + && self.water == o.water } } -/// The units read last, kept while their layer's rows and query and the box stay the same: a +/// The cuts read last, kept while their layer's rows and query and the box stay the same: a /// view drawn as the map moves crosses no polygon with the box again. Up to [`KEPT`]. -static LAST: Mutex)>> = Mutex::new(Vec::new()); -/// How many units [`LAST`] keeps (maps drawn side by side, a layout's frames). +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 box, from [`LAST`] when it was read already. +fn cut(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_data::query::Env) -> Arc { + let key = Key { + rows: layer.dataset.features.allocation_key(), + layer: layer.name.clone(), + query: layer.definition_query.clone(), + page: env.page.as_ref().filter(|_| layer.definition_query.as_deref().is_some_and(rustgis_data::query::reads_series_page)).cloned(), + sides: [b.x0, b.y0, b.x1, b.y1], + water, + }; + 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)); + if let Ok(mut last) = LAST.lock() { + last.retain(|(k, _)| k.rows.strong_count() > 0 && !k.same(&key)); + if last.len() >= KEPT { + last.remove(0); + } + last.push((key, u.clone())); + } + u + }) +} + /// The colours along the walls of block `b` on `map`. With a walls layer /// (`TerrainBlock::walls_layer`, as [`crate::terrain::walls_layer`] takes it): the colour its /// symbology gives the polygon under each stretch of the box's edge (the topmost where polygons @@ -193,25 +234,7 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: .and_then(|t| t.walls_layer.as_deref()) .and_then(|n| crate::terrain::walls_layer(map, n)); let Some(layer) = layer else { return [0, 1, 2, 3].map(whole) }; - let key = Key { - rows: layer.dataset.features.allocation_key(), - layer: layer.name.clone(), - query: layer.definition_query.clone(), - page: env.page.as_ref().filter(|_| layer.definition_query.as_deref().is_some_and(rustgis_data::query::reads_series_page)).cloned(), - sides: [b.x0, b.y0, b.x1, b.y1], - }; - let kept = LAST.lock().ok().and_then(|last| last.iter().find(|(k, _)| k.same(&key)).map(|(_, u)| u.clone())); - let units = kept.unwrap_or_else(|| { - let u = Arc::new(units(layer, b, env)); - if let Ok(mut last) = LAST.lock() { - last.retain(|(k, _)| k.rows.strong_count() > 0 && !k.same(&key)); - if last.len() >= KEPT { - last.remove(0); - } - last.push((key, u.clone())); - } - u - }); + let cut = cut(layer, b, false, env); let styler = layer.styler_with(env.clone()); let grow = layer.size_factor(scale); let look = |row: Option| match row { @@ -227,7 +250,7 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: }; [0, 1, 2, 3].map(|i| { let mut out: Vec = Vec::new(); - for &(lo, hi, row) in &units[i] { + for &(lo, hi, row) in &cut.units[i] { let (color, patterns) = look(row); match out.last_mut() { Some(last) if last.color == color && last.patterns == patterns => last.hi = hi, @@ -275,16 +298,42 @@ fn grown(pattern: FillPattern, k: f32) -> FillPattern { } } +/// A side of block `b`'s box as a line: across it at the first number, along it from the second +/// to the third ([`along`]). +fn side_line(b: &Block, side: u8) -> (f64, f64, f64) { + match side { + SOUTH => (b.y0, b.x0, b.x1), + NORTH => (b.y1, b.x0, b.x1), + EAST => (b.x1, b.y0, b.y1), + _ => (b.x0, b.y0, b.y1), + } +} + +/// Where a point lies across a side of the box: its y across the south and north sides, its x +/// across the east and west. +fn across(side: u8, m: Coord) -> f64 { + if side & (SOUTH | NORTH) != 0 { m.y } else { m.x } +} + +/// The point `t` along a side of block `b`'s box. +fn side_point(b: &Block, side: u8, t: f64) -> Coord { + let at = side_line(b, side).0; + if side & (SOUTH | NORTH) != 0 { Coord::new(t, at) } else { Coord::new(at, t) } +} + /// Each side of block `b`'s box cut where `layer`'s polygons cross it, with the row of the -/// topmost polygon over each piece, found at its middle: the contacts go straight down. -fn units(layer: &rustgis_map::Layer, b: &Block, env: &rustgis_data::query::Env) -> Units { +/// topmost polygon over each piece, found at its middle: the contacts go straight down. For the +/// water (`water`), the first polygon in row order instead, as the ground's level takes it, given +/// as its place in the polygons reaching the box (each part of a multipolygon on its own), which +/// are kept. +fn units(layer: &rustgis_map::Layer, b: &Block, water: bool, env: &rustgis_data::query::Env) -> Cut { let keep = layer.query_rows_with(&layer.dataset, env); // The box in longitude and latitude (Web Mercator keeps north-up boxes north-up), so a part // off it is left before its rings are put in Web Mercator. let (lo, hi) = (merc_to_lonlat(Coord::new(b.x0, b.y0)), merc_to_lonlat(Coord::new(b.x1, b.y1))); // The polygons reaching the box (Web Mercator rings, and their box), each part on its own, in // row order. - let mut parts: Vec<(usize, Vec>, Extent)> = Vec::new(); + let mut parts: Vec = Vec::new(); for (row, ft) in layer.dataset.features.iter().enumerate() { if keep.as_ref().is_some_and(|k| !k.get(row).copied().unwrap_or(false)) { continue; @@ -302,22 +351,14 @@ fn units(layer: &rustgis_map::Layer, b: &Block, env: &rustgis_data::query::Env) parts.push((row, rings, e)); } } - [0, 1, 2, 3].map(|i| { + let units = [0, 1, 2, 3].map(|i| { let side = SIDES[i]; - // The side as a line: across it at `at`, along it from `lo` to `hi`. - let (at, lo, hi) = match side { - SOUTH => (b.y0, b.x0, b.x1), - NORTH => (b.y1, b.x0, b.x1), - EAST => (b.x1, b.y0, b.y1), - _ => (b.x0, b.y0, b.y1), - }; - let across = |c: Coord| if side & (SOUTH | NORTH) != 0 { c.y } else { c.x }; - let point = |t: f64| if side & (SOUTH | NORTH) != 0 { Coord::new(t, at) } else { Coord::new(at, t) }; + let (at, lo, hi) = side_line(b, side); let mut cuts = vec![lo, hi]; for r in parts.iter().flat_map(|(_, rings, _)| rings) { for (j, a) in r.iter().enumerate() { let Some(&q) = r.get((j + 1) % r.len()) else { continue }; - let (da, dq) = (across(*a) - at, across(q) - at); + let (da, dq) = (across(side, *a) - at, across(side, q) - at); if (da > 0.0) != (dq > 0.0) { let t = along(side, *a) + da / (da - dq) * (along(side, q) - along(side, *a)); if t > lo && t < hi { @@ -330,15 +371,109 @@ fn units(layer: &rustgis_map::Layer, b: &Block, env: &rustgis_data::query::Env) cuts.dedup(); let mut out: Vec<(f64, f64, Option)> = Vec::new(); for w in cuts.windows(2) { - let mid = point((w[0] + w[1]) / 2.0); - let row = parts.iter().rev().find(|(_, rings, e)| e.contains(mid) && inside(rings, mid)).map(|(row, _, _)| *row); + let mid = side_point(b, side, (w[0] + w[1]) / 2.0); + let over = |p: &Part| p.2.contains(mid) && inside(&p.1, mid); + // The water's pieces keep their part, so each part's shore shapes its own floor. + let row = if water { parts.iter().position(over) } else { parts.iter().rev().find(|p| over(p)).map(|p| p.0) }; match out.last_mut() { Some(last) if last.2 == row => last.1 = w[1], _ => out.push((w[0], w[1], row)), } } out - }) + }); + Cut { units, parts: if water { parts } else { Vec::new() } } +} + +/// A stretch of one side of the box inside a water body (#2317): from `lo` to `hi` along it +/// ([`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. +pub(crate) struct WaterRun { + pub lo: f64, + pub hi: f64, + pub color: Rgba, + pub level: f64, + pub depth: f64, + 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. + 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 + } +} + +/// How far `p` lies from the segment from `a` to `q`. +fn segment_distance(p: Coord, a: Coord, q: Coord) -> f64 { + let (dx, dy) = (q.x - a.x, q.y - a.y); + let l2 = dx * dx + dy * dy; + let t = if l2 > 0.0 { (((p.x - a.x) * dx + (p.y - a.y) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 }; + (p.x - a.x - t * dx).hypot(p.y - a.y - t * dy) +} + +/// The water along each side of a block's box, in [`SIDES`]' order. +pub(crate) type WaterRuns = [Vec; 4]; + +/// The colour a water body's section takes where its symbol has no solid fill. +const SECTION_WATER: Rgba = Rgba::rgb(0x8F, 0xB8, 0xDE); + +/// The water block `b`'s walls cut through on `map` (#2317), when its block has `water` and its +/// terrain a water layer ([`crate::terrain::walls_layer`]'s checks): each stretch of the box's +/// edge inside one of its polygons (the first in row order, among those its definition query +/// 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. Runs on the thread drawing the frame; the stretches are +/// kept as the walls' units are ([`cut`]). Each frame looks at every edge of the rings of each +/// water body a stretch lies in once, a few comparisons an edge, to keep those within the ramp +/// (the ramp follows the view's scale, so they can't be kept with the stretches). +pub(crate) fn water_runs(map: &Map, b: &Block, ground: &Ground, res: f64, env: &rustgis_data::query::Env) -> WaterRuns { + let mut out: WaterRuns = Default::default(); + let Some(t) = map.view.terrain.as_ref() else { return out }; + let (Some(bw), Some(tw), Some(water)) = (t.block.as_ref().and_then(|b| b.water.as_ref()), t.water.as_ref(), ground.water()) else { + return out; + }; + let Some(layer) = crate::terrain::walls_layer(map, &tw.layer) else { return out }; + let field = bw.field.as_deref().and_then(|f| layer.dataset.field_index(f)); + let cut = cut(layer, b, true, env); + let styler = layer.styler_with(env.clone()); + let x = ground.exaggeration(); + let ramp = f64::from(crate::terrain::SHORE_PX) * res; + for (i, side) in SIDES.into_iter().enumerate() { + let at = side_line(b, side).0; + for &(lo, hi, part) in &cut.units[i] { + let Some((row, rings, _)) = part.and_then(|p| cut.parts.get(p)) else { continue }; + let row = *row; + let given = field.and_then(|f| layer.dataset.features.get(row)?.attrs.get(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 mid = side_point(b, side, (lo + hi) / 2.0); + let Some(level) = water.level(mid) else { 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); + let color = unit_paint(sym.fill, fills, SECTION_WATER).0; + // The shore's edges that can lie within the ramp of the stretch. + let shore = rings + .iter() + .flat_map(|r| r.iter().zip(r.iter().cycle().skip(1)).map(|(a, q)| (*a, *q))) + .filter(|&(a, q)| { + let (da, dq) = (across(side, a) - at, across(side, q) - at); + let (sa, sq) = (along(side, a), along(side, q)); + (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); + out[i].push(WaterRun { lo, hi, color, level, depth, ramp, shore, dark: tw.shore }); + } + } + out } /// Whether `p` lies inside a polygon's `rings`, even-odd, so its holes are outside. @@ -529,8 +664,20 @@ fn draw_patterns( /// over them ([`draw_patterns`]), lit by the way its side faces the light as extruded walls are /// and darker toward its foot, fogged with distance as the ground is (into `fog` toward the view's /// reach `far`), and outlined along the ground, the base, the box's corners and the contacts -/// between colours. -pub(crate) fn draw_walls(pm: &mut Pixmap, view: &View, ground: &Ground, b: &Block, edges: &[Edge], runs: &Runs, fog: Rgba, far: f64) { +/// between colours. The water the box's edge runs through (`water`, [`water_runs`]) is drawn +/// over them from its level down to its floor, in its colour lit as the side is and darker toward +/// the full depth (half as bright there), with a line at the level and one along the floor. +pub(crate) fn draw_walls( + pm: &mut Pixmap, + view: &View, + ground: &Ground, + b: &Block, + edges: &[Edge], + runs: &Runs, + water: &WaterRuns, + fog: Rgba, + far: f64, +) { let fog_at = |depth: f64| crate::fog_share(depth, far); let k = f64::from(pm.width()) / view.width.max(1e-9); let cam = view.camera; @@ -712,9 +859,97 @@ pub(crate) fn draw_walls(pm: &mut Pixmap, view: &View, ground: &Ground, b: &Bloc let stroke = Stroke { width: (0.7 * k) as f32, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Stroke::default() }; pm.stroke_path(&path, &paint(edge, 1.0), &stroke, Transform::identity(), None); } + // 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. + for wr in &water[s] { + // 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. + type Sample = (f64, (f64, f64), (f64, f64), (f64, f64)); + let mut samples: Vec = Vec::new(); + for (ends, _, [ta, tz]) in &quads { + let (ca, cz) = (along(side, ends[0]), along(side, ends[1])); + let span = cz - ca; + if span.abs() < 1e-12 { + continue; + } + 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 m = Coord::new(ends[0].x + (ends[1].x - ends[0].x) * t, ends[0].y + (ends[1].y - ends[0].y) * t); + 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)) { + // 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((along(side, m), 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); + if samples.len() < 2 { + continue; + } + let (mut band, mut level, mut floor) = (PathBuilder::new(), PathBuilder::new(), PathBuilder::new()); + for (i, (_, top, bed, _)) in samples.iter().enumerate() { + let (top, bed) = (pt(*top), pt(*bed)); + if i == 0 { + band.move_to(top.0, top.1); + level.move_to(top.0, top.1); + floor.move_to(bed.0, bed.1); + } else { + band.line_to(top.0, top.1); + level.line_to(top.0, top.1); + floor.line_to(bed.0, bed.1); + } + } + for (_, _, bed, _) in samples.iter().rev() { + band.line_to(pt(*bed).0, pt(*bed).1); + } + band.close(); + let n = samples.len() as f64; + let mean = |pick: fn(&Sample) -> (f64, f64)| { + let s = samples.iter().map(pick).fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1)); + Point::from_xy((s.0 / n) as f32, (s.1 / n) as f32) + }; + let (top, deep) = (wr.color.shade(top_shade).lerp(fog, f), wr.color.shade(top_shade * 0.5).lerp(fog, f)); + let shader = tiny_skia::LinearGradient::new( + mean(|p| p.1), + mean(|p| p.3), + vec![GradientStop::new(0.0, color(top)), GradientStop::new(1.0, color(deep))], + SpreadMode::Pad, + Transform::identity(), + ); + let paint_water = match shader { + Some(shader) => Paint { shader, anti_alias: true, ..Paint::default() }, + None => paint(top, 1.0), + }; + if let Some(path) = band.finish() { + pm.fill_path(&path, &paint_water, FillRule::Winding, Transform::identity(), None); + } + // A line at the level, and one along the floor as dark as the shore band at its outline. + let stroke = Stroke { width: k as f32, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Stroke::default() }; + let bed = Rgba::rgb(0, 0, 0).lerp(fog, f).with_alpha((wr.dark.clamp(0.0, 1.0) * 255.0).round() as u8); + for (line, c) in [(floor, bed), (level, wr.color.shade(0.6).lerp(fog, f))] { + if let Some(path) = line.finish().filter(|_| c.a() > 0) { + pm.stroke_path(&path, &paint(c, 1.0), &stroke, Transform::identity(), None); + } + } + } } } +/// The points each stretch of wall is cut into for the water's floor (#2317): enough for the +/// ramp at the shore, which spans a few pixels, inside a stretch of the settled mesh. +const WATER_STEPS: u32 = 4; + #[cfg(test)] mod tests { use super::*; @@ -810,6 +1045,7 @@ mod tests { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: Some("geo".into()), + water: None, }), water: None, }); @@ -822,7 +1058,7 @@ mod tests { fn walls_take_the_unit_under_the_boxs_edge_with_contacts_straight_down() { let (mut m, b) = walls_by_units(); let cuts = |m: &Map| { - let u = units(m.layer_by_name("geo").unwrap(), &b, &Default::default()); + let u = units(m.layer_by_name("geo").unwrap(), &b, false, &Default::default()).units; u.map(|side| side.iter().map(|&(lo, hi, row)| (lo.round(), hi.round(), row)).collect::>()) }; let [south, east, north, west] = cuts(&m); @@ -963,4 +1199,96 @@ mod tests { let bare = FillLayer { color: Some(blue), pattern: FillPattern::Hatch { angle: 0.0, spacing: 4.0, width: 0.0, offset: 0.0 } }; assert_eq!(unit_paint(red, &[bare], walls), (walls, Vec::new())); } + + /// A flat DEM at 500 m round (0, 0), exaggerated twice, cut to the box ±1000 m with `water` + /// in its walls, and a water layer of `lakes` (Web Mercator boxes, each with its value of the + /// depth field "prof" or none), seen at 10 m a pixel. + fn block_over_lakes(lakes: &[(&[[f64; 4]], Option)], water: Option) -> (Map, Block, Ground, f64) { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let dem = + Raster::new("dem", 500, 500, vec![vec![500.0; 500 * 500]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut m = Map::new("Map"); + m.add_raster("dem", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + let deg = |x: f64, y: f64| merc_to_lonlat(Coord::new(x, y)); + let mut d = Dataset::new("lagos", GeometryType::Polygon, vec![Field::new("prof", FieldType::Double)]); + for &(parts, prof) in lakes { + let ring = |[x0, y0, x1, y1]: [f64; 4]| vec![vec![deg(x0, y0), deg(x1, y0), deg(x1, y1), deg(x0, y1), deg(x0, y0)]]; + let polygon = Geometry::Polygon(parts.iter().map(|p| ring(*p)).collect()); + d.push(Some(polygon), vec![prof.map_or(Value::Null, Value::Float)]); + } + m.add_dataset(d); + m.view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 2.0, + block: Some(rustgis_map::view::TerrainBlock { + extent: Some([-1000.0, -1000.0, 1000.0, 1000.0]), + depth: None, + walls: rustgis_map::view::BLOCK_WALLS, + walls_layer: None, + water, + }), + water: Some(rustgis_map::view::TerrainWater { layer: "lagos".into(), level: None, glint: 0.0, shore: 0.35 }), + }); + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res: 10.0, bearing: 0.0, pitch: 60.0 }; + let g = Ground::of(&m, &camera).unwrap(); + let b = g.block(&m).unwrap(); + (m, b, g, camera.res) + } + + #[test] + fn a_wall_across_a_lake_shows_its_water_down_to_a_basins_floor() { + 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 w = water_runs(&m, &b, &g, res, &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") }; + assert!((r.lo + 300.0).abs() < 1e-6 && (r.hi - 300.0).abs() < 1e-6, "{} {}", r.lo, r.hi); + // At the shore's level, 10 m deep, both doubled. + assert!((r.level - 1000.0).abs() < 1e-6 && (r.depth - 20.0).abs() < 1e-6, "{} {}", r.level, r.depth); + // None at the shore, the full depth a shore band (4 px of 10 m) in from it, half halfway. + for (y, floor) in [(300.0, 1000.0), (280.0, 990.0), (260.0, 980.0), (0.0, 980.0), (-290.0, 995.0)] { + assert!((r.floor(Coord::new(1000.0, y)) - floor).abs() < 1e-6, "{y}: {}", r.floor(Coord::new(1000.0, y))); + } + // 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 (m, b, g, res) = block_over_lakes(&lakes, field(None)); + let w = water_runs(&m, &b, &g, res, &Default::default()); + assert_eq!((w[1].len(), w[2].len()), (1, 0)); + assert!((w[1][0].depth - 8.0).abs() < 1e-6); + let (m, b, g, res) = block_over_lakes(&lakes, field(Some(10.0))); + let w = water_runs(&m, &b, &g, res, &Default::default()); + assert!((w[1][0].depth - 8.0).abs() < 1e-6 && (w[2][0].depth - 20.0).abs() < 1e-6); + // No water in the block: none in the walls. + let (m, b, g, res) = block_over_lakes(&lakes, None); + assert!(water_runs(&m, &b, &g, res, &Default::default()).iter().all(Vec::is_empty)); + } + + #[test] + fn each_part_of_a_lake_shapes_its_own_floor_in_its_own_colour() { + use rustgis_map::fills::FillLayer; + use rustgis_map::view::BlockWater; + // 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 w = water_runs(&m, &b, &g, res, &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); + for (run, y, floor) in [(south, -290.0, 995.0), (south, -150.0, 980.0), (north, 290.0, 995.0), (north, 150.0, 980.0)] { + assert!((run.floor(Coord::new(1000.0, y)) - floor).abs() < 1e-6, "{y}: {}", run.floor(Coord::new(1000.0, y))); + } + // The section takes the topmost solid fill of the layer's stack, opaque. + let blue = Rgba::rgb(20, 60, 200); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "lagos") { + l.fill_layers = + vec![FillLayer { color: None, pattern: FillPattern::Solid }, FillLayer { color: Some(blue), pattern: FillPattern::Solid }]; + } + assert!(water_runs(&m, &b, &g, res, &Default::default())[1].iter().all(|r| r.color == blue)); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1bb74fad3..836659332 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2861,7 +2861,8 @@ fn drape_terrain( // each tile (the frame is drawn again when they arrive, `Ground::pending`). if let Some(b) = block.as_ref().filter(|b| b.walls_stand(ground)) { let scale = map.ground_res_at(&view.camera) / rustgis_geom::PIXEL_M; - block::draw_walls(pm, view, ground, b, &edges, &block::runs(map, b, scale, env), fog, far); + let water = block::water_runs(map, b, ground, cam.res, env); + block::draw_walls(pm, view, ground, b, &edges, &block::runs(map, b, scale, env), &water, fog, far); } true } @@ -9917,6 +9918,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + water: None, }; let terrain = |block: Option| { Some(rustgis_map::view::Terrain { @@ -9994,6 +9996,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: Some("geo".into()), + water: None, }), water: None, }); @@ -10044,6 +10047,68 @@ mod tests { assert_eq!(striped(&column(500.0)).0, 0, "east"); } + #[test] + fn a_block_diagrams_wall_shows_the_water_its_edge_cuts() { + // #2317: the near wall of a 2 km box, seen from the south, crosses a blue lake over its + // east half, 300 m deep: blue from the lake's level down to its floor there, the walls' + // sandy brown below the floor and beside the lake. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Geometry, GeometryType}; + let camera = Camera { center: Coord::new(0.0, 0.0), res: 20.0, bearing: 0.0, pitch: 60.0 }; + let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let dem = + Raster::new("dem", 500, 500, vec![vec![500.0; 500 * 500]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.add_raster("dem", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + let deg = |x: f64, y: f64| rustgis_geom::merc_to_lonlat(Coord::new(x, y)); + let lake = vec![deg(0.0, -3000.0), deg(3000.0, -3000.0), deg(3000.0, 0.0), deg(0.0, 0.0), deg(0.0, -3000.0)]; + let mut d = Dataset::new("lagos", GeometryType::Polygon, Vec::new()); + d.push(Some(Geometry::Polygon(vec![vec![lake]])), Vec::new()); + m.add_dataset(d); + let blue = Rgba::rgb(40, 90, 220); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "lagos") { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { + fill: blue, + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }); + } + let block = |water| rustgis_map::view::TerrainBlock { + extent: Some([-1000.0, -1000.0, 1000.0, 1000.0]), + depth: Some(1000.0), + walls: rustgis_map::view::BLOCK_WALLS, + walls_layer: None, + water, + }; + 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 }))), + 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"); + let g = terrain::Ground::of(&m, &camera).expect("terrain"); + // On the near wall at `x`, `metres` high. + let at = |frame: &Rendered, x: f64, metres: f64| { + let edge = Coord::new(x, -1000.0); + let (u, v) = camera.ground_px(edge); + let (px, py) = camera.project_raised(u, v, metres / g.per_unit(edge) / camera.res, view.width, view.height).expect("in view"); + frame.pixmap.pixel(px as u32, py as u32).expect("in the frame").demultiply() + }; + let bluish = |c: tiny_skia::ColorU8| c.blue() > c.red() + 60 && c.blue() > c.green() + 30; + let water = at(&frame, 500.0, 350.0); + assert!(bluish(water), "in the lake's section: {water:?}"); + for (x, metres) in [(500.0, 0.0), (-500.0, 350.0)] { + let c = at(&frame, x, metres); + assert!(!bluish(c) && c.red() > c.blue(), "({x}, {metres}): {c:?}"); + } + // Without water in the block the wall is ground there too. + m.view.terrain.as_mut().unwrap().block = Some(block(None)); + let dry = at(&render(&mut m, &view).expect("a frame"), 500.0, 350.0); + assert!(!bluish(dry) && dry.red() > dry.blue(), "{dry:?}"); + } + #[test] fn the_settled_mesh_follows_the_picture_up_to_the_dem() { // #1882: each band's mesh grows with its picture, within 160 and 640 cells along its diff --git a/crates/render/src/terrain.rs b/crates/render/src/terrain.rs index 8c26277d8..5e9961e2c 100644 --- a/crates/render/src/terrain.rs +++ b/crates/render/src/terrain.rs @@ -15,7 +15,7 @@ use rustgis_tiles::template::{self, TileId}; mod water; -pub(crate) use water::{Glint, Water, paint_shore}; +pub(crate) use water::{Glint, SHORE_PX, Water, paint_shore}; /// Cells along each side of a tilted view's band laid over the relief while the map moves (the /// drape, `tilt_drape` in the app): few enough to lay out every frame. @@ -256,6 +256,11 @@ impl Ground { per_unit(m, self.body) } + /// How much the heights are stretched (`Terrain::exaggeration`, as read). + pub(crate) fn exaggeration(&self) -> f64 { + self.exaggeration + } + /// Where the Web Mercator point `m` falls on the ground's grid, in its cells (column, row): /// a DEM's pixels; elevation tiles' pixels at the zoom read. `None` off the DEM's plane. pub fn grid_point(&self, m: Coord) -> Option<(f64, f64)> { @@ -629,6 +634,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + water: None, }; m.view.terrain = Some(rustgis_map::view::Terrain { source: rustgis_map::view::TerrainSource::Layer("dem".into()), @@ -672,6 +678,7 @@ mod tests { depth: Some(300.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + water: None, }; m.view.terrain = Some(rustgis_map::view::Terrain { source: rustgis_map::view::TerrainSource::Tiles { diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 110f4ecbe..4593f164a 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -655,7 +655,7 @@ impl Glint { /// How far inside the water's outline its shore band reaches, in logical pixels (#1915): a few, /// as relief artists draw it. -const SHORE_PX: f32 = 4.0; +pub(crate) const SHORE_PX: f32 = 4.0; /// The strokes the shore band is drawn with, each narrower than the one before, so it fades from /// the outline inward in as many steps. @@ -802,6 +802,7 @@ mod tests { depth: Some(300.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + water: None, }), water: None, }); diff --git a/docs/maintaining.md b/docs/maintaining.md index 368a39c0d..a783235ca 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -105,6 +105,7 @@ in the fixtures' README and in the test's `SKIPS` when a release has no such fil New project saves and map/layer exports write format 2. Their `requires` header names only features present in the saved payload: `terrain-block`, `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), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light) and `normalized-legend-urls` for normalized legend addresses. Project diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index e94910cef..4b3e63364 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -132,6 +132,24 @@ features (not one read a view at a time), with a name of its own; it follows the and when it is removed, or a project opens without it, the walls are `color` (said) until a polygon layer of that name comes back. A plain `"walls": "#RRGGBB"` takes the layer off. +With water on the terrain (below), `"block": {"water": {"depth": 12}}` shows it in the walls' +section: where the box's edge runs inside a water polygon (the first in the layer's rows where +they overlap, among the features its definition query keeps), the wall shows a band of water from +the water's level down to its floor, over the walls' colours, in the water layer's solid fill (the +topmost of its fill layers; one partly transparent laid over a light blue, as a section is opaque), +lit as the wall is and darker with depth, half as bright at the full +depth, with a line at the level and one along the floor as dark as the shore band. A DEM holds the +water's surface, not its bed, so the depth is given: `"depth"` in metres for every water body, or +`"field": "prof"` names a numeric field of the water layer holding each one's depth (`"depth"` then +serves the rows with no value). Both are stretched by the exaggeration, and the floor goes no lower +than the base. The floor follows the shore: no depth at the shoreline, the full depth from about +the shore band's width in (a few pixels at the view's centre), so the section shows a basin, not a +cliff. A water body with no depth, or no level, shows none, and setting the block or the water says +how many of those its definition query keeps have no value in the field. These depths are schematic +unless they come from a field: say so in the figure's caption. `"water": false` in the block takes +the water out of the walls; while it is there, taking the terrain's water off, or giving it a layer +without the depth field, is refused. + **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_v2.rgis b/schema/fixtures/terrain_block_water_v2.rgis new file mode 100644 index 000000000..73c88ddff --- /dev/null +++ b/schema/fixtures/terrain_block_water_v2.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Terrain block water","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,"field":"prof"}},"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"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index c6f3644e2..d981b569a 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1070,6 +1070,7 @@ "terrain-block", "terrain-water", "terrain-water-shore", + "terrain-block-water", "shaded-relief-effects", "normalized-legend-urls", "field-origin", @@ -1151,6 +1152,7 @@ "terrain-block", "terrain-water", "terrain-water-shore", + "terrain-block-water", "shaded-relief-effects", "normalized-legend-urls", "field-origin",