diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index c21f8dd8e3..48a0d1b6a8 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -651,6 +651,9 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { crate::s3_connections::resolve_project_s3(s); s.wait_in_place_reads(); super::project::say_conversion_fallbacks(s); + // What the imported maps' block diagrams can't draw their walls, top band or water bed + // from, as when a project opens. + super::project::say_block_layers(s, first_map..s.project.maps.len()); super::connections::note_waiting(s); if let Some(n) = names.last() && let Some(i) = s.project.maps.iter().position(|m| &m.name == n) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5d55e0d74..c3ff12fdf6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7480,6 +7480,10 @@ 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 layer of its walls' top band (#2607). + if let Some(top) = s.map_mut().view.terrain.as_mut().and_then(|t| t.block.as_mut()).and_then(|b| b.walls_top.as_mut()) { + replace(&mut top.layer); + } // 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()) @@ -7838,6 +7842,12 @@ fn square_labels_follow_removal(s: &mut Session, names: &[String]) { } } +/// What brings back a block's walls layer or top band after its layer is gone: a layer +/// `rustgis_render::terrain::walls_layer` takes. +fn back_as_walls_layer() -> &'static str { + "a polygon layer of that name comes back, the only layer so named and not one read a view at a time" +} + /// After layers called `names` are removed: a terrain drawn from one of them would lose its /// relief, or take another layer's heights by that name, so it is turned off, and said. Its water /// layer removed (#1915), the water keeps the name, so a layer of that name brings it back, and @@ -7853,12 +7863,24 @@ fn terrain_follows_removal(s: &mut Session, names: &[String]) { } let dem = terrain_dem(s).filter(|d| names.iter().any(|n| n.eq_ignore_ascii_case(d))); // So does the block's walls layer (#1914): its walls are their own colour meanwhile. Not when - // the DEM goes too: the terrain, its block with it, is turned off below. + // the DEM goes too: the terrain, its block with it, is turned off below. Said whenever no layer + // of that name is left that the walls can be drawn from (`walls_layer`): none, or only one that + // isn't of polygons, or several sharing the name. + let drawable = |s: &Session, name: &str| rustgis_render::terrain::walls_layer(s.map(), name).is_some(); let walls = s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.walls_layer.clone()); - if let Some(w) = walls.filter(|w| dem.is_none() && names.iter().any(|n| n.eq_ignore_ascii_case(w)) && named_layers(s, w) == 0) { + if let Some(w) = walls.filter(|w| dem.is_none() && names.iter().any(|n| n.eq_ignore_ascii_case(w)) && !drawable(s, w)) { + s.notify( + format!("Terrain: the block's walls layer '{w}' was removed, so the walls are one colour until {}", back_as_walls_layer()), + false, + ); + } + // And its walls' top band's (#2607): no band meanwhile. + let top = s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.walls_top.as_ref()).map(|t| t.layer.clone()); + if let Some(l) = top.filter(|l| dem.is_none() && names.iter().any(|n| n.eq_ignore_ascii_case(l)) && !drawable(s, l)) { s.notify( format!( - "Terrain: the block's walls layer '{w}' was removed, so the walls are one colour until a layer of that name comes back" + "Terrain: the block's walls' top layer '{l}' was removed, so the walls have no top band until {}", + back_as_walls_layer() ), false, ); diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 4f9a3c557a..f48ade0fa4 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -291,6 +291,100 @@ pub(super) fn off_dem(extent: Option<[f64; 4]>, dem: Option<&(String, Option<[f6 } } +/// What a block's walls layer (#1914), walls' top band (#2607) and water bed (#2434) can't be +/// drawn from in the project's maps `range` says: as a project opens ([`reset`]) and as maps are +/// imported (`map.import`), each kept by name so a layer of that name brings it back. +pub(crate) fn say_block_layers(s: &mut Session, range: std::ops::Range) { + // A block whose walls layer (#1914) is missing, holds no polygons, is read a view at a time or + // shares its name with another layer draws its walls in their own colour (`block::runs`, as + // the terrain command refuses such a layer): said, and kept, so a polygon layer of that name + // colours them again. + let plain: Vec = s + .project + .maps + .get(range.clone()) + .unwrap_or_default() + .iter() + .filter_map(|m| { + let l = m.view.terrain.as_ref()?.block.as_ref()?.walls_layer.as_ref()?; + rustgis_render::terrain::walls_layer(m, l).is_none().then(|| format!("{} ('{l}')", m.name)) + }) + .collect(); + match plain.as_slice() { + [] => {} + [one] => s.notify( + format!("{one}: the block diagram's walls layer is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so its walls are one colour"), + false, + ), + _ => s.notify( + format!( + "{} block diagrams have a walls layer that is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so their walls are one colour: {}", + plain.len(), + plain.join(", ") + ), + false, + ), + } + // So does a walls' top band (#2607) whose layer can't be read: no band, said, and kept. + let bandless: Vec = s + .project + .maps + .get(range.clone()) + .unwrap_or_default() + .iter() + .filter_map(|m| { + let l = &m.view.terrain.as_ref()?.block.as_ref()?.walls_top.as_ref()?.layer; + rustgis_render::terrain::walls_layer(m, l).is_none().then(|| format!("{} ('{l}')", m.name)) + }) + .collect(); + match bandless.as_slice() { + [] => {} + [one] => s.notify( + format!("{one}: the block diagram's walls' top layer is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so its walls have no top band"), + false, + ), + _ => s.notify( + format!( + "{} block diagrams have a walls' top layer that is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so their walls have no top band: {}", + bandless.len(), + bandless.join(", ") + ), + 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 + .get(range.clone()) + .unwrap_or_default() + .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, + ), + } +} + /// Replaces project authority, clearing the exchange record, item trust and active connections. fn reset(s: &mut Session, p: Project) { s.exchange = None; @@ -386,19 +480,6 @@ fn reset(s: &mut Session, p: Project) { ); } } - // A block whose walls layer (#1914) is missing, holds no polygons, is read a view at a time or - // shares its name with another layer draws its walls in their own colour (`block::runs`, as - // the terrain command refuses such a layer): said, and kept, so a polygon layer of that name - // colours them again. - let plain: Vec = s - .project - .maps - .iter() - .filter_map(|m| { - let l = m.view.terrain.as_ref()?.block.as_ref()?.walls_layer.as_ref()?; - rustgis_render::terrain::walls_layer(m, l).is_none().then(|| format!("{} ('{l}')", m.name)) - }) - .collect(); // A block cut to polygons (#2318) whose layer is missing or picks no polygon with an area // isn't drawn: said, and kept, so a polygon layer of that name, or an edit, brings it back. // One whose outline was simplified to stay under 65 535 sides is said as `map.terrain` says @@ -436,50 +517,7 @@ fn reset(s: &mut Session, p: Project) { ); super::terrain_blocks::told_uncut(s); } - match plain.as_slice() { - [] => {} - [one] => s.notify( - format!("{one}: the block diagram's walls layer is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so its walls are one colour"), - false, - ), - _ => s.notify( - format!( - "{} block diagrams have a walls layer that is missing, isn't a polygon layer, holds its features only a view at a time, or shares its name with another layer, so their walls are one colour: {}", - plain.len(), - plain.join(", ") - ), - 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, - ), - } + say_block_layers(s, 0..s.project.maps.len()); // 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. diff --git a/crates/engine/src/cmd/terrain_blocks.rs b/crates/engine/src/cmd/terrain_blocks.rs index 52dd850b4e..391c9e73f5 100644 --- a/crates/engine/src/cmd/terrain_blocks.rs +++ b/crates/engine/src/cmd/terrain_blocks.rs @@ -304,6 +304,7 @@ mod tests { depth: None, walls: BLOCK_WALLS, walls_layer: None, + walls_top: None, shape: Default::default(), water: None, }), diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index e43a5b0a53..a1dff0a23d 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, "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}"##, + 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, "top"?: a band along the walls' top, soil over rock {"layer": a polygon layer as the walls' layer: its solid fill where its polygons meet the block's edge (no band off them), "thickness": metres down from the ground before exaggeration (schematic) | {"field": a numeric field of the layer holding each polygon's metres (no band under one without a value over 0)}}, or false}, "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() @@ -339,16 +339,18 @@ fn terrain_block( None => Ok(left_out), Some(Value::Null) => Ok(BLOCK_WALLS), Some(Value::String(c)) => rustgis_map::Rgba::from_hex(c).ok_or("block's walls is an opaque colour, #RRGGBB"), - Some(_) => Err("block's walls is a colour, #RRGGBB, or {\"color\"?, \"layer\"?}"), + Some(_) => Err("block's walls is a colour, #RRGGBB, or {\"color\"?, \"layer\"?, \"top\"?}"), }; - // A colour, or the colour and a polygon layer that colours the walls where it has a polygon. - let (kept_color, kept_layer) = base.map_or((BLOCK_WALLS, None), |b| (b.walls, b.walls_layer.clone())); - let (walls, walls_layer) = match b.get("walls") { - None => (kept_color, kept_layer), - Some(Value::Null) => (BLOCK_WALLS, None), + // A colour, or the colour and a polygon layer that colours the walls where it has a polygon, + // and a band along their top from another (#2607). + let (kept_color, kept_layer, kept_top) = + base.map_or((BLOCK_WALLS, None, None), |b| (b.walls, b.walls_layer.clone(), b.walls_top.clone())); + let (walls, walls_layer, walls_top) = match b.get("walls") { + None => (kept_color, kept_layer, kept_top), + Some(Value::Null) => (BLOCK_WALLS, None, None), Some(Value::Object(w)) => { - if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "color" | "layer")) { - return Err(format!("block's walls has no '{k}' (color, layer)")); + if let Some(k) = w.keys().find(|k| !matches!(k.as_str(), "color" | "layer" | "top")) { + return Err(format!("block's walls has no '{k}' (color, layer, top)")); } let layer = match w.get("layer") { None => kept_layer, @@ -356,10 +358,16 @@ fn terrain_block( Some(Value::String(n)) => Some(polygon_layer(s, n, "block's walls", "the units the walls show")?), Some(_) => return Err("block's walls' layer is a polygon layer's name".into()), }; - (color(w.get("color"), kept_color)?, layer) + let top = match w.get("top") { + None => kept_top, + Some(Value::Null | Value::Bool(false)) => None, + Some(Value::Object(t)) => Some(walls_top_band(s, t)?), + Some(_) => return Err(WALLS_TOP.into()), + }; + (color(w.get("color"), kept_color)?, layer, top) } - // A plain colour takes the walls' layer off. - other => (color(other, BLOCK_WALLS)?, None), + // A plain colour takes the walls' layers off. + other => (color(other, BLOCK_WALLS)?, None, None), }; // 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`). @@ -429,7 +437,7 @@ fn terrain_block( if b.get("radius").is_some_and(|r| !r.is_null()) && !matches!(shape, BlockShape::Circle { .. }) { return Err("block's radius is a circle's: give \"shape\": \"circle\" too".into()); } - let block = rustgis_map::view::TerrainBlock { extent, depth, walls, walls_layer, shape, water }; + let block = rustgis_map::view::TerrainBlock { extent, depth, walls, walls_layer, walls_top, shape, water }; block.check()?; Ok(block) } @@ -448,6 +456,40 @@ fn bed_layer(s: &Session, name: &str) -> Result { Ok(l.name.clone()) } +/// What a block's walls' top (#2607) is, as its errors say. +const WALLS_TOP: &str = + "block's walls' top is {\"layer\": a polygon layer, \"thickness\": metres | {\"field\": a numeric field of the layer}}, or false"; + +/// The band along the top of a block's walls (#2607) from `"top": {"layer", "thickness"}`: a +/// polygon layer as the walls' ([`polygon_layer`]) and its thickness, metres (checked by +/// [`rustgis_map::view::TerrainBlock::check`]) or `{"field"}`, a numeric field of that layer. +fn walls_top_band(s: &Session, t: &serde_json::Map) -> Result { + use rustgis_map::view::BandThickness; + if let Some(k) = t.keys().find(|k| !matches!(k.as_str(), "layer" | "thickness")) { + return Err(format!("block's walls' top has no '{k}' (layer, thickness)")); + } + let name = t.get("layer").and_then(Value::as_str).ok_or(WALLS_TOP)?; + let layer = polygon_layer(s, name, "block's walls' top", "the units the band shows")?; + let thickness = match t.get("thickness") { + Some(Value::Number(n)) => BandThickness::Metres(n.as_f64().ok_or(WALLS_TOP)?), + Some(Value::Object(f)) => { + if let Some(k) = f.keys().find(|k| k.as_str() != "field") { + return Err(format!("block's walls' top thickness has no '{k}' (field)")); + } + let f = f.get("field").and_then(Value::as_str).ok_or(WALLS_TOP)?; + let l = s.map().layer_by_name(&layer).ok_or_else(|| format!("no layer '{layer}'"))?; + let i = l.dataset.field_index(f).ok_or_else(|| format!("'{layer}' has no field '{f}' (the band's thickness)"))?; + let field = l.dataset.fields.get(i).ok_or_else(|| format!("'{layer}' has no field '{f}' (the band's thickness)"))?; + if !field.ty.is_numeric() { + return Err(format!("block's walls' top thickness field '{}' isn't numeric (metres)", field.name)); + } + BandThickness::Field { field: field.name.clone() } + } + _ => return Err(WALLS_TOP.into()), + }; + Ok(rustgis_map::view::WallsTop { layer, thickness }) +} + /// 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. @@ -750,9 +792,10 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { (None, Some(d)) => (json!(d), "layer"), (None, None) => (json!("layer"), "layer"), }; - let walls = match &b.walls_layer { - Some(l) => json!({"color": b.walls.hex(), "layer": l}), - None => json!(b.walls.hex()), + let walls = match (&b.walls_layer, &b.walls_top) { + (None, None) => json!(b.walls.hex()), + (l, None) => json!({"color": b.walls.hex(), "layer": l}), + (l, Some(top)) => json!({"color": b.walls.hex(), "layer": l, "top": top}), }; // A circle's radius as drawn: the largest in the box when none is given or a larger one is // (`radius_capped`), when the box is known. @@ -800,12 +843,16 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { } return Err(e); } - // And the walls' layer (#1914), kept by name as the water's is. - if let Some(l) = t.block.as_ref().and_then(|b| b.walls_layer.as_ref()) - && m.layers.iter().filter(|o| o.name.eq_ignore_ascii_case(l)).count() > 1 + // And the walls' layer (#1914) and their top's (#2607), kept by name as the water's is. + let walls_layers = + t.block.as_ref().map(|b| [(b.walls_layer.as_ref(), "walls layer"), (b.walls_top.as_ref().map(|t| &t.layer), "walls' top layer")]); + if let Some((l, what)) = walls_layers + .into_iter() + .flatten() + .find_map(|(l, what)| l.filter(|l| m.layers.iter().filter(|o| o.name.eq_ignore_ascii_case(l)).count() > 1).map(|l| (l, what))) { let e = format!( - "more than one layer is called '{l}': give the block's walls layer a name of its own, then try again (Terrain stays as it was)" + "more than one layer is called '{l}': give the block's {what} a name of its own, then try again (Terrain stays as it was)" ); if let Some(old) = old_terrain { m.view.terrain = Some(old); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9c32ea295f..cbee53b64e 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -82,6 +82,7 @@ pub const CAPABILITIES: &[&str] = &[ "terrain-block-water", "terrain-block-water-bed", "terrain-block-walls-layer", + "terrain-block-walls-top", "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 201f64f145..cfa3495381 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -1078,7 +1078,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, mut bed, mut soft) = (false, false, false); + let (mut crisp, mut bed, mut walls_top, mut soft) = (false, false, 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. @@ -1110,6 +1110,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static 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()); + // The band along their top (#2607), which an older reader would save away. + walls_top |= t.block.as_ref().is_some_and(|b| b.walls_top.is_some()); } relief |= map.layers.iter().any(relief_effects); light |= map.layers.iter().any(relief_light); @@ -1132,6 +1134,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (block_water, "terrain-block-water"), (bed, "terrain-block-water-bed"), (walls_layer, "terrain-block-walls-layer"), + (walls_top, "terrain-block-walls-top"), (relief, "shaded-relief-effects"), (light, "shaded-relief-light"), (soft, "shaded-relief-shadow-softness"), @@ -1397,6 +1400,26 @@ mod tests { assert_eq!(serde_json::to_value(&plain).unwrap()["requires"], json!(["terrain-block"])); } + /// A band along the top of a block's walls (#2607) reads back as it was, and saving names it in + /// `requires`; the same block without it doesn't. + #[test] + fn terrain_block_walls_top_fixture_requires_it() { + let fixture = Project::from_json(include_str!("../../../schema/fixtures/terrain_block_walls_top_v2.rgis")).unwrap(); + let top = fixture.maps[0].view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.walls_top.clone()); + assert_eq!( + top, + Some(rustgis_map::view::WallsTop { layer: "solos".into(), thickness: rustgis_map::view::BandThickness::Metres(150.0) }) + ); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["terrain-block", "terrain-block-walls-layer", "terrain-block-walls-top"])); + assert_eq!(saved["maps"][0]["view"]["terrain"]["block"]["walls_top"], json!({"layer": "solos", "thickness": 150.0})); + let mut plain = fixture; + if let Some(b) = plain.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()) { + b.walls_top = None; + } + assert_eq!(serde_json::to_value(&plain).unwrap()["requires"], json!(["terrain-block", "terrain-block-walls-layer"])); + } + /// 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] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 228a95f994..91429ddd63 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -11928,6 +11928,7 @@ fn terrain_block_is_checked_kept_and_taken_off() { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), @@ -12148,6 +12149,7 @@ fn terrain_is_set_from_a_dem_or_tiles() { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), @@ -12170,6 +12172,7 @@ fn terrain_is_set_from_a_dem_or_tiles() { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), @@ -12196,6 +12199,7 @@ fn terrain_is_set_from_a_dem_or_tiles() { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), @@ -18145,6 +18149,7 @@ fn terrain_block_is_read_back_from_a_saved_project() { depth: Some(150.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }) @@ -18411,6 +18416,150 @@ fn terrain_block_walls_follow_a_polygon_layer() { assert!(s.map().view.terrain.is_none()); } +/// A band along the top of a block's walls from a second polygon layer (#2607): the layer and +/// its thickness checked before anything changes, reported and saved with the walls, following +/// its layer's renames, and said when it is removed or a saved project's is missing. +#[test] +fn imported_map_says_its_blocks_walls_and_top_band_have_no_layer() { + // #2173, #2607: a map whose block's walls and top band come from "solos", imported without + // that layer: both said as the map is imported, as when a project opens without it. + use base64::Engine; + let soils = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"classe": "latossolo"}, "geometry": {"type": "Polygon", "coordinates": [[[10.0, 45.0], [10.02, 45.0], [10.02, 45.04], [10.0, 45.04], [10.0, 45.0]]]}}, + ]}); + let soils = base64::engine::general_purpose::STANDARD.encode(soils.to_string().as_bytes()); + 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(); + s.run("layer.addDataBytes", &json!({"fileName": "solos.geojson", "data": soils})).unwrap(); + let name = s.map().layers.iter().find(|l| !l.is_raster()).map(|l| l.name.clone()).unwrap(); + s.run("map.terrain", &json!({"layer": dem, "block": {"walls": {"layer": name, "top": {"layer": name, "thickness": 150}}}})).unwrap(); + let mut map = s.map().clone(); + map.name = "Importado".into(); + map.layers.retain(|l| l.name != name); + assert!(map.view.terrain.as_ref().and_then(|t| t.block.as_ref()).is_some_and(|b| b.walls_top.is_some())); + let mark = s.notice_mark(); + s.run("map.import", &json!({"text": serde_json::to_string(&map).unwrap()})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("the block diagram's walls' top layer is missing")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("the block diagram's walls layer is missing")), "{said:?}"); +} + +#[test] +fn terrain_block_says_a_removal_that_leaves_no_layer_to_colour_its_walls() { + // #2173, #2607: the walls and their top band both from "solos". Removing it while a raster of + // that name stays, or while two polygon layers of that name stay, leaves no layer they can + // be drawn from (`walls_layer`): both say so, as when no layer of that name is left. + use base64::Engine; + let soils = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"classe": "latossolo"}, "geometry": {"type": "Polygon", "coordinates": [[[10.0, 45.0], [10.02, 45.0], [10.02, 45.04], [10.0, 45.04], [10.0, 45.0]]]}}, + ]}); + let soils = base64::engine::general_purpose::STANDARD.encode(soils.to_string().as_bytes()); + for left in ["a raster", "two polygon layers"] { + 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(); + s.run("layer.addDataBytes", &json!({"fileName": "solos.geojson", "data": soils})).unwrap(); + let (id, name) = s.map().layers.iter().find(|l| !l.is_raster()).map(|l| (l.id, l.name.clone())).unwrap(); + s.run("map.terrain", &json!({"layer": dem, "block": {"walls": {"layer": name, "top": {"layer": name, "thickness": 150}}}})) + .unwrap(); + // The layers of that name that stay, added and renamed to it. + let files: &[&str] = if left == "a raster" { &["outro.tif"] } else { &["b.geojson", "c.geojson"] }; + for file in files { + let data = if file.ends_with(".tif") { dem_b64() } else { soils.clone() }; + let before: Vec = s.map().layers.iter().map(|l| l.id).collect(); + s.run("layer.addDataBytes", &json!({"fileName": file, "data": data})).unwrap(); + let added = s.map().layers.iter().map(|l| l.id).find(|i| !before.contains(i)).unwrap(); + s.run("layer.rename", &json!({"layer": added, "name": name})).unwrap(); + } + assert_eq!(s.map().layers.iter().filter(|l| l.name.eq_ignore_ascii_case(&name)).count(), 1 + files.len(), "{left}"); + let mark = s.notice_mark(); + s.run("layer.remove", &json!({"layer": id})).unwrap(); + assert!(s.map().layers.iter().all(|l| l.id != id), "{left}: the first polygon layer is gone"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains(&format!("walls layer '{name}' was removed"))), "{left}: {said:?}"); + assert!(said.iter().any(|t| t.contains(&format!("walls' top layer '{name}' was removed"))), "{left}: {said:?}"); + } +} + +#[test] +fn terrain_block_walls_top_band_follows_its_layer() { + 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 soils = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"classe": "latossolo", "espessura": 2.5}, "geometry": {"type": "Polygon", "coordinates": [[[10.0, 45.0], [10.02, 45.0], [10.02, 45.04], [10.0, 45.04], [10.0, 45.0]]]}}, + ]}); + let data = base64::engine::general_purpose::STANDARD.encode(soils.to_string().as_bytes()); + s.run("layer.addDataBytes", &json!({"fileName": "solos.geojson", "data": data})).unwrap(); + let solos = s.map().layers.iter().find(|l| !l.is_raster()).map(|l| l.name.clone()).unwrap(); + let points = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10.01, 45.01]}}, + ]}); + let data = base64::engine::general_purpose::STANDARD.encode(points.to_string().as_bytes()); + s.run("layer.addDataBytes", &json!({"fileName": "furos.geojson", "data": data})).unwrap(); + for (top, said) in [ + (json!({"layer": "Nowhere", "thickness": 150}), "no layer 'Nowhere'"), + (json!({"layer": "furos", "thickness": 150}), "'furos' isn't a polygon layer"), + (json!({"layer": dem, "thickness": 150}), "isn't a polygon layer"), + (json!({"layer": solos}), "\"thickness\": metres"), + (json!({"layer": solos, "thickness": "150"}), "\"thickness\": metres"), + (json!({"layer": solos, "thickness": 0}), "over 0 and up to 20000"), + (json!({"layer": solos, "thickness": 30000}), "over 0 and up to 20000"), + (json!({"layer": solos, "thickness": 150, "field": "x"}), "has no 'field' (layer, thickness)"), + (json!({"layer": solos, "thickness": {"field": "nada"}}), "has no field 'nada' (the band's thickness)"), + (json!({"layer": solos, "thickness": {"field": "classe"}}), "thickness field 'classe' isn't numeric"), + (json!({"layer": solos, "thickness": {"field": "espessura", "x": 1}}), "thickness has no 'x' (field)"), + (json!({"layer": solos, "thickness": {}}), "{\"field\": a numeric field"), + (json!("solos"), "or false"), + ] { + let e = s.run("map.terrain", &json!({"layer": dem, "block": {"walls": {"top": top}}})).unwrap_err(); + assert!(e.contains(said), "{top}: {e}"); + assert!(s.map().view.terrain.is_none(), "{top}: refused whole"); + } + // Set: reported with the walls, saved with the project; the walls' other keys stay. + let v = s.run("map.terrain", &json!({"layer": dem, "block": {"walls": {"top": {"layer": solos, "thickness": 150}}}})).unwrap(); + assert_eq!(v["block"]["walls"], json!({"color": "#C8B89A", "layer": null, "top": {"layer": solos, "thickness": 150.0}})); + let v = s.run("map.terrain", &json!({"block": {"walls": {"color": "#806040"}}})).unwrap(); + assert_eq!(v["block"]["walls"]["top"]["layer"], json!(solos)); + // Or its thickness from a numeric field of the layer, named as the layer has it. + let v = s.run("map.terrain", &json!({"block": {"walls": {"top": {"layer": solos, "thickness": {"field": "ESPESSURA"}}}}})).unwrap(); + assert_eq!(v["block"]["walls"]["top"]["thickness"], json!({"field": "espessura"})); + let saved = serde_json::to_string(&s.map().view).unwrap_or_default(); + let back: rustgis_map::view::ViewSettings = serde_json::from_str(&saved).unwrap_or_default(); + assert_eq!(back.terrain, s.map().view.terrain); + let top = |s: &Session| { + s.map().view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|b| b.walls_top.as_ref()).map(|t| t.layer.clone()) + }; + // It follows its layer's renames. + let id = s.map().layer_by_name(&solos).map(|l| l.id).unwrap(); + s.run("layer.rename", &json!({"layer": id, "name": "pedologia"})).unwrap(); + assert_eq!(top(&s).as_deref(), Some("pedologia")); + // A saved project without it opens with no band, said; the name kept. A clean one says nothing. + let mut saved = s.project.clone(); + saved.maps[0].layers.retain(|l| l.name != "pedologia"); + let mut opened = Session::new(Project::default()); + crate::cmd::project::reset_to(&mut opened, saved); + assert!(opened.notices.iter().any(|n| n.text.contains("the block diagram's walls' top layer is missing")), "{:?}", opened.notices); + assert_eq!(top(&opened).as_deref(), Some("pedologia")); + let mut clean = Session::new(Project::default()); + crate::cmd::project::reset_to(&mut clean, s.project.clone()); + assert!(!clean.notices.iter().any(|n| n.text.contains("top")), "{:?}", clean.notices); + // Removed: said, and the name kept. + let mark = s.notice_mark(); + s.run("layer.remove", &json!({"layer": id})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let removed = said.iter().find(|t| t.contains("walls' top layer 'pedologia' was removed")); + // With what brings the band back: a layer of that name that the band can be drawn from. + let back = "until a polygon layer of that name comes back, the only layer so named and not one read a view at a time"; + assert!(removed.is_some_and(|t| t.contains(back)), "{said:?}"); + assert_eq!(top(&s).as_deref(), Some("pedologia")); + // False takes it off, as a plain colour does. + s.run("map.terrain", &json!({"block": {"walls": {"top": false}}})).unwrap(); + assert_eq!(top(&s), None); +} + /// #2605: `map.terrain`'s help names every key the block's parts and the water take, each in its /// own part of the text, as the parser lists them when it refuses one it doesn't know (the walls' /// object form of #2173 was missing); so do the errors for a block or water that isn't an object. @@ -18432,6 +18581,7 @@ fn terrain_help_names_every_block_key() { for (params, from, to) in [ (json!({"block": {"bogus": 1}}), r#""block"?:"#, ", or false to take it off"), (json!({"block": {"walls": {"bogus": 1}}}), r#""walls"?:"#, r#", "shape"?:"#), + (json!({"block": {"walls": {"top": {"bogus": 1}}}}), r#""top"?:"#, ", or false}"), (json!({"block": {"shape": {"bogus": 1}}}), r#""shape"?:"#, r#", "radius"?:"#), (json!({"block": {"water": {"bogus": 1}}}), r#""water"?: the terrain's water"#, ", or false}"), (json!({"water": {"bogus": 1}}), r#""water"?: water bodies"#, ", or false to take it off"), diff --git a/crates/map/src/view.rs b/crates/map/src/view.rs index fda47f120e..374a4eabe6 100644 --- a/crates/map/src/view.rs +++ b/crates/map/src/view.rs @@ -225,6 +225,10 @@ 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, + /// A band along the top of the walls from a second polygon layer (#2607): soil over the rock + /// `walls_layer` shows. None: no band. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub walls_top: Option, /// The outline the ground is cut to inside the box (#2318). #[serde(default, skip_serializing_if = "BlockShape::is_box")] pub shape: BlockShape, @@ -235,6 +239,26 @@ pub struct TerrainBlock { pub water: Option, } +/// The band along the top of a block diagram's walls (#2607): under each polygon of `layer` (by +/// name, as the terrain's DEM) the box's edge meets, its fill, `thickness` deep below the ground, +/// its contacts straight across it. Schematic: as a rule far thicker than the real soil. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct WallsTop { + pub layer: String, + /// How deep the band reaches down from the ground, before exaggeration. + pub thickness: BandThickness, +} + +/// How thick a block's walls' top band is (#2607): metres all along, or a numeric field of its +/// layer holding each polygon's (no band under a polygon without a value over 0 there). Saved as +/// a number, or as `{"field": name}`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum BandThickness { + Metres(f64), + Field { field: String }, +} + /// The outline a block diagram's ground is cut to (#2318). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -348,6 +372,20 @@ impl TerrainBlock { if self.walls.a() != 255 { return Err("block's walls is an opaque colour, #RRGGBB".into()); } + if let Some(t) = &self.walls_top { + if t.layer.trim().is_empty() { + return Err("block's walls' top needs a layer: a polygon layer of the band's units".into()); + } + match &t.thickness { + BandThickness::Metres(d) if !(d.is_finite() && *d > 0.0 && *d <= BLOCK_MAX_DEPTH) => { + return Err(format!("block's walls' top thickness is metres, over 0 and up to {BLOCK_MAX_DEPTH:.0}")); + } + BandThickness::Field { field } if field.trim().is_empty() => { + return Err("block's walls' top thickness field needs a name: a numeric field of the top layer".into()); + } + _ => {} + } + } if let Some(w) = &self.water { if w.depth.is_none() && w.field.is_none() && w.bed.is_none() { return Err( diff --git a/crates/render/src/approximations.rs b/crates/render/src/approximations.rs index 5a47279947..d87f3e8120 100644 --- a/crates/render/src/approximations.rs +++ b/crates/render/src/approximations.rs @@ -324,6 +324,50 @@ pub(crate) fn walls_left_plain(name: &str, n: usize) { ); } +/// What a block diagram's top band (#2607) drew of layer `name`: `n` of the polygons along it +/// fill with hatches, markers, gradients or shapebursts, which the band leaves off. +pub(crate) fn band_left_plain(name: &str, n: usize) { + note( + format!("{name}\0band"), + format!( + "{name}: the block diagram's top band shows solid fills only, so {n} of its polygons along the walls show there without their hatches, markers, gradients or shapebursts" + ), + ); +} + +/// What a block diagram's top band (#2607) drew of layer `name`, its thickness read from `field`: +/// `n` of its polygons along the walls have no value over 0 there, so no band under them. +pub(crate) fn band_unmeasured(name: &str, field: &str, n: usize) { + note( + format!("{name}\0band thickness"), + format!( + "{name}: {n} of its polygons along the block diagram's walls have no thickness over 0 in field '{field}', so its top band leaves them out" + ), + ); +} + +/// What a block diagram's top band (#2607) drew of layer `name` when its thickness `field` isn't a +/// numeric field of it (deleted, renamed or turned to text since it was set): no band. +pub(crate) fn band_no_field(name: &str, field: &str) { + note( + format!("{name}\0band field"), + format!( + "{name}: the block diagram's top band takes its thickness from field '{field}', which isn't a numeric field of it, so there is no band" + ), + ); +} + +/// What a block diagram's top band (#2607) drew of layer `name` where it is thicker than the +/// ground stands over the base: `n` of its stretches along the walls stop at the base. +pub(crate) fn band_at_base(name: &str, n: usize) { + note( + format!("{name}\0band base"), + format!( + "{name}: the block diagram's top band is thicker than the ground stands over the base along {n} stretches of the walls, so it stops at the base there" + ), + ); +} + /// 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). diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index f921f7c743..54dbee7805 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -659,8 +659,9 @@ impl Key { /// 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 cuts [`LAST`] keeps (maps drawn side by side, a layout's frames, walls and water). -const KEPT: usize = 4; +/// How many cuts [`LAST`] keeps (maps drawn side by side, a layout's frames, walls, their top +/// band and water). +const KEPT: usize = 6; /// `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. @@ -705,8 +706,8 @@ fn layer_cut( /// symbology gives the polygon under each stretch of the box's edge (the topmost where polygons /// overlap, among the rows its definition query keeps), and the walls' own colour off every /// polygon, with the patterns over it grown or shrunk as the layer's reference scale asks at the -/// map scale 1:`scale` (`Layer::size_factor`), as the ground's are. Else the walls' colour all -/// along. +/// map scale 1:`scale` (`Layer::size_factor`), as the ground's are, and styled at that scale (its +/// fill's `@map_scale`). Else the walls' colour all along. /// /// Runs on the thread drawing the frame. The pieces the polygons cut the sides into /// ([`units`]) are kept in [`LAST`], so they are read again only after an edit of the layer, a @@ -730,7 +731,8 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: let Some(layer) = layer else { return (0..b.sides()).map(whole).collect() }; crate::note_held_read(layer); let cut = layer_cut(layer, b, false, None, env); - let styler = layer.styler_with(env.clone()); + // Styled at the drawing scale, as the layer is on the ground and the top band is. + let styler = layer.styler_with(env.at_scale(Some(scale))); let grow = layer.size_factor(scale); // The rows along the walls whose gradients or shapebursts the walls leave off, said once // with their number (see `crate::approximations`). @@ -768,6 +770,115 @@ pub(crate) fn runs(map: &Map, b: &Block, scale: f64, env: &rustgis_data::query:: runs } +/// A stretch of a side under one polygon of the walls' top layer (#2607): from `lo` to `hi` +/// along it ([`Block::along`]), in `color`, `thickness` metres (exaggerated, as +/// [`Ground::height`]'s are) down from the ground, and the polygon's class among the layer's +/// Unique Values (none for `` and the other renderers), so that two classes +/// filled alike still meet at a contact. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct BandRun { + pub lo: f64, + pub hi: f64, + pub color: Rgba, + pub thickness: f64, + pub class: Option, +} + +/// The top band's stretches along each side of a block's outline, in [`Block::side`]'s order +/// (through `Deref`), and the name of the layer they come from, for what is said of them. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Bands { + pub layer: String, + pub sides: Vec>, +} + +impl std::ops::Deref for Bands { + type Target = Vec>; + fn deref(&self) -> &Self::Target { + &self.sides + } +} + +/// The band along the top of the walls of block `b` on `map` (#2607), when they have a top layer +/// (`TerrainBlock::walls_top`, taken as [`crate::terrain::walls_layer`] takes the walls' layer): +/// under each polygon of it the box's edge meets (the topmost, among the rows its definition +/// query keeps), the solid fill [`unit_paint`] gives it, the top's thickness deep (metres all +/// along, or the polygon's value of the top's numeric field, as given: [`draw_walls`] stops it at +/// the base, said); off its polygons, no band, nor under one with no value over 0 in the field, +/// said once with how many (and no band at all, said, when the layer has no such numeric field). +/// Its hatches, markers, gradients and shapebursts are left off, said once with how many polygons. +/// Styled at the drawing scale 1:`scale` (its fill's `@map_scale`), as the layer is on the ground. +/// The pieces are cut, and kept, as the walls' are ([`layer_cut`]). +pub(crate) fn band_runs(map: &Map, b: &Block, ground: &Ground, scale: f64, env: &rustgis_data::query::Env) -> Bands { + use rustgis_map::view::BandThickness; + let none = || Bands { layer: String::new(), sides: vec![Vec::new(); b.sides()] }; + let top = map.view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|t| t.walls_top.as_ref()); + let Some((layer, top)) = top.and_then(|t| crate::terrain::walls_layer(map, &t.layer).map(|l| (l, t))) else { + return none(); + }; + let x = ground.exaggeration(); + // The thickness all along, or the numeric field holding each polygon's. + let (metres, field) = match &top.thickness { + BandThickness::Metres(d) => (Some(*d), None), + BandThickness::Field { field } => { + let numeric = layer.dataset.field_index(field).filter(|&i| layer.dataset.fields.get(i).is_some_and(|f| f.ty.is_numeric())); + let Some(i) = numeric else { + crate::approximations::band_no_field(&layer.name, field); + return none(); + }; + (None, Some((i, field.as_str()))) + } + }; + crate::note_held_read(layer); + let cut = layer_cut(layer, b, false, None, env); + let styler = layer.styler_with(env.at_scale(Some(scale))); + let classer = layer.renderer.classer_with(&layer.dataset, env.at_scale(Some(scale))); + let (mut plain, mut thin) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + let mut side_bands = |side: &Vec<(f64, f64, Option)>| { + let mut out: Vec = Vec::new(); + for &(lo, hi, row) in side { + let Some(r) = row else { continue }; + let given = metres.or_else(|| field.and_then(|(i, _)| layer.dataset.features.value(r, i).as_f64())); + let Some(d) = given.filter(|d| d.is_finite() && *d > 0.0) else { + thin.insert(r); + continue; + }; + // As given: one deeper than the ground stands over the base stops there, said. + let thickness = d * x; + let (sym, _, fills) = styler.style_and_fills(r); + let (color, patterns) = unit_paint(sym.fill, fills, b.walls); + if !patterns.is_empty() || band_leaves_off(sym.fill, fills) { + plain.insert(r); + } + let class = layer.renderer.unique_class(&layer.dataset, r, &classer); + match out.last_mut() { + Some(last) if (last.color, last.thickness, last.class) == (color, thickness, class) && (lo - last.hi).abs() < SEAM => { + last.hi = hi + } + _ => out.push(BandRun { lo, hi, color, thickness, class }), + } + } + out + }; + let bands = Bands { layer: layer.name.clone(), sides: cut.units.iter().map(&mut side_bands).collect() }; + if !plain.is_empty() { + crate::approximations::band_left_plain(&layer.name, plain.len()); + } + if let (false, Some((_, f))) = (thin.is_empty(), field) { + crate::approximations::band_unmeasured(&layer.name, f, thin.len()); + } + bands +} + +/// Whether the top band, solid fills only (#2607), leaves off part of how a polygon whose symbol +/// fills with `fill`, or with the stacked `fills` in its place, looks: any hatch, marker, +/// gradient or shapeburst that draws over its topmost opaque solid fill (over everything, +/// without one), a hatch under a translucent solid among them, as it shows through it. +fn band_leaves_off(fill: Rgba, fills: &[FillLayer]) -> bool { + let top = fills.iter().rposition(|f| matches!(f.pattern, FillPattern::Solid) && f.color.unwrap_or(fill).a() == 255); + fills.iter().skip(top.map_or(0, |i| i + 1)).any(|f| !matches!(f.pattern, FillPattern::Solid) && f.draws(fill)) +} + /// Whether walls leave off part of how a polygon whose symbol fills with `fill`, or with the /// stacked `fills` in its place, looks: a gradient or shapeburst that shows over its topmost /// opaque solid fill (over everything, without one), which [`unit_paint`] leaves off. @@ -1386,6 +1497,10 @@ fn draw_patterns( /// the contacts between colours. The water the outline 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. +/// The top band (`bands`, [`band_runs`], #2607) is drawn over the walls and their outline, below +/// the water: from the ground's edge down its thickness (never below the base), in its colour lit +/// as the top of the side is, outlined along the ground, its foot and its ends, so the walls' +/// contacts stop at its foot and its own classes meet at short lines across it. /// /// A polygon block's outline can be concave: ground and other walls can stand in front of a /// wall. Its walls are drawn among the ground instead, far to near, a few stretches of a side at @@ -1400,6 +1515,7 @@ pub(crate) fn draw_walls( b: &Block, edges: &[Edge], runs: &Runs, + bands: &Bands, water: &WaterRuns, fog: Rgba, far: f64, @@ -1476,6 +1592,18 @@ pub(crate) fn draw_walls( let mut outlines: Vec<(tiny_skia::Path, Rgba)> = Vec::new(); // The water in the walls' section, drawn over their outlines ([`draw_water`]). let mut waters: Vec = Vec::new(); + // The top band (#2607): its fills and its lines, drawn over the outlines, as a round block's + // outlines are, once all its sides are filled ([`draw_bands`]); and whether it stopped at the + // base anywhere. + let (mut band_fills, mut band_lines): (Vec<(tiny_skia::Path, Rgba)>, Vec<(tiny_skia::Path, Rgba)>) = (Vec::new(), Vec::new()); + // The band's stretches that stop at the base, by side and the stretch's ends along it (two + // runs, two classes, meeting inside one count it once), said once with the layer and how many. + let mut band_at_base = std::collections::BTreeSet::new(); + // Where a side's band meets its neighbour's in its own colour: no contact there. + let side_ends = |i: usize| { + let (key, a, z) = b.side(i); + (b.along(key, a).min(b.along(key, z)), b.along(key, a).max(b.along(key, z))) + }; let foot = |m: Coord| { let (u, v) = cam.ground_px(m); let up = (b.base / ground.per_unit(m) / cam.res.max(1e-9)).clamp(-1e7, 1e7); @@ -1714,12 +1842,150 @@ pub(crate) fn draw_walls( outline.line_to(ft.0, ft.1); } } + let edge_color = b.walls.shade(0.45).lerp(fog, f); if let Some(path) = outline.finish() { - outlines.push((path, b.walls.shade(0.45).lerp(fog, f))); + outlines.push((path, edge_color)); if !round { stroke_outlines(pm, &mut outlines, k); } } + // The top band (#2607): each of its stretches from the ground's edge down its thickness, + // a quad a stretch as the wall's (a hair longer each way), outlined along the ground and + // its foot, and across it at its ends: a contact with another class or the bare rock. At + // the ends of a side, where the walls' outline goes down the corner (a box's corners, a + // polygon block's sharp ones), always: the band's fill would hide that line, + // drawn before it; elsewhere only where the neighbour's band isn't there in its colour, + // thickness and class. + let ((lo_end, hi_end), (prev, next)) = (side_ends(s), b.neighbours(s)); + let (before_band, after_band) = (bands.get(prev).and_then(|r| r.last()), bands.get(next).and_then(|r| r.first())); + let goes_on = |o: Option<&BandRun>, run: &BandRun, at_end: bool| { + o.is_some_and(|p| { + let (lo, hi) = side_ends(if at_end { next } else { prev }); + (p.color, p.thickness, p.class) == (run.color, run.thickness, run.class) + && if at_end { (p.lo - lo).abs() < SEAM } else { (p.hi - hi).abs() < SEAM } + }) + }; + // Where the walls' outline goes down a corner (`down`), at the side's low and high end. + let (down_lo, down_hi) = if b.along(side, a) <= b.along(side, z) { (down_a, down_z) } else { (down_z, down_a) }; + let mut lines = PathBuilder::new(); + for run in bands.get(s).into_iter().flatten() { + let ends_across = [ + (run.lo, (run.lo - lo_end).abs() >= SEAM || down_lo || !goes_on(before_band, run, false)), + (run.hi, (run.hi - hi_end).abs() >= SEAM || down_hi || !goes_on(after_band, run, true)), + ]; + let mut fill = PathBuilder::new(); + for (ends, _, [ta, tz]) in &quads { + let (ca, cz) = (b.along(side, ends[0]), b.along(side, ends[1])); + let span = cz - ca; + if span.abs() < 1e-12 { + continue; + } + let (u, v) = ((run.lo - ca) / span, (run.hi - ca) / span); + let (t0, t1) = (u.min(v).max(0.0), u.max(v).min(1.0)); + if t1 <= t0 { + continue; + } + // The stretch's ends raised to the ground: its top is the straight line between them. + let raised = |m: Coord| { + let (u, v) = cam.ground_px(m); + (u, v, ground.up_px(m, &cam)) + }; + let (ra, rz) = (raised(ends[0]), raised(ends[1])); + // The ground's edge over `t`, on the screen line from `ta` to `tz` the wall is drawn + // to: in a turned view the stretch's ends lie at different depths, so the ground's + // point `t` along the stretch is not `t` along that line, and the band's contacts + // would lean away from their feet. + let seen = |t: f64| { + let (u, v) = lerp((ra.0, ra.1), (rz.0, rz.1), t); + cam.project_raised(u, v, ra.2 + (rz.2 - ra.2) * t, w, h) + }; + let (sa, sz) = (seen(0.0), seen(1.0)); + let top_at = |t: f64| { + let along = match (sa, sz, seen(t)) { + (Some(a), Some(z), Some(q)) => { + let (dx, dy) = (z.0 - a.0, z.1 - a.1); + let len = dx * dx + dy * dy; + if len > 1e-18 { ((q.0 - a.0) * dx + (q.1 - a.1) * dy) / len } else { t } + } + _ => t, + }; + lerp(*ta, *tz, along.clamp(0.0, 1.0)) + }; + // The band's foot `t` along the stretch: its thickness under the ground's edge + // drawn there, never below the base. That edge is the mesh's (`ta` to `tz`), which + // can stand off the ground read at the stretch's ends, and the ground inside the + // stretch off both: its height is read through its screen point + // ([`up_through`]), from the line's between the ends there. + // Whether this stretch of the band stops at the base anywhere. + let mut at_base = false; + let mut under = |t: f64| { + 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 per = ground.per_unit(m) * res; + let seen_up = |up: f64| { + cam.project_raised(gu, gv, up.clamp(-1e7, 1e7), w, h) + .map(|(x, y)| (x * k, y * k)) + .filter(|p| p.0.is_finite() && p.1.is_finite()) + }; + let (line, top) = (ra.2 + (rz.2 - ra.2) * t, top_at(t)); + let edge = up_through(&cam, (gu, gv), line, top, (w, h, k)); + let (foot, base) = (edge - run.thickness / per, b.base / per); + at_base |= foot < base; + // Never over the top on screen, whatever the heights: where it would + // stand up the vertical from the top, it is the top. + let (Some(p), Some(q), Some(at)) = (seen_up(line), seen_up(line - 1.0), seen_up(foot.max(base))) else { + return None; + }; + let over_top = (at.0 - top.0) * (p.0 - q.0) + (at.1 - top.1) * (p.1 - q.1) > 0.0; + // With how far over the base the foot would stand (under 0: it stops there). + Some((if over_top { top } else { at }, foot - base)) + }; + let (Some((ba, over_a)), Some((bz, over_z))) = (under(t0), under(t1)) else { continue }; + // Where the foot meets the base inside the stretch, it bends there: along the base + // on one side, rising from it on the other, not straight across over the rock. + let bend = ((over_a < 0.0) != (over_z < 0.0)) + .then(|| t0 + (t1 - t0) * over_a / (over_a - over_z)) + .and_then(&mut under) + .map(|(p, _)| p); + if at_base { + // Keyed by where the stretch lies along its side, which holds across the runs + // a long side is drawn in (`WALL_RUN`), not by its place among them. + band_at_base.insert((s, ca.to_bits(), cz.to_bits())); + } + let (ta2, tz2) = (top_at(t0), top_at(t1)); + let foot = match bend { + Some(c) => vec![grow(bz, c), pt(c), grow(ba, c)], + None => vec![grow(bz, ba), grow(ba, bz)], + }; + for (i, p) in [grow(ta2, tz2), grow(tz2, ta2)].into_iter().chain(foot).enumerate() { + if i == 0 { fill.move_to(p.0, p.1) } else { fill.line_to(p.0, p.1) } + } + fill.close(); + lines.move_to(pt(ta2).0, pt(ta2).1); + lines.line_to(pt(tz2).0, pt(tz2).1); + lines.move_to(pt(ba).0, pt(ba).1); + if let Some(c) = bend { + lines.line_to(pt(c).0, pt(c).1); + } + lines.line_to(pt(bz).0, pt(bz).1); + for (t, top, foot) in [(t0, ta2, ba), (t1, tz2, bz)] { + let c = ca + span * t; + if ends_across.iter().any(|(e, across)| *across && (c - e).abs() < SEAM) { + lines.move_to(pt(top).0, pt(top).1); + lines.line_to(pt(foot).0, pt(foot).1); + } + } + } + if let Some(path) = fill.finish() { + band_fills.push((path, run.color.shade(top_shade).lerp(fog, f))); + } + } + if let Some(path) = lines.finish() { + band_lines.push((path, edge_color)); + } + if !round { + draw_bands(pm, &mut band_fills, &mut band_lines, k); + } // 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, and at // each of the bed's samples too where it is read (#2434), so the floor follows the bed. @@ -1873,9 +2139,46 @@ pub(crate) fn draw_walls( } } stroke_outlines(pm, &mut outlines, k); + draw_bands(pm, &mut band_fills, &mut band_lines, k); + if !band_at_base.is_empty() { + crate::approximations::band_at_base(&bands.layer, band_at_base.len()); + } draw_water(pm, &mut waters, k); } +/// The height (up px, as [`rustgis_map::Camera::project_raised`] takes it) at which the vertical +/// over ground offsets `(u, v)` passes screen point `at` (physical px, `k` of them a logical px), +/// read along the vertical's line on screen (the part of `at` across it left out) from its +/// points at `near` and a pixel of height either side. A vertical's heights and its points' places +/// along that line match by a projective map, which keeps cross-ratios, so the height is exact +/// (a straight-line estimate is off where `near` stands far from it). `near` where it can't be told. +fn up_through(cam: &rustgis_map::Camera, (u, v): (f64, f64), near: f64, at: (f64, f64), (w, h, k): (f64, f64, f64)) -> f64 { + let seen = |up: f64| cam.project_raised(u, v, up, w, h).map(|(x, y)| (x * k, y * k)); + let (Some(p0), Some(p1), Some(p2)) = (seen(near), seen(near - 1.0), seen(near + 1.0)) else { return near }; + let (dx, dy) = (p2.0 - p1.0, p2.1 - p1.1); + let len = dx.hypot(dy); + // Places along the line from `p0`, up the vertical. + let place = |p: (f64, f64)| ((p.0 - p0.0) * dx + (p.1 - p0.1) * dy) / len; + let (s1, s2, s) = (place(p1), place(p2), place(at)); + if len < 1e-12 || s.abs() < 1e-12 || (s2 - s1).abs() < 1e-12 { + return near; + } + // The cross-ratio of (p0, p1; p2, at) along the line equals that of their heights (near, + // near − 1; near + 1, x): (x − near + 1) / (2 (x − near)). + let c = s2 * (s - s1) / ((s2 - s1) * s); + let x = (near - 1.0 - 2.0 * c * near) / (1.0 - 2.0 * c); + if x.is_finite() { x } else { near } +} + +/// Draws the top band's `fills` (#2607), then strokes its `lines` as the walls' outlines are, at +/// the scale `k` (physical px a logical one), and empties both. +fn draw_bands(pm: &mut Pixmap, fills: &mut Vec<(tiny_skia::Path, Rgba)>, lines: &mut Vec<(tiny_skia::Path, Rgba)>, k: f64) { + for (path, c) in fills.drain(..) { + pm.fill_path(&path, &paint(c, 1.0), FillRule::Winding, Transform::identity(), None); + } + stroke_outlines(pm, lines, k); +} + /// 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; @@ -1963,8 +2266,13 @@ pub fn flat_walls(map: &Map, ground: &Ground, b: &Block, res: f64, per_unit: f64 // What `runs` approximates is this drawing's, said with it; what frames before it said stays. let before = crate::approximations::keep(); let runs = runs(map, b, scale, &env); - let gaps = crate::approximations::take(); + let mut gaps = crate::approximations::take(); crate::approximations::restore(before); + // The walls' top band (#2607) is the map view's only. + let top = map.view.terrain.as_ref().and_then(|t| t.block.as_ref()).and_then(|t| t.walls_top.as_ref()); + if let Some(top) = top.filter(|t| crate::terrain::walls_layer(map, &t.layer).is_some()) { + gaps.push(format!("the walls' top band from '{}' is drawn on the map view only, not on the model's walls", top.layer)); + } let water = water_runs(map, b, ground, res, scale, &env).iter().map(Vec::len).sum(); let mut out = FlatWalls { pictures: None, squeeze: 1.0, water, gaps }; let boxed = b.circle.is_none() && b.outline.is_none() && runs.len() == 4; @@ -2451,6 +2759,7 @@ mod tests { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: Some("geo".into()), + walls_top: None, shape: rustgis_map::view::BlockShape::Box, water: None, }), @@ -2788,6 +3097,7 @@ mod tests { depth: None, walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, shape, water, }), @@ -2929,10 +3239,22 @@ mod tests { let water: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); let draw = |go_on: bool| { let (mut pm, mut asked) = (Pixmap::new(600, 500).unwrap(), 0); - draw_walls(&mut pm, &view, &g, &b, &edges, &runs, &water, Rgba::rgb(255, 255, 255), rustgis_map::camera::FAR, |_, _| { - asked += 1; - go_on - }); + draw_walls( + &mut pm, + &view, + &g, + &b, + &edges, + &runs, + &band_runs(&m, &b, &g, 1.0, &Default::default()), + &water, + Rgba::rgb(255, 255, 255), + rustgis_map::camera::FAR, + |_, _| { + asked += 1; + go_on + }, + ); (pm.pixels().iter().filter(|p| p.alpha() > 0).count(), asked) }; let (drawn, asked) = draw(true); @@ -2974,7 +3296,19 @@ mod tests { let runs = runs(&m, &b, 1.0, &Default::default()); let draw = |water: &WaterRuns| { let mut pm = Pixmap::new(600, 500).unwrap(); - draw_walls(&mut pm, &view, &g, &b, &edges, &runs, water, Rgba::rgb(255, 255, 255), rustgis_map::camera::FAR, |_, _| true); + draw_walls( + &mut pm, + &view, + &g, + &b, + &edges, + &runs, + &band_runs(&m, &b, &g, 1.0, &Default::default()), + water, + Rgba::rgb(255, 255, 255), + rustgis_map::camera::FAR, + |_, _| true, + ); pm }; let (wet, dry) = (draw(&water), draw(&(0..b.sides()).map(|_| Vec::new()).collect())); @@ -3030,28 +3364,65 @@ mod tests { /// 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 }; + south_wall_seen(m, b, g, res, water, 0.0, 20, None) + } + + /// [`south_wall`] seen from `bearing`, its wall in `count` stretches of equal length, the + /// ground's edge over them at the heights `mesh` gives (metres, exaggerated) as a mesh's + /// vertices would put it, else at the ground's own. A polygon block's south side is the side + /// along y −1000. + fn south_wall_seen( + m: &Map, + b: &Block, + g: &Ground, + res: f64, + water: &WaterRuns, + bearing: f64, + count: u16, + mesh: Option, + ) -> (Pixmap, impl Fn(f64, f64) -> (u32, u32)) { + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing, 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) + let top = |x: f64| { + let m = Coord::new(x, -1000.0); + raised(x, mesh.map_or_else(|| g.up_px(m, &camera), |metres| metres / g.per_unit(m) / res)) + }; + let south = match &b.outline { + Some(_) => (0..b.sides()) + .find(|&k| { + let (_, a, z) = b.side(k); + (a.y + 1000.0).abs() < 1.0 && (z.y + 1000.0).abs() < 1.0 + }) + .expect("a south side") as u16, + None => u16::from(SOUTH), + }; + let step = 2000.0 / f64::from(count); + let edges: Vec = (0..count) .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, - } + let (x0, x1) = (-1000.0 + step * f64::from(i), -1000.0 + step * f64::from(i + 1)); + Edge { side: 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); + draw_walls( + &mut pm, + &view, + g, + b, + &edges, + &runs, + &band_runs(m, b, g, 1.0, &Default::default()), + 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); @@ -3273,4 +3644,627 @@ mod tests { let (px, py) = at(-100.0, 970.0); assert!(is_water(pm.pixel(px, py).expect("in the picture").demultiply(), color)); } + + /// [`block_over_lakes`] with no lakes, its walls' top band (#2607) from "solos": one polygon a + /// class (field "classe"), each a Web Mercator box in its colour, `thickness` metres deep. + fn block_under_soils(soils: &[([f64; 4], &str, Rgba)], thickness: f64) -> (Map, Block, Ground, f64) { + let soils: Vec<_> = soils.iter().map(|&(r, c, fill)| (r, c, fill, None)).collect(); + block_under_soils_by(&soils, rustgis_map::view::BandThickness::Metres(thickness)) + } + + /// [`block_under_soils`] with each polygon's value of the numeric field "espessura" (none: + /// null) and the band's thickness given as `thickness`. + fn block_under_soils_by( + soils: &[([f64; 4], &str, Rgba, Option)], + thickness: rustgis_map::view::BandThickness, + ) -> (Map, Block, Ground, f64) { + with_soils(block_over_lakes(&[], None), soils, thickness) + } + + /// The block `base` with [`block_under_soils_by`]'s soils as its walls' top band. + fn with_soils( + base: (Map, Block, Ground, f64), + soils: &[([f64; 4], &str, Rgba, Option)], + thickness: rustgis_map::view::BandThickness, + ) -> (Map, Block, Ground, f64) { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let (mut m, b, g, res) = base; + let deg = |x: f64, y: f64| merc_to_lonlat(Coord::new(x, y)); + let fields = vec![Field::new("classe", FieldType::Text), Field::new("espessura", FieldType::Double)]; + let mut d = Dataset::new("solos", GeometryType::Polygon, fields); + for ([x0, y0, x1, y1], class, _, depth) in soils { + let ring = vec![deg(*x0, *y0), deg(*x1, *y0), deg(*x1, *y1), deg(*x0, *y1), deg(*x0, *y0)]; + d.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Text((*class).into()), depth.map_or(Value::Null, Value::Float)]); + } + m.add_dataset(d); + let base = rustgis_map::Symbol::default_for(GeometryType::Polygon, 0); + let classes = soils.iter().map(|(_, c, fill, _)| ((*c).to_string(), rustgis_map::Symbol { fill: *fill, ..base })).collect(); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "solos") { + l.renderer = rustgis_map::Renderer::Unique { + field: "classe".into(), + classes, + other: base, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: Default::default(), + other_fills: Vec::new(), + expression: None, + }; + } + if let Some(block) = m.view.terrain.as_mut().and_then(|t| t.block.as_mut()) { + block.walls_top = Some(rustgis_map::view::WallsTop { layer: "solos".into(), thickness }); + } + (m, b, g, res) + } + + #[test] + fn a_wall_shows_its_soil_band_over_the_rock() { + // #2607: along the south wall (ground at 500 m, the base 100 m under it, both doubled), red soil + // west of x 0 and green from 0 to 500, 30 m (60 m doubled, 6 px) deep; no soil east of 500. + let (red, green) = (Rgba::rgb(220, 30, 30), Rgba::rgb(30, 170, 60)); + let soils = [([-3000.0, -1500.0, 0.0, 0.0], "argissolo", red), ([0.0, -1500.0, 500.0, 0.0], "latossolo", green)]; + let (m, b, g, res) = block_under_soils(&soils, 30.0); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + let [w, e] = &bands[0][..] else { panic!("two classes along the south side: {:?}", bands[0]) }; + assert!((w.lo + 1000.0).abs() < 1e-6 && w.hi.abs() < 1e-6 && (e.hi - 500.0).abs() < 1e-6, "{w:?} {e:?}"); + assert!((w.thickness - 60.0).abs() < 1e-9 && (w.color, e.color) == (red, green)); + // The other sides: west under the red soil, north and east under none. + assert!(bands[1].is_empty() && bands[2].is_empty() && bands[3].len() == 1, "{bands:?}"); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let before = crate::approximations::keep(); + let (pm, at) = south_wall(&m, &b, &g, res, &dry); + let said = crate::approximations::take(); + crate::approximations::restore(before); + assert!(said.is_empty(), "solid fills reaching no base say nothing: {said:?}"); + let bare = block_over_lakes(&[], None).0; + let (plain, _) = south_wall(&bare, &b, &g, res, &dry); + let pixel = |pm: &Pixmap, x: f64, metres: f64| { + let (px, py) = at(x, metres); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + let hue = |c: tiny_skia::ColorU8| (c.red(), c.green(), c.blue()); + // Halfway down the band, each class's colour; under its foot and east of the soil, the rock. + let (r, gr) = (pixel(&pm, -500.0, 970.0), pixel(&pm, 250.0, 970.0)); + assert!(r.red() > 2 * r.green() && r.red() > 2 * r.blue(), "{r:?}"); + assert!(gr.green() > 2 * gr.red() && gr.green() > gr.blue() + 40, "{gr:?}"); + for (x, metres) in [(-500.0, 900.0), (250.0, 900.0), (750.0, 970.0)] { + assert_eq!(hue(pixel(&pm, x, metres)), hue(pixel(&plain, x, metres)), "{x} {metres}"); + } + // The contacts across the band, at x 0 between the classes and at 500 with the bare rock: a + // dark line there, none in the middle of a class. + // How near the outline's colour the pixels round `x` come (the sum of their differences). + let line = b.walls.shade(0.45); + let near_line = |x: f64| { + let (px, py) = at(x, 970.0); + let apart = |c: tiny_skia::ColorU8| { + c.red().abs_diff(line.r()) as u16 + c.green().abs_diff(line.g()) as u16 + c.blue().abs_diff(line.b()) as u16 + }; + (px - 1..=px + 1).filter_map(|x| pm.pixel(x, py)).map(|c| apart(c.demultiply())).min() + }; + for x in [0.0, 500.0] { + assert!(near_line(x).is_some_and(|d| d < 40), "{x}: {:?}", near_line(x)); + } + assert!(near_line(-500.0).is_some_and(|d| d > 100), "{:?}", near_line(-500.0)); + } + + #[test] + fn a_band_takes_each_polygons_thickness_from_a_field() { + // #2607: "thickness": {"field": "espessura"}: red soil 30 m (60 doubled) deep west of x 0, + // green 15 m (30 doubled) from 0 to 500, blue from 500 to 1000 with none: no band there, + // said with how many polygons. + use rustgis_map::view::BandThickness; + let (red, green, blue) = (Rgba::rgb(220, 30, 30), Rgba::rgb(30, 170, 60), Rgba::rgb(30, 60, 220)); + let soils = [ + ([-3000.0, -1500.0, 0.0, 0.0], "argissolo", red, Some(30.0)), + ([0.0, -1500.0, 500.0, 0.0], "latossolo", green, Some(15.0)), + ([500.0, -1500.0, 1000.0, 0.0], "neossolo", blue, None), + ]; + let by_field = BandThickness::Field { field: "espessura".into() }; + let (m, b, g, res) = block_under_soils_by(&soils, by_field); + let before = crate::approximations::keep(); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + let [w, e] = &bands[0][..] else { panic!("two measured classes along the south side: {:?}", bands[0]) }; + assert_eq!((w.color, e.color), (red, green)); + assert!((w.thickness - 60.0).abs() < 1e-9 && (e.thickness - 30.0).abs() < 1e-9, "{w:?} {e:?}"); + assert!((e.hi - 500.0).abs() < 1e-6, "{e:?}"); + let unmeasured: Vec<_> = said.iter().filter(|t| t.contains("no thickness over 0 in field 'espessura'")).collect(); + assert!(unmeasured.len() == 1 && unmeasured[0].starts_with("solos: 1 of its polygons"), "{said:?}"); + // Drawn: each class down its own thickness, the rock under it and where the blue soil has none. + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall(&m, &b, &g, res, &dry); + let (plain, _) = south_wall(&block_over_lakes(&[], None).0, &b, &g, res, &dry); + let pixel = |pm: &Pixmap, x: f64, metres: f64| { + let (px, py) = at(x, metres); + let c = pm.pixel(px, py).expect("in the picture").demultiply(); + (c.red(), c.green(), c.blue()) + }; + let (r, gr) = (pixel(&pm, -500.0, 955.0), pixel(&pm, 250.0, 985.0)); + assert!(r.0 > 2 * r.1 && r.0 > 2 * r.2, "{r:?}"); + assert!(gr.1 > 2 * gr.0 && gr.1 > gr.2 + 40, "{gr:?}"); + for (x, metres) in [(250.0, 955.0), (750.0, 985.0), (-500.0, 920.0)] { + assert_eq!(pixel(&pm, x, metres), pixel(&plain, x, metres), "{x} {metres}"); + } + // A field the layer doesn't have, or one that isn't numeric: no band at all, said. + for field in ["nada", "classe"] { + let (m, b, g, _) = block_under_soils_by(&soils, BandThickness::Field { field: field.into() }); + let before = crate::approximations::keep(); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + assert!(bands.iter().all(Vec::is_empty), "{field}: {bands:?}"); + assert!(said.iter().any(|t| t.contains(&format!("field '{field}', which isn't a numeric field"))), "{field}: {said:?}"); + } + } + + #[test] + fn a_band_reaching_a_box_corner_keeps_the_corners_outline() { + // #2607: the band runs to the south wall's west end, the box's corner: the + // outline down that corner shows across the band as it does below it, not under its fill. + let red = Rgba::rgb(220, 30, 30); + let (m, b, g, res) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 30.0); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall(&m, &b, &g, res, &dry); + let line = b.walls.shade(0.45); + // How near the outline's colour the pixels round the corner come, at `metres` up. + let near_line = |metres: f64| { + let (px, py) = at(-1000.0, metres); + let apart = |c: tiny_skia::ColorU8| { + c.red().abs_diff(line.r()) as u16 + c.green().abs_diff(line.g()) as u16 + c.blue().abs_diff(line.b()) as u16 + }; + (px.saturating_sub(1)..=px + 1).filter_map(|x| pm.pixel(x, py)).filter(|c| c.alpha() > 0).map(|c| apart(c.demultiply())).min() + }; + // Halfway down the band, the corner's line (anti-aliased at the wall's edge): far nearer + // the line's colour than the band's fill 100 m in from the corner is. + let fill = { + let (px, py) = at(-900.0, 970.0); + let c = pm.pixel(px, py).expect("in the picture").demultiply(); + c.red().abs_diff(line.r()) as u16 + c.green().abs_diff(line.g()) as u16 + c.blue().abs_diff(line.b()) as u16 + }; + assert!(fill > 120, "{fill}"); + assert!(near_line(970.0).is_some_and(|d| d < 60), "{:?}", near_line(970.0)); + } + + #[test] + fn a_field_thickness_past_the_blocks_depth_is_kept_and_stops_at_the_base() { + // #2607: a polygon's 25 000 m (more than any block is deep) is its thickness as + // given, not cut to 20 000 unsaid; the band stops at the base, said once. A thickness + // within the wall says nothing of the base. + use rustgis_map::view::BandThickness; + let red = Rgba::rgb(220, 30, 30); + let by_field = || BandThickness::Field { field: "espessura".into() }; + let deep = [([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red, Some(25_000.0))]; + let (m, b, g, res) = block_under_soils_by(&deep, by_field()); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + assert!((bands[0][0].thickness - 50_000.0).abs() < 1e-6, "{:?}", bands[0]); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let said = |m: &Map| { + let before = crate::approximations::keep(); + let _ = south_wall(m, &b, &g, res, &dry); + let said = crate::approximations::take(); + crate::approximations::restore(before); + said + }; + assert_eq!(said(&m).iter().filter(|t| t.contains("stops at the base")).count(), 1, "{:?}", said(&m)); + let thin = [([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red, Some(10.0))]; + let (m, ..) = block_under_soils_by(&thin, by_field()); + assert!(said(&m).is_empty(), "{:?}", said(&m)); + } + + #[test] + fn a_band_contact_stands_upright_in_a_turned_view() { + // #2607: seen from bearing 40°, the south wall recedes, so its ends lie at + // different depths. In one stretch, the contact at x 0 (red soil west, green east, 30 m, + // 60 doubled) runs straight down from the ground's edge there to the band's foot there: + // red just west of x 0 and green just east, near the ground as near the foot. + let (red, green) = (Rgba::rgb(220, 30, 30), Rgba::rgb(30, 170, 60)); + let soils = [([-3000.0, -1500.0, 0.0, 0.0], "argissolo", red), ([0.0, -1500.0, 3000.0, 0.0], "latossolo", green)]; + let (m, b, g, res) = block_under_soils(&soils, 30.0); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 40.0, 1, None); + let hue = |x: f64, metres: f64| { + let (px, py) = at(x, metres); + let c = pm.pixel(px, py).expect("in the picture").demultiply(); + (c.red(), c.green(), c.blue()) + }; + let is_red = |c: (u8, u8, u8)| c.0 > 2 * c.1 && c.0 > 2 * c.2; + let is_green = |c: (u8, u8, u8)| c.1 > 2 * c.0 && c.1 > c.2 + 40; + for metres in [992.0, 948.0] { + let (west, east) = (hue(-60.0, metres), hue(60.0, metres)); + assert!(is_red(west) && is_green(east), "{metres}: {west:?} {east:?}"); + } + } + + #[test] + fn a_band_over_a_rise_inside_a_stretch_stays_under_its_top() { + // #2607: the ground rises from 500 m at the south wall's ends to 700 m at x 0, but + // the wall is one stretch, whose top is the straight line between its ends (1000 m + // doubled). The band's foot is taken from that line too: at x 0, where the classes meet, + // it doesn't stand 1340 m up, over the top, and no band shows above the top line. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let (red, green) = (Rgba::rgb(220, 30, 30), Rgba::rgb(30, 170, 60)); + let soils = [([-3000.0, -1500.0, 0.0, 0.0], "argissolo", red), ([0.0, -1500.0, 3000.0, 0.0], "latossolo", green)]; + let (mut m, _, _, res) = block_under_soils(&soils, 30.0); + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let rise = (0..500 * 500) + .map(|i| { + let x = -5000.0 + 20.0 * (f64::from(i % 500) + 0.5); + (500.0 + 200.0 * (1.0 - x.abs() / 500.0).max(0.0)) as f32 + }) + .collect(); + let dem = Raster::new("dem", 500, 500, vec![rise], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "dem") { + l.raster = Some(rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + } + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; + let g = Ground::of(&m, &camera).unwrap(); + let b = g.block(&m).unwrap(); + assert!((g.up_px(Coord::new(0.0, -1000.0), &camera) * res * g.per_unit(Coord::new(0.0, -1000.0)) - 1400.0).abs() < 25.0); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 1, None); + let band = |c: tiny_skia::ColorU8| { + let (r, g) = (u16::from(c.red()), u16::from(c.green())); + c.alpha() > 0 && (r > 2 * g || g > r + 60) + }; + let above: Vec<_> = (-18..=18) + .flat_map(|i| (0..20).map(move |j| (50.0 * f64::from(i), 1030.0 + 20.0 * f64::from(j)))) + .filter(|&(x, metres)| { + let (px, py) = at(x, metres); + pm.pixel(px, py).is_some_and(|c| band(c.demultiply())) + }) + .collect(); + assert!(above.is_empty(), "band over the top line at {above:?}"); + // Under the top line, the band still shows each class. + let hue = |x: f64| { + let (px, py) = at(x, 970.0); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + let (w, e) = (hue(-500.0), hue(500.0)); + assert!(u16::from(w.red()) > 2 * u16::from(w.green()) && u16::from(e.green()) > u16::from(e.red()) + 60, "{w:?} {e:?}"); + } + + #[test] + fn a_band_reaching_a_polygon_blocks_corner_keeps_the_corners_outline() { + // #2607: a square polygon block under one soil all round. The band goes on + // round the south-west corner in the same colour and thickness, but the outline turns + // 90° there, so the walls' outline goes down the corner: that line shows across the band + // too, not under its fill. + use rustgis_map::view::{BandThickness, BlockShape}; + let red = Rgba::rgb(220, 30, 30); + let square: [(&[[f64; 4]], _); 1] = [(&[[-1000.0, -1000.0, 1000.0, 1000.0]], None)]; + let base = block_over_lakes_shaped(&square, None, BlockShape::Polygon { layer: "lagos".into(), filter: None }); + let soil = [([-3000.0, -1500.0, 3000.0, 3000.0], "argissolo", red, None)]; + let (m, b, g, res) = with_soils(base, &soil, BandThickness::Metres(30.0)); + assert!(b.outline.is_some()); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + assert!(bands.iter().all(|r| r.len() == 1), "one run a side, all round: {bands:?}"); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 8, None); + let line = b.walls.shade(0.45); + let apart = |c: tiny_skia::ColorU8| { + c.red().abs_diff(line.r()) as u16 + c.green().abs_diff(line.g()) as u16 + c.blue().abs_diff(line.b()) as u16 + }; + let near_line = |metres: f64| { + let (px, py) = at(-1000.0, metres); + (px.saturating_sub(1)..=px + 1).filter_map(|x| pm.pixel(x, py)).filter(|c| c.alpha() > 0).map(|c| apart(c.demultiply())).min() + }; + let fill = { + let (px, py) = at(-900.0, 970.0); + apart(pm.pixel(px, py).expect("in the picture").demultiply()) + }; + // Halfway down the band, the corner's line: well nearer the line's colour than the band's + // fill 100 m in from the corner is (without it, about as far: the fill hid it). The + // band's fill reaches a hair past the corner, so the line's anti-aliased half lies on it. + assert!(fill > 120, "{fill}"); + assert!(near_line(970.0).is_some_and(|d| d + 40 < fill), "{:?} vs {fill}", near_line(970.0)); + } + + #[test] + fn a_band_hangs_from_the_meshs_edge_where_the_ground_reads_higher() { + // #2607: the mesh puts the ground's edge along the south wall at 500 m (1000 + // doubled), but the DEM reads 700 m (1400) there. The band hangs its 30 m (60) from the + // edge drawn, so its foot is at 940, not at 1340 over the top: no band above the top + // line, and the band under it. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let red = Rgba::rgb(220, 30, 30); + let (mut m, _, _, res) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 30.0); + 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![700.0; 500 * 500]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "dem") { + l.raster = Some(rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + } + if let Some(block) = m.view.terrain.as_mut().and_then(|t| t.block.as_mut()) { + block.depth = Some(1000.0); + } + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; + let g = Ground::of(&m, &camera).unwrap(); + let b = g.block(&m).unwrap(); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 4, Some(1000.0)); + let band = |c: tiny_skia::ColorU8| c.alpha() > 0 && u16::from(c.red()) > 2 * u16::from(c.green()); + let above: Vec<_> = (-18..=18) + .flat_map(|i| (0..20).map(move |j| (50.0 * f64::from(i), 1030.0 + 20.0 * f64::from(j)))) + .filter(|&(x, metres)| { + let (px, py) = at(x, metres); + pm.pixel(px, py).is_some_and(|c| band(c.demultiply())) + }) + .collect(); + assert!(above.is_empty(), "band over the top line at {above:?}"); + let pixel = |metres: f64| { + let (px, py) = at(-500.0, metres); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + assert!(band(pixel(970.0)), "the band under the top: {:?}", pixel(970.0)); + assert!(!band(pixel(900.0)), "the rock under its foot: {:?}", pixel(900.0)); + } + + #[test] + fn a_band_meeting_the_base_inside_a_stretch_stays_on_it() { + // #2607: one stretch along the south wall, its ground rising from 100 at x −1000 + // to 300 at x 1000 (exaggerated), the base at 0, the band 200 deep. Its foot is on the + // base all along the west half, where the ground stands under 200 over it, and rises from + // x 0: no rock shows between the band and the base, as it would under a straight foot + // from the base at the west end to 100 at the east. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let red = Rgba::rgb(220, 30, 30); + let (mut m, _, _, res) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 100.0); + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let rise = (0..500 * 500) + .map(|i| { + let x = -5000.0 + 20.0 * (f64::from(i % 500) + 0.5); + (100.0 + 0.05 * x).clamp(0.0, 1000.0) as f32 + }) + .collect(); + let dem = Raster::new("dem", 500, 500, vec![rise], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "dem") { + l.raster = Some(rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + } + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; + let g = Ground::of(&m, &camera).unwrap(); + let mut b = g.block(&m).unwrap(); + b.base = 0.0; + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 1, None); + let red_at = |x: f64, metres: f64| { + let (px, py) = at(x, metres); + let c = pm.pixel(px, py).expect("in the picture").demultiply(); + u16::from(c.red()) > 2 * u16::from(c.green()) + }; + // Each column of the west half, from 2 px under the ground to 2 px over the base: band. + let mut rock = Vec::new(); + for i in 1..20 { + let x = -1000.0 + 50.0 * f64::from(i); + let ground = 200.0 + 0.1 * x; + let (_, top) = at(x, ground); + let (_, base) = at(x, 0.0); + let n = (top + 2..base.saturating_sub(1)) + .filter(|&py| { + let (px, _) = at(x, 0.0); + pm.pixel(px, py).is_some_and(|c| { + let c = c.demultiply(); + u16::from(c.red()) <= 2 * u16::from(c.green()) + }) + }) + .count(); + if n > 0 { + rock.push((x, n)); + } + } + assert!(rock.is_empty(), "rock under the band (x, px): {rock:?}"); + assert!(red_at(-500.0, 100.0) && red_at(500.0, 150.0) && !red_at(500.0, 50.0)); + } + + #[test] + fn a_thin_band_hangs_from_a_mesh_edge_far_under_the_ground_read() { + // #2607: a 600 × 500 view at 60°, 5 m a pixel, heights + // doubled, the DEM at 280 m (560) and the mesh's edge at 200 m (400) along the south + // wall, the band 1 m deep (0.4 px). Its foot hangs from the edge drawn: no band shows over + // the top line, where a foot taken from a straight-line estimate of the edge's height + // stands about 9 px up. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let red = Rgba::rgb(220, 30, 30); + let (mut m, _, _, _) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 1.0); + 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![280.0; 500 * 500]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "dem") { + l.raster = Some(rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + } + if let Some(block) = m.view.terrain.as_mut().and_then(|t| t.block.as_mut()) { + block.depth = Some(1000.0); + } + let res = 5.0; + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res, bearing: 0.0, pitch: 60.0 }; + let g = Ground::of(&m, &camera).unwrap(); + let b = g.block(&m).unwrap(); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 4, Some(400.0)); + let band = |c: tiny_skia::ColorU8| c.alpha() > 0 && u16::from(c.red()) > 2 * u16::from(c.green()); + let above: Vec<_> = (-18..=18) + .flat_map(|i| (0..40).map(move |j| (50.0 * f64::from(i), 410.0 + 5.0 * f64::from(j)))) + .filter(|&(x, metres)| { + let (px, py) = at(x, metres); + pm.pixel(px, py).is_some_and(|c| band(c.demultiply())) + }) + .collect(); + assert!(above.is_empty(), "band over the top line at {} points, e.g. {:?}", above.len(), above.first()); + } + + #[test] + fn the_height_through_a_screen_point_is_read_exactly() { + // #2607: a 600 × 500 view at 60°, 5 m a pixel, heights + // doubled: the mesh's edge at 200 m (80 up px), the DEM at 280 m (112). Read from the DEM's + // height, the height through the edge's screen point is the edge's, not a straight-line + // estimate's (80.9 there, which stood a 0.4 px band's foot over its top). + let camera = rustgis_map::Camera { center: Coord::new(0.0, 0.0), res: 5.0, bearing: 0.0, pitch: 60.0 }; + let (w, h) = (600.0, 500.0); + for (k, bearing) in [(1.0, 0.0), (2.0, 0.0), (1.0, 40.0)] { + let camera = rustgis_map::Camera { bearing, ..camera }; + for y in [-1000.0, -400.0, 0.0, 600.0] { + let gp = camera.ground_px(Coord::new(300.0, y)); + let top = camera.project_raised(gp.0, gp.1, 80.0, w, h).map(|(x, y)| (x * k, y * k)).unwrap(); + let up = up_through(&camera, gp, 112.0, top, (w, h, k)); + assert!((up - 80.0).abs() < 1e-6, "k {k}, bearing {bearing}, y {y}: {up}"); + // From under it too, and from itself. + assert!((up_through(&camera, gp, 40.0, top, (w, h, k)) - 80.0).abs() < 1e-6); + assert!((up_through(&camera, gp, 80.0, top, (w, h, k)) - 80.0).abs() < 1e-6); + } + } + } + + #[test] + fn a_band_says_a_hatch_seen_through_a_translucent_solid_is_left_off() { + // #2607: a blue hatch under a red solid at half opacity shows through it on the map, so + // the band, solid only, says it leaves it off; under an opaque solid it can't be seen, and + // nothing is said. + let red = Rgba::rgb(220, 30, 30); + let hatch = FillPattern::Hatch { angle: 0.0, spacing: 6.0, width: 2.0, offset: 0.0 }; + let said_with = |solid: Rgba| { + let (mut m, b, g, _) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 30.0); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "solos") { + l.fill_layers = vec![ + FillLayer { color: Some(Rgba::rgb(0, 0, 255)), pattern: hatch }, + FillLayer { color: Some(solid), pattern: FillPattern::Solid }, + ]; + } + let before = crate::approximations::keep(); + band_runs(&m, &b, &g, 1.0, &Default::default()); + let said = crate::approximations::take(); + crate::approximations::restore(before); + said.iter().filter(|t| t.contains("shows solid fills only")).count() + }; + assert_eq!(said_with(Rgba::new(220, 30, 30, 128)), 1, "seen through half a solid"); + assert_eq!(said_with(red), 0, "hidden under an opaque one"); + } + + #[test] + fn a_band_keeps_the_contact_between_two_classes_filled_alike() { + // #2607: "argissolo" west of x 0 and "latossolo" from 0 to 500, two classes of the soils' + // Unique Values in the same red, 30 m deep: two runs, and the contact between them shows + // across the band at x 0, as at 500 where the rock comes up; none in the middle of one. + let red = Rgba::rgb(220, 30, 30); + let soils = [([-3000.0, -1500.0, 0.0, 0.0], "argissolo", red), ([0.0, -1500.0, 500.0, 0.0], "latossolo", red)]; + let (m, b, g, res) = block_under_soils(&soils, 30.0); + let bands = band_runs(&m, &b, &g, 1.0, &Default::default()); + assert_eq!(bands[0].len(), 2, "a run a class: {:?}", bands[0]); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let (pm, at) = south_wall(&m, &b, &g, res, &dry); + let line = b.walls.shade(0.45); + let near_line = |x: f64| { + let (px, py) = at(x, 970.0); + let apart = |c: tiny_skia::ColorU8| { + c.red().abs_diff(line.r()) as u16 + c.green().abs_diff(line.g()) as u16 + c.blue().abs_diff(line.b()) as u16 + }; + (px - 1..=px + 1).filter_map(|x| pm.pixel(x, py)).map(|c| apart(c.demultiply())).min() + }; + // Between the two reds, well nearer the line's colour than the red fill is (without the + // contact, about as far); where the rock comes up, the line beside the rock's own colour. + let fill = near_line(-500.0).expect("in the picture"); + assert!(fill > 100, "{fill}"); + assert!(near_line(0.0).is_some_and(|d| d + 40 < fill), "{:?} vs {fill}", near_line(0.0)); + assert!(near_line(500.0).is_some_and(|d| d < 40), "{:?}", near_line(500.0)); + } + + #[test] + fn a_stretch_two_classes_share_at_the_base_counts_once() { + // #2607: 150 m (300 doubled) of red soil west of x 50 and green east of it, over a wall + // 200 m (doubled) high: the band stops at the base in each of the south wall's 20 + // stretches, and the one from 0 to 100, which both classes share, is one of them, not two. + let (red, green) = (Rgba::rgb(220, 30, 30), Rgba::rgb(30, 170, 60)); + let soils = [([-3000.0, -1500.0, 50.0, 0.0], "argissolo", red), ([50.0, -1500.0, 3000.0, 0.0], "latossolo", green)]; + let (m, b, g, res) = block_under_soils(&soils, 150.0); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let before = crate::approximations::keep(); + let _ = south_wall(&m, &b, &g, res, &dry); + let said = crate::approximations::take(); + crate::approximations::restore(before); + let at_base: Vec<_> = said.iter().filter(|t| t.contains("stops at the base")).collect(); + assert!(at_base.len() == 1 && at_base[0].contains(" 20 stretches "), "{said:?}"); + } + + #[test] + fn a_polygon_blocks_long_side_counts_every_stretch_at_the_base() { + // #2607: a square polygon block's south side in 20 stretches, drawn in runs of + // `WALL_RUN` (8, 8 and 4), 150 m (300 doubled) of soil over a wall 200 m (doubled) high: + // the band stops at the base in all 20, and the notice counts 20, not the 8 of a run. + use rustgis_map::view::{BandThickness, BlockShape}; + let red = Rgba::rgb(220, 30, 30); + let square: [(&[[f64; 4]], _); 1] = [(&[[-1000.0, -1000.0, 1000.0, 1000.0]], None)]; + let base = block_over_lakes_shaped(&square, None, BlockShape::Polygon { layer: "lagos".into(), filter: None }); + let soil = [([-3000.0, -1500.0, 3000.0, 3000.0], "argissolo", red, None)]; + let (m, b, g, res) = with_soils(base, &soil, BandThickness::Metres(150.0)); + assert!(b.outline.is_some() && WALL_RUN < 20); + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let before = crate::approximations::keep(); + let _ = south_wall_seen(&m, &b, &g, res, &dry, 0.0, 20, None); + let said = crate::approximations::take(); + crate::approximations::restore(before); + let at_base: Vec<_> = said.iter().filter(|t| t.contains("stops at the base")).collect(); + assert!(at_base.len() == 1 && at_base[0].contains(" 20 stretches "), "{said:?}"); + } + + /// The band's thickness reads and saves as a number, or as `{"field": name}` (#2607). + #[test] + fn a_band_thickness_saves_as_a_number_or_a_field() { + use rustgis_map::view::{BandThickness, WallsTop}; + for (top, saved) in [ + ( + WallsTop { layer: "solos".into(), thickness: BandThickness::Metres(150.0) }, + serde_json::json!({"layer": "solos", "thickness": 150.0}), + ), + ( + WallsTop { layer: "solos".into(), thickness: BandThickness::Field { field: "espessura".into() } }, + serde_json::json!({"layer": "solos", "thickness": {"field": "espessura"}}), + ), + ] { + assert_eq!(serde_json::to_value(&top).unwrap(), saved); + assert_eq!(serde_json::from_value::(saved).unwrap(), top); + } + } + + #[test] + fn a_band_thicker_than_the_wall_stops_at_the_base_and_says_so() { + // #2607: 150 m (300 m doubled) of soil over a wall 200 m (doubled) high: red down to the + // base, said once with the layer and the stretches; a hatch over the soil's fill is left + // off the band, said with how many. + let red = Rgba::rgb(220, 30, 30); + let (mut m, b, g, res) = block_under_soils(&[([-3000.0, -1500.0, 3000.0, 0.0], "argissolo", red)], 150.0); + let hatch = FillPattern::Hatch { angle: 0.0, spacing: 6.0, width: 2.0, offset: 0.0 }; + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "solos") { + l.fill_layers = vec![ + FillLayer { color: None, pattern: FillPattern::Solid }, + FillLayer { color: Some(Rgba::rgb(0, 0, 255)), pattern: hatch }, + ]; + } + let dry: WaterRuns = (0..b.sides()).map(|_| Vec::new()).collect(); + let before = crate::approximations::keep(); + let c = { + let (pm, at) = south_wall(&m, &b, &g, res, &dry); + let (px, py) = at(-500.0, b.base + 10.0); + pm.pixel(px, py).expect("in the picture").demultiply() + }; + let said = crate::approximations::take(); + crate::approximations::restore(before); + assert!(c.red() > 2 * c.green() && c.red() > 2 * c.blue(), "{c:?}"); + // Said once, with the layer and how many of the wall's 20 stretches it stops in: all. + let at_base: Vec<_> = said.iter().filter(|t| t.contains("stops at the base")).collect(); + assert!(at_base.len() == 1 && at_base[0].starts_with("solos: ") && at_base[0].contains(" 20 stretches "), "{said:?}"); + assert_eq!( + said.iter().filter(|t| t.starts_with("solos: the block diagram's top band shows solid fills only, so 1 of")).count(), + 1, + "{said:?}" + ); + // No such layer, or no top: no band. + m.view.terrain.as_mut().and_then(|t| t.block.as_mut()).unwrap().walls_top.as_mut().unwrap().layer = "none".into(); + assert!(band_runs(&m, &b, &g, 1.0, &Default::default()).iter().all(Vec::is_empty)); + // And a 3D model's walls say they leave a band out. + m.view.terrain.as_mut().and_then(|t| t.block.as_mut()).unwrap().walls_top.as_mut().unwrap().layer = "solos".into(); + let flat = flat_walls(&m, &g, &b, res, g.per_unit(Coord::new(0.0, 0.0)), [1000.0; 4]); + assert!(flat.gaps.iter().any(|t| t.contains("top band from 'solos'")), "{:?}", flat.gaps); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index ef4ed7823c..d0cfac0366 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -3230,18 +3230,42 @@ fn drape_terrain( match walls { Some(b) if polygon => { let mut scratch = Vec::new(); - block::draw_walls(pm, view, ground, b, &edges, &block::runs(map, b, scale, env), &water, fog, far, |pm, key| { - let go_on = draw_to(pm, key, &mut scratch); - scratch.clear(); - go_on - }); + block::draw_walls( + pm, + view, + ground, + b, + &edges, + &block::runs(map, b, scale, env), + &block::band_runs(map, b, ground, scale, env), + &water, + fog, + far, + |pm, key| { + let go_on = draw_to(pm, key, &mut scratch); + scratch.clear(); + go_on + }, + ); draw_to(pm, f64::NEG_INFINITY, &mut scratch); } _ => { draw_to(pm, f64::NEG_INFINITY, &mut edges); // A cancelled frame is thrown away: its walls aren't drawn. if let Some(b) = walls.filter(|_| !stopped) { - block::draw_walls(pm, view, ground, b, &edges, &block::runs(map, b, scale, env), &water, fog, far, |_, _| true); + block::draw_walls( + pm, + view, + ground, + b, + &edges, + &block::runs(map, b, scale, env), + &block::band_runs(map, b, ground, scale, env), + &water, + fog, + far, + |_, _| true, + ); } } } @@ -12746,6 +12770,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }; @@ -12827,6 +12852,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape, }), @@ -12901,6 +12927,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape, }), @@ -12969,6 +12996,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape, }), @@ -13027,6 +13055,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, shape, water: None, }), @@ -13097,6 +13126,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: Some("geo".into()), + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), @@ -13149,6 +13179,117 @@ mod tests { assert_eq!(striped(&column(500.0)).0, 0, "east"); } + #[test] + fn a_walls_top_band_takes_its_fill_at_the_drawing_scale_as_the_ground_does() { + // #2607: the soils both drape the ground and give the near wall's top band, 100 m deep, + // filled by an expression reading `@map_scale`: green at a drawing scale, red without + // one. The band shows the ground's green, not red. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_map::symbol_by::SymbolBy; + 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 all = vec![deg(-3000.0, -3000.0), deg(3000.0, -3000.0), deg(3000.0, 3000.0), deg(-3000.0, 3000.0), deg(-3000.0, -3000.0)]; + let mut d = Dataset::new("solos", GeometryType::Polygon, Vec::new()); + d.push(Some(Geometry::Polygon(vec![vec![all]])), Vec::new()); + m.add_dataset(d); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "solos") { + l.symbol_by = + SymbolBy { fill: Some("CASE WHEN @map_scale IS NULL THEN '#ff0000' ELSE '#00ff00' END".into()), ..Default::default() }; + } + m.view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 1.0, + block: Some(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, + walls_top: Some(rustgis_map::view::WallsTop { + layer: "solos".into(), + thickness: rustgis_map::view::BandThickness::Metres(100.0), + }), + water: None, + shape: rustgis_map::view::BlockShape::Box, + }), + water: None, + }); + let frame = render(&mut m, &view).expect("a frame"); + let g = terrain::Ground::of(&m, &camera).expect("terrain"); + let px = |x: f64, y: f64, metres: f64| { + let at = Coord::new(x, y); + let (u, v) = camera.ground_px(at); + let p = camera.project_raised(u, v, metres / g.per_unit(at) / camera.res, view.width, view.height).expect("in view"); + let c = frame.pixmap.pixel(p.0 as u32, p.1 as u32).expect("in the frame").demultiply(); + (c.red(), c.green(), c.blue()) + }; + let green = |c: (u8, u8, u8)| u16::from(c.1) > 2 * u16::from(c.0) && u16::from(c.1) > 2 * u16::from(c.2); + let (ground, band) = (px(0.0, -700.0, 500.0), px(0.0, -1000.0, 450.0)); + assert!(green(ground), "the ground: {ground:?}"); + assert!(green(band), "the band, halfway down: {band:?}"); + } + + #[test] + fn a_walls_layer_takes_its_fill_at_the_drawing_scale_as_the_ground_does() { + // #2173, #2607: the soils both drape the ground and colour the near wall (`walls.layer`), + // filled by an expression reading `@map_scale`: green at a drawing scale, red without + // one. The wall shows the ground's green, as the top band does, not red. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_map::symbol_by::SymbolBy; + 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 all = vec![deg(-3000.0, -3000.0), deg(3000.0, -3000.0), deg(3000.0, 3000.0), deg(-3000.0, 3000.0), deg(-3000.0, -3000.0)]; + let mut d = Dataset::new("solos", GeometryType::Polygon, Vec::new()); + d.push(Some(Geometry::Polygon(vec![vec![all]])), Vec::new()); + m.add_dataset(d); + if let Some(l) = m.layers.iter_mut().find(|l| l.name == "solos") { + l.symbol_by = + SymbolBy { fill: Some("CASE WHEN @map_scale IS NULL THEN '#ff0000' ELSE '#00ff00' END".into()), ..Default::default() }; + } + m.view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 1.0, + block: Some(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: Some("solos".into()), + walls_top: None, + water: None, + shape: rustgis_map::view::BlockShape::Box, + }), + water: None, + }); + let frame = render(&mut m, &view).expect("a frame"); + let g = terrain::Ground::of(&m, &camera).expect("terrain"); + let px = |x: f64, y: f64, metres: f64| { + let at = Coord::new(x, y); + let (u, v) = camera.ground_px(at); + let p = camera.project_raised(u, v, metres / g.per_unit(at) / camera.res, view.width, view.height).expect("in view"); + let c = frame.pixmap.pixel(p.0 as u32, p.1 as u32).expect("in the frame").demultiply(); + (c.red(), c.green(), c.blue()) + }; + let green = |c: (u8, u8, u8)| u16::from(c.1) > 2 * u16::from(c.0) && u16::from(c.1) > 2 * u16::from(c.2); + let (ground, wall) = (px(0.0, -700.0, 500.0), px(0.0, -1000.0, 0.0)); + assert!(green(ground), "the ground: {ground:?}"); + assert!(green(wall), "the wall, halfway down: {wall:?}"); + } + #[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 @@ -13181,6 +13322,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, shape: rustgis_map::view::BlockShape::Box, water, }; diff --git a/crates/render/src/terrain.rs b/crates/render/src/terrain.rs index 8022041290..d665878604 100644 --- a/crates/render/src/terrain.rs +++ b/crates/render/src/terrain.rs @@ -688,6 +688,7 @@ mod tests { depth: Some(1000.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }; @@ -745,6 +746,7 @@ mod tests { depth: Some(300.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }; diff --git a/crates/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 98c94cd61f..5d05be20ed 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -921,6 +921,7 @@ mod tests { depth: Some(300.0), walls: rustgis_map::view::BLOCK_WALLS, walls_layer: None, + walls_top: None, water: None, shape: rustgis_map::view::BlockShape::Box, }), diff --git a/docs/maintaining.md b/docs/maintaining.md index f8e490dde3..2dbf78aa27 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -115,6 +115,7 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `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), +`terrain-block-walls-top` (the band along the top of its walls from a second layer), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light), `shaded-relief-shadow-softness` (a softness stored for a Shaded Relief's cast shadows, or set by a saved step; diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index b384e3e51e..6a4805a1c2 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -161,6 +161,27 @@ polygon layer of that name comes back. A plain `"walls": "#RRGGBB"` takes the la `{"walls": {"layer": "Geology"}}` keeps the walls' colour, `{"walls": {"color": "#806040"}}` keeps the layer, and `{"walls": {"layer": null}}` takes the layer off and keeps the colour. +Soil over rock: `"walls": {"layer": "Geology", "top": {"layer": "Soils", "thickness": 150}}` adds a +band along the top of the walls from a second polygon layer. Along each wall the band runs under +the ground's edge, `thickness` metres deep (before exaggeration, so it is stretched as the relief +is), in the solid fill the second layer's symbology gives the polygon under the box's edge there +(as the walls take theirs; its hatches, markers, gradients and shapebursts are left off, said with +how many polygons). Off its polygons there is no band, and the rock reaches the ground. In place +of a number, `"thickness": {"field": "depth_m"}` takes each polygon's thickness from a numeric +field of the second layer (metres, before exaggeration): under a polygon with no value over 0 +there is no band, said with how many, and a field the layer no longer has as a number (deleted, +renamed or turned to text since) gives no band at all, said. The band +is outlined along the ground and its foot, so the walls' contacts stop there, and two soil classes +meet at a short line across it. It never reaches below the base: where the ground stands less +than its thickness over the base it stops there, said. The band is schematic: real soil is a few +metres deep at most, and a band that shows at the block's scale is far thicker, so give the figure +a note such as "soil thickness not to scale". It works without a walls layer too, over the walls' +colour. The top layer is checked, followed and said as the walls layer is (a polygon layer holding +all its features, with a name of its own; renamed with it; when it is removed, or a project opens +without it, no band until a layer of that name comes back). `"top": false` takes the band off, and +a plain `"walls": "#RRGGBB"` takes it off with the layer. Only the map view draws the band: a 3D +model's walls (`map.exportBlock`) leave it out, said. Saved projects require `terrain-block-walls-top`. + `"shape": "circle"` cuts a round block: the largest circle inside the box (the DEM's extent or `"extent"`), centred in it, or a smaller one with `"radius"` (map units; one larger than the box's circle takes the box's). It reads the same at any bearing, which suits a figure that diff --git a/schema/fixtures/terrain_block_walls_top_v2.rgis b/schema/fixtures/terrain_block_walls_top_v2.rgis new file mode 100644 index 0000000000..f352ba7267 --- /dev/null +++ b/schema/fixtures/terrain_block_walls_top_v2.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Terrain block walls top","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":[128,96,64,255],"walls_layer":"geologia","walls_top":{"layer":"solos","thickness":150.0}}}},"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-block-walls-layer","terrain-block-walls-top"]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 480dd51cb4..a50a4dbb78 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1244,6 +1244,7 @@ "terrain-block-water", "terrain-block-water-bed", "terrain-block-walls-layer", + "terrain-block-walls-top", "shaded-relief-effects", "normalized-legend-urls", "field-origin", @@ -1366,6 +1367,7 @@ "terrain-block-water", "terrain-block-water-bed", "terrain-block-walls-layer", + "terrain-block-walls-top", "shaded-relief-effects", "normalized-legend-urls", "field-origin",