From b8518f4c32214af8f978777abb4fa913bdb739dc Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 14 Nov 2026 10:45:44 -0300 Subject: [PATCH 1/3] feat(render): a rock colour on the steep slopes of Shaded Relief (#1913) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/raster.rs | 38 ++++++- crates/engine/src/tests.rs | 32 ++++++ crates/map/src/qgis/raster.rs | 1 + crates/map/src/qgis/tests.rs | 11 +- crates/map/src/raster.rs | 141 +++++++++++++++++++++--- crates/render/src/layout.rs | 2 + crates/render/src/lib.rs | 3 + crates/render/src/raster.rs | 171 ++++++++++++++++++++--------- crates/render/src/raster_export.rs | 2 + crates/ui-egui/src/mapview.rs | 12 +- crates/ui-egui/src/panes.rs | 49 ++++++++- docs/user-guide/data.md | 14 ++- 12 files changed, 395 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 25b286223b..7fbfd48b68 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use rustgis_data::raster::{self, Raster}; use rustgis_geom::Extent; use rustgis_map::raster::{ - Normalizer, RasterLayer, RasterMask, RasterRenderer, RasterStyle, Resampling, Stretch, classify_masked, unique_values, + Normalizer, RasterLayer, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, Stretch, classify_masked, unique_values, }; use rustgis_map::{ClassMethod, Ramp, RasterDefaults}; use serde_json::{Value, json}; @@ -36,7 +36,7 @@ pub fn commands() -> Vec { C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"fileName": "name.tif|.tiff|.asc|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k (JPEG 2000: desktop, through GDAL)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "stream"?, "as"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "grey"?: bool (shadedRelief without its colour ramp)}"#, + r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), C::new("raster.stretch", "Stretch Type", "Style › Rendering", stretch).inputs(stretch_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_raster) @@ -778,10 +778,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { RasterRenderer::Colormap } "shadedrelief" | "hillshade" => { - // Left out, a Shaded Relief keeps its own shadows and sky; a new one has neither. - let (cur_shadow, cur_sky) = match rl.style.renderer { - RasterRenderer::ShadedRelief { shadow, sky, .. } => (shadow, sky), - _ => (0.0, 0.0), + // Left out, a Shaded Relief keeps its own shadows, sky and rock; a new one has none. + let (cur_shadow, cur_sky, cur_rock) = match rl.style.renderer { + RasterRenderer::ShadedRelief { shadow, sky, rock, .. } => (shadow, sky, rock), + _ => (0.0, 0.0, None), }; RasterRenderer::ShadedRelief { band: bi, @@ -791,6 +791,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { z_factor: f(p, "zFactor").unwrap_or(1.0).clamp(0.001, 1000.0), shadow: f(p, "shadow").unwrap_or(cur_shadow).clamp(0.0, 1.0), sky: f(p, "sky").unwrap_or(cur_sky).clamp(0.0, 1.0), + rock: match p.get("rock") { + None => cur_rock, + Some(v) => relief_rock(v, cur_rock)?, + }, } } other => return Err(format!("unknown raster symbology '{other}'")), @@ -804,6 +808,28 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { }) } +/// The rock of a Shaded Relief's `"rock"` (see `raster.symbology`): `false` or null for none, or +/// an object whose missing keys keep `cur`'s, or else [`Rock::DEFAULT`]'s. +fn relief_rock(v: &Value, cur: Option) -> Result, String> { + if v.is_null() || *v == Value::Bool(false) { + return Ok(None); + } + if !v.is_object() { + return Err("rock must be an object with from, to and color, or false".into()); + } + let was = cur.unwrap_or(Rock::DEFAULT); + let angle = |k: &str, d: f64| match v.get(k).filter(|x| !x.is_null()) { + None => Ok(d), + Some(x) => x.as_f64().filter(|a| a.is_finite()).map(|a| a.clamp(0.0, 90.0)).ok_or_else(|| format!("rock's {k} must be degrees")), + }; + let (from, to) = (angle("from", was.from)?, angle("to", was.to)?); + if from >= to { + return Err(format!("rock's from ({from}°) must be below its to ({to}°)")); + } + let color = super::layout::color(v, "color", was.color)?.with_alpha(255); + Ok(Some(Rock { from, to, color })) +} + /// Most values a mask lists. const MAX_MASK_VALUES: usize = 256; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bb613dfa53..320598e5b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4325,6 +4325,38 @@ fn shaded_relief_keeps_its_sky_visibility() { assert!(s.notices.iter().all(|n| !n.text.contains("sky")), "{:?}", s.notices); } +/// Shaded Relief's rock on steep slopes (#1913): an object turns it on, its missing keys from the +/// current rock or the defaults; kept when left out; `false` removes it; a `from` not below `to` +/// or a bad colour is refused; saved with the project only when set, and drawn in an export. +#[test] +fn shaded_relief_keeps_its_rock_on_steep_slopes() { + use rustgis_map::raster::Rock; + let mut s = with_raster(); + let rock = |s: &Session| match s.map().layers.first().and_then(|l| l.raster.as_ref()).map(|r| &r.style.renderer) { + Some(rustgis_map::RasterRenderer::ShadedRelief { rock, .. }) => *rock, + other => panic!("{other:?}"), + }; + let rocks_saved = |s: &mut Session| s.project.saved_text(None).unwrap().0.matches("\"rock\"").count(); + s.run("raster.symbology", &json!({"type": "shadedRelief"})).unwrap(); + assert_eq!(rock(&s), None, "off by default"); + let before = rocks_saved(&mut s); + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": {}})).unwrap(); + assert_eq!(rock(&s), Some(Rock::DEFAULT)); + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": {"to": 50, "color": "#806040"}})).unwrap(); + s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200})).unwrap(); + let want = Rock { from: 25.0, to: 50.0, color: rustgis_map::Rgba::rgb(0x80, 0x60, 0x40) }; + assert_eq!(rock(&s), Some(want), "left out, kept; its missing keys too"); + assert_eq!(rocks_saved(&mut s), before + 1, "saved when set"); + for bad in [json!({"from": 40, "to": 30}), json!({"from": 30, "to": 30}), json!({"color": "rock"}), json!(3)] { + assert!(s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": bad})).is_err(), "{bad}"); + assert_eq!(rock(&s), Some(want), "{bad}: refused, the rock kept"); + } + assert!(crate::cmd::share::map_png(&mut s, Some(300.0), Some(200.0), None).unwrap().len() > 1000); + s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": false})).unwrap(); + assert_eq!(rock(&s), None); + assert_eq!(rocks_saved(&mut s), before, "not saved once removed"); +} + /// An export draws the sky a pit hides: its floor darker with `sky` 1 than with 0, the ground /// around it (which sees the whole sky) the same. The first export with the sky, from a cold /// cache, waits for the grid: it is the same image as one drawn once the grid is kept. diff --git a/crates/map/src/qgis/raster.rs b/crates/map/src/qgis/raster.rs index 8cf2350131..cd4b4c1d38 100644 --- a/crates/map/src/qgis/raster.rs +++ b/crates/map/src/qgis/raster.rs @@ -96,6 +96,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo z_factor: num("zfactor", 1.0).clamp(0.0001, 10_000.0), shadow: 0.0, sky: 0.0, + rock: None, }; (renderer, Stretch::None) } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 319f4eb740..5a60a28a0b 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -867,7 +867,16 @@ fn raster_renderers_read_as_rustgis_raster_styles() { ); assert_eq!( s.raster.unwrap().renderer, - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 300.0, altitude: 35.0, z_factor: 2.0, shadow: 0.0, sky: 0.0 } + RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth: 300.0, + altitude: 35.0, + z_factor: 2.0, + shadow: 0.0, + sky: 0.0, + rock: None + } ); assert!(report.notes.iter().any(|n| n.text.contains("saturation"))); let (s, report) = read(r#""#, ""); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index b2d0939125..6d4b0a10cd 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1150,6 +1150,32 @@ impl Default for ZarrTime { } } +/// Shaded Relief's rock colour on steep slopes (#1913): below `from` degrees of slope the ramp's +/// colour is kept, above `to` it is `color`, and between them the two are blended on a smooth +/// step. The slope is the ground's own, without the Z factor (see [`slope`]). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Rock { + pub from: f64, + pub to: f64, + pub color: Rgba, +} + +impl Rock { + /// What a rock turned on without settings is: a light warm grey from 25° to 40°, which a 30 m + /// DEM reaches on its real scarps (it averages a cliff with its foot). + pub const DEFAULT: Rock = Rock { from: 25.0, to: 40.0, color: Rgba::rgb(0xB2, 0xAC, 0xA4) }; + + /// The share of rock (0 to 1) on a slope of `degrees`: 0 up to `from`, 1 from `to` on, and a + /// smooth step between them, so no hard outline follows a contour of slope. + pub fn share(&self, degrees: f64) -> f64 { + if self.to - self.from <= 0.0 { + return if degrees >= self.to { 1.0 } else { 0.0 }; + } + let t = ((degrees - self.from) / (self.to - self.from)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + } +} + fn is_no_shadow(v: &f64) -> bool { *v == 0.0 } @@ -1356,7 +1382,8 @@ pub enum RasterRenderer { /// Hillshade, optionally tinted by elevation. `shadow` (0 to 1) is how dark the shadows the /// terrain casts are drawn (see [`crate::shadow`]); 0, the default, casts none. `sky` (0 to 1) /// is how much the share of the sky each cell sees scales its ambient light - /// ([`crate::shadow::sky`]); 0, the default, leaves it whole. + /// ([`crate::shadow::sky`]); 0, the default, leaves it whole. `rock` tints steep slopes toward + /// a rock colour before the light shades them (see [`Rock`]); none, the default, keeps the ramp. ShadedRelief { band: usize, ramp: Option, @@ -1367,6 +1394,8 @@ pub enum RasterRenderer { shadow: f64, #[serde(default, skip_serializing_if = "is_no_shadow")] sky: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + rock: Option, }, } @@ -1925,16 +1954,17 @@ impl<'a> Colorizer<'a> { /// The colour of a pixel from its renderer band values (`NaN` = no data), or `None` for /// transparent. `hillshade` (0–255) is used by Shaded Relief. pub fn color(&self, vals: &[f32], hillshade: Option) -> Option<[u8; 4]> { - self.color_lit(vals, hillshade, None) + self.color_lit(vals, hillshade, None, None) } /// [`Colorizer::color`], with Shaded Relief's ambient light scaled by `ambient` (0–255, the - /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`). - pub fn color_lit(&self, vals: &[f32], hillshade: Option, ambient: Option) -> Option<[u8; 4]> { + /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`), and + /// its colour moved `rock` (0–255) of the way to its rock colour (its `rock`, see [`Rock::share`]). + pub fn color_lit(&self, vals: &[f32], hillshade: Option, ambient: Option, rock: Option) -> Option<[u8; 4]> { // The renderer masks values as it samples them (they arrive as NaN); this is for other callers. let mask = &self.style.mask; if mask.is_empty() || !vals.iter().any(|v| mask.hides(*v)) { - return self.paint(vals, hillshade, ambient); + return self.paint(vals, hillshade, ambient, rock); } // Masked values are no data. The renderer bands are at most three. let mut kept = [f32::NAN; 3]; @@ -1943,10 +1973,10 @@ impl<'a> Colorizer<'a> { *k = *v; } } - self.paint(kept.get(..vals.len().min(3)).unwrap_or(&kept), hillshade, ambient) + self.paint(kept.get(..vals.len().min(3)).unwrap_or(&kept), hillshade, ambient, rock) } - fn paint(&self, vals: &[f32], hillshade: Option, ambient: Option) -> Option<[u8; 4]> { + fn paint(&self, vals: &[f32], hillshade: Option, ambient: Option, rock: Option) -> Option<[u8; 4]> { let v0 = *vals.first()?; let c = match &self.style.renderer { RasterRenderer::Rgb { .. } => { @@ -1973,9 +2003,14 @@ impl<'a> Colorizer<'a> { } *self.palette.get(i as usize)? } - RasterRenderer::ShadedRelief { ramp, .. } => { + RasterRenderer::ShadedRelief { ramp, rock: steep, .. } => { let h = hillshade.unwrap_or(180) as f64 / 255.0; let base = if ramp.is_some() { *self.ramp_lut.get(self.byte(0, v0) as usize)? } else { [255, 255, 255, 255] }; + // Steep ground first takes on the rock colour; the light then shades either. + let base = match (steep, rock) { + (Some(steep), Some(share)) if share > 0 => Rgba(base).lerp(steep.color.with_alpha(255), f64::from(share) / 255.0).0, + _ => base, + }; // Multiply the tint by the hillshade, keeping some ambient light (less of it where // the terrain hides part of the sky). let a = 0.25 * ambient.map_or(1.0, |a| f64::from(a) / 255.0); @@ -1987,11 +2022,24 @@ impl<'a> Colorizer<'a> { } } -/// Hillshade (0–255) from a 3×3 window of elevations (row by row), Horn's method. -pub fn hillshade(z: &[f64; 9], cell_x: f64, cell_y: f64, azimuth: f64, altitude: f64, z_factor: f64) -> u8 { +/// The slope (degrees) of a 3×3 window of elevations (row by row), from the gradient +/// [`hillshade`] uses: the ground's own, with no Z factor. +pub fn slope(z: &[f64; 9], cell_x: f64, cell_y: f64) -> f64 { + let (dzdx, dzdy) = horn(z, cell_x, cell_y); + dzdx.hypot(dzdy).atan().to_degrees() +} + +/// The east and south gradients of a 3×3 window of elevations, Horn's method. +fn horn(z: &[f64; 9], cell_x: f64, cell_y: f64) -> (f64, f64) { let [a, b, c, d, _, f, g, h, i] = *z; let dzdx = ((c + 2.0 * f + i) - (a + 2.0 * d + g)) / (8.0 * cell_x.max(1e-9)); let dzdy = ((g + 2.0 * h + i) - (a + 2.0 * b + c)) / (8.0 * cell_y.max(1e-9)); + (dzdx, dzdy) +} + +/// Hillshade (0–255) from a 3×3 window of elevations (row by row), Horn's method. +pub fn hillshade(z: &[f64; 9], cell_x: f64, cell_y: f64, azimuth: f64, altitude: f64, z_factor: f64) -> u8 { + let (dzdx, dzdy) = horn(z, cell_x, cell_y); let slope = (z_factor * (dzdx * dzdx + dzdy * dzdy).sqrt()).atan(); let aspect = if dzdx != 0.0 || dzdy != 0.0 { dzdy.atan2(-dzdx) } else { 0.0 }; let zenith = (90.0 - altitude.clamp(0.0, 90.0)).to_radians(); @@ -2295,6 +2343,11 @@ mod tests { use super::*; + /// A Shaded Relief without a ramp or rock, lit from `azimuth` and `altitude`. + fn grey_relief(azimuth: f64, altitude: f64, z_factor: f64, shadow: f64, sky: f64) -> RasterRenderer { + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor, shadow, sky, rock: None } + } + /// The legend names a class as the file does (#889), and gives the value of one it doesn't. #[test] fn legend_labels_classes_with_their_names() { @@ -2781,14 +2834,69 @@ mod tests { assert!(plain.opening.is_none(), "an anonymous web raster is not fetched whole"); } + /// Rock on steep slopes (#1913): the ramp's colour up to `from`, the rock's from `to` on, and a + /// smooth step between them; the slope is the ground's own, which no Z factor changes; and the + /// rock is saved only when set. + #[test] + fn rock_tints_steep_slopes_by_the_grounds_own_slope() { + let rock = Rock { from: 20.0, to: 40.0, color: Rgba::rgb(200, 100, 50) }; + assert_eq!((rock.share(0.0), rock.share(20.0), rock.share(40.0), rock.share(70.0)), (0.0, 0.0, 1.0, 1.0)); + assert!((rock.share(30.0) - 0.5).abs() < 1e-12); + let (a, b) = (rock.share(22.0), rock.share(25.0)); + assert!(0.0 < a && a < b && b < 0.5, "a smooth step, slow at its ends: {a}, {b}"); + // A plane rising one metre a metre eastward is 45 degrees, whatever the light's Z factor. + let z = [0.0, 10.0, 20.0, 0.0, 10.0, 20.0, 0.0, 10.0, 20.0]; + assert!((slope(&z, 10.0, 10.0) - 45.0).abs() < 1e-9); + assert_ne!(hillshade(&z, 10.0, 10.0, 270.0, 45.0, 1.0), hillshade(&z, 10.0, 10.0, 270.0, 45.0, 3.0)); + + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = + Raster::new("dem", 10, 10, vec![(0..100).map(|v| v as f32).collect()], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32") + .unwrap(); + let relief = |rock| RasterRenderer::ShadedRelief { + band: 0, + ramp: Some(Ramp::Terrain), + azimuth: 315.0, + altitude: 45.0, + z_factor: 1.0, + shadow: 0.0, + sky: 0.0, + rock, + }; + let (mut rocky, mut plain) = (RasterStyle::default_for(&r), RasterStyle::default_for(&r)); + (rocky.renderer, plain.renderer) = (relief(Some(rock)), relief(None)); + let (with, without) = (Colorizer::new(&rocky, &r, None), Colorizer::new(&plain, &r, None)); + for (v, h) in [(10.0, 0), (50.0, 128), (90.0, 255)] { + let plain = without.color_lit(&[v], Some(h), None, None); + assert_eq!(with.color_lit(&[v], Some(h), None, None), plain, "no share of rock: the ramp"); + assert_eq!(with.color_lit(&[v], Some(h), None, Some(0)), plain, "flat ground: the ramp"); + assert_eq!(without.color_lit(&[v], Some(h), None, Some(255)), plain, "no rock set: the ramp"); + // All rock: the rock colour, lit as the ramp is (a quarter ambient, the rest the sun). + let lit = |c: u8| (f64::from(c) * (0.25 + 0.75 * f64::from(h) / 255.0)).round() as u8; + assert_eq!(with.color_lit(&[v], Some(h), None, Some(255)), Some([lit(200), lit(100), lit(50), 255])); + // Half way: half way between the two colours. + let half = with.color_lit(&[v], Some(255), None, Some(128)).unwrap(); + let ramp = without.color_lit(&[v], Some(255), None, None).unwrap(); + for (k, end) in [200u8, 100, 50].into_iter().enumerate() { + let mid = (f64::from(ramp[k]) + f64::from(end)) / 2.0; + assert!((f64::from(half[k]) - mid).abs() <= 1.5, "{v}: channel {k} {} not near {mid}", half[k]); + } + } + + // Saved only when set, and read back as it was. + let saved = serde_json::to_string(&relief(None)).unwrap(); + assert!(!saved.contains("rock"), "{saved}"); + let saved = serde_json::to_string(&relief(Some(rock))).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap(), relief(Some(rock))); + } + /// A tower lit from the east, drawn as Shaded Relief with `shadow`. fn tower(shadow: f64) -> RasterLayer { let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 30.0, pixel_height: -30.0 }; let data: Vec = (0..400).map(|i| if i == 10 * 20 + 10 { 900.0 } else { 0.0 }).collect(); let r = Raster::new("tower", 20, 20, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "tower.tif"); - rl.style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 90.0, altitude: 30.0, z_factor: 1.0, shadow, sky: 0.0 }; + rl.style.renderer = grey_relief(90.0, 30.0, 1.0, shadow, 0.0); rl } @@ -2846,8 +2954,7 @@ mod tests { let r = Raster::new("hills", 1200, 1200, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "hills.tif"); let lit = |rl: &mut RasterLayer, az: f64| { - rl.style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: az, altitude: 10.0, z_factor: 1.0, shadow: 1.0, sky: 0.0 }; + rl.style.renderer = grey_relief(az, 10.0, 1.0, 1.0, 0.0); }; let other = |az: f64, rl: &RasterLayer| { let mut c = rl.clone(); @@ -2906,8 +3013,7 @@ mod tests { let data: Vec = (0..2000 * 2000).map(|i| ((i % 2000) as f32 * 0.01) + ((i / 2000) as f32 * 0.01)).collect(); let r = Raster::new("plain", 2000, 2000, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "plain.tif"); - rl.style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 135.0, altitude: 2.0, z_factor: 1.0, shadow: 1.0, sky: 0.0 }; + rl.style.renderer = grey_relief(135.0, 2.0, 1.0, 1.0, 0.0); let (sent, landings) = std::sync::mpsc::channel::<()>(); { let _cancelled = rustgis_data::progress::install(Some(std::sync::Arc::new(Cancelled))); @@ -2935,8 +3041,7 @@ mod tests { let data: Vec = (0..800 * 800).map(|i| ((i % 800) as f32 * 0.01) + ((i / 800) as f32 * 0.01)).collect(); let r = Raster::new("plain", 800, 800, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut rl = RasterLayer::from_path(r, "plain.tif"); - rl.style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 135.0, altitude: 3.0, z_factor: 1.0, shadow: 1.0, sky: 0.0 }; + rl.style.renderer = grey_relief(135.0, 3.0, 1.0, 1.0, 0.0); let (sent, landings) = std::sync::mpsc::channel::<&'static str>(); let told = |who: &'static str| { let tx = sent.clone(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 0a3d06d90c..b9d70351f8 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -3681,6 +3681,7 @@ mod tests { z_factor: 1.0, shadow, sky: 0.0, + rock: None, }; for shadow in [0.0, 1.0] { let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); @@ -3730,6 +3731,7 @@ mod tests { z_factor: 1.0, shadow: 1.0, sky: 0.0, + rock: None, }; let mut m = Map::new(name.clone()); assert_eq!(m.add_raster("dem", copy), 1); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 46d6c8f485..1bf1bd5a26 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8850,6 +8850,7 @@ mod tests { z_factor: 1.0, shadow, sky: 0.0, + rock: None, }; }; let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1200.0, bearing: 0.0, pitch: 0.0 }; @@ -8883,6 +8884,7 @@ mod tests { z_factor: 1.0, shadow: 1.0, sky: 0.0, + rock: None, }; // Drawn only zoomed out past a scale between the centre's and the far band's. l.max_scale = Some((centre + farthest) / 2.0); @@ -8926,6 +8928,7 @@ mod tests { z_factor: 1.0, shadow: 1.0, sky: 0.0, + rock: None, }; // Drawn only zoomed in past 1:1: or in a group drawn only there. if grouped { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 5954d7e354..351e3ae85f 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -10,7 +10,7 @@ use rustgis_data::raster::{BandStats, ColorHint, Raster}; use rustgis_geom::{Coord, Extent, extent_to_merc}; use rustgis_map::Globe; use rustgis_map::projection::Flat; -use rustgis_map::raster::{Colorizer, RasterMask, RasterRenderer, RasterStyle, Resampling, hillshade}; +use rustgis_map::raster::{Colorizer, RasterMask, RasterRenderer, RasterStyle, Resampling, Rock, hillshade, slope}; use tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform}; use crate::View; @@ -491,6 +491,11 @@ fn draw_with( RasterRenderer::ShadedRelief { shadow, sky, .. } => (lit_by(light.shadow, shadow, cells), lit_by(light.sky, sky, cells)), _ => (None, None), }; + // Steep slopes tinted toward rock, before the light. + let rock = match style.renderer { + RasterRenderer::ShadedRelief { rock, .. } => rock, + _ => None, + }; // Blending neighbours would invent values that aren't classes or palette entries. let resampling = match style.renderer { RasterRenderer::UniqueValues { .. } | RasterRenderer::Colormap => Resampling::Nearest, @@ -521,6 +526,7 @@ fn draw_with( relief, shadow, sky, + rock, resampling, alpha_band, alpha_max: rustgis_data::raster::alpha_max(&r.data_type), @@ -532,6 +538,7 @@ fn draw_with( let mut shade = if relief.is_some() { vec![0u8; bw * bh] } else { Vec::new() }; let mut alpha = if alpha_band.is_some() { vec![0u8; bw * bh] } else { Vec::new() }; let mut ambient = if sky.is_some() { vec![255u8; bw * bh] } else { Vec::new() }; + let mut rocky = if relief.is_some() && rock.is_some() { vec![0u8; bw * bh] } else { Vec::new() }; let threads = threads.clamp(1, bh); let rows = bh.div_ceil(threads.max(1)); each_chunk( @@ -540,8 +547,9 @@ fn draw_with( .zip(chunks_or_empty(&mut shade, rows * bw)) .zip(chunks_or_empty(&mut alpha, rows * bw)) .zip(chunks_or_empty(&mut ambient, rows * bw)) + .zip(chunks_or_empty(&mut rocky, rows * bw)) .enumerate(), - |(i, (((v, sh), al), am))| pass1.rows(y0 + i * rows, v, sh, al, am), + |(i, ((((v, sh), al), am), ro))| pass1.rows(y0 + i * rows, v, sh, al, am, ro), ); // Dynamic range adjustment: statistics of the values in view. @@ -551,19 +559,19 @@ fn draw_with( // Pass 2: colours, premultiplied, into a pixmap the size of the raster's screen box. let Some(mut lay) = Pixmap::new(bw as u32, bh as u32) else { return }; - let (vals, shade, alpha, ambient) = (&vals, &shade, &alpha, &ambient); + let (vals, shade, alpha, ambient, rocky) = (&vals, &shade, &alpha, &ambient, &rocky); each_chunk(threads, lay.data_mut().chunks_mut(rows * bw * 4).enumerate(), |(ci, out)| { let first = ci * rows * bw; // Neighbouring pixels often share their values (zoomed in, or classes): colour once. - let mut last: Option<(&[f32], [Option; 3], Option<[u8; 4]>)> = None; + let mut last: Option<(&[f32], [Option; 4], Option<[u8; 4]>)> = None; for (j, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { let i = first + j; let Some(v) = vals.get(i * nb..(i + 1) * nb) else { continue }; - let (sh, al, am) = (shade.get(i).copied(), alpha.get(i).copied(), ambient.get(i).copied()); + let (sh, al, am, ro) = (shade.get(i).copied(), alpha.get(i).copied(), ambient.get(i).copied(), rocky.get(i).copied()); let c = match last { - Some((lv, l, c)) if l == [sh, al, am] && same(lv, v) => c, + Some((lv, l, c)) if l == [sh, al, am, ro] && same(lv, v) => c, _ => { - let c = colorizer.color_lit(v, sh, am).map(|mut c| { + let c = colorizer.color_lit(v, sh, am, ro).map(|mut c| { if let Some(a) = al { c[3] = ((c[3] as u16 * a as u16 + 127) / 255) as u8; } @@ -571,7 +579,7 @@ fn draw_with( let pm = |x: u8| ((x as u16 * a + 127) / 255) as u8; [pm(c[0]), pm(c[1]), pm(c[2]), c[3]] }); - last = Some((v, [sh, al, am], c)); + last = Some((v, [sh, al, am, ro], c)); c } }; @@ -657,6 +665,8 @@ struct Pass1<'a> { shadow: Option<(&'a [u8], f64)>, /// The share of the sky each cell sees, and how much it scales the ambient light (0 to 1). sky: Option<(&'a [u8], f64)>, + /// Shaded Relief's rock on steep slopes, when it has one. + rock: Option, resampling: Resampling, alpha_band: Option, /// The alpha band's opaque value (its pixel type's: 65535 for 16 bits). @@ -670,9 +680,9 @@ struct Pass1<'a> { } impl Pass1<'_> { - /// Fills the band values (and hillshade, alpha and ambient light, when kept) of the screen rows - /// from `py0` on, as many as `vals` holds. - fn rows(&self, py0: usize, vals: &mut [f32], shade: &mut [u8], alpha: &mut [u8], ambient: &mut [u8]) { + /// Fills the band values (and hillshade, alpha, ambient light and share of rock, when kept) of + /// the screen rows from `py0` on, as many as `vals` holds. + fn rows(&self, py0: usize, vals: &mut [f32], shade: &mut [u8], alpha: &mut [u8], ambient: &mut [u8], rocky: &mut [u8]) { let (r, bw, nb) = (self.r, self.bw, self.bands.len().max(1)); let lerp = |p: f64, q: f64, t: f64| p + (q - p) * t; // Each grid column's source position at this row, interpolated down the grid. @@ -810,6 +820,9 @@ impl Pass1<'_> { { *a = light.ambient.round().clamp(0.0, 255.0) as u8; } + if let Some(ro) = rocky.get_mut(i) { + *ro = light.rock.round().clamp(0.0, 255.0) as u8; + } } } } @@ -817,7 +830,8 @@ impl Pass1<'_> { /// The lights on the relief's cell `(ci, ri)`, from 0 to 255 and not rounded: the direct /// light, the hillshade of its 3 × 3 window times what the cast shadows leave on it; and the - /// ambient light, scaled by the sky the cell sees. `centre` is the cell's height, and stands in + /// ambient light, scaled by the sky the cell sees; and its share of rock (see [`Rock::share`]), + /// from the ground's own slope in the same window. `centre` is the cell's height, and stands in /// for a neighbour that is no data, masked or outside the grid. Every light a cell gets is /// worked out here, so that [`blend`] smooths each of them. fn light(&self, band: usize, (az, alt, zf): (f64, f64, f64), (ci, ri): (i64, i64), centre: f64) -> Lit { @@ -836,7 +850,8 @@ impl Pass1<'_> { if let Some(left) = left(self.shadow) { direct *= left; } - Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0) } + let rock = self.rock.map_or(0.0, |rock| rock.share(slope(&z, self.cell.0, self.cell.1)) * 255.0); + Lit { direct, ambient: left(self.sky).map_or(255.0, |left| left * 255.0), rock } } /// The lights of the cell `(i, j)`, or none when it is no data, masked or outside the grid; a @@ -862,6 +877,8 @@ impl Pass1<'_> { struct Lit { direct: f64, ambient: f64, + /// Its share of rock, 0 to 255: not a light, but blended as the lights are. + rock: f64, } /// The four cells' lights of [`Pass1::quad_lights`] blended bilinearly at `(fx, fy)` (0 to 1) @@ -871,15 +888,16 @@ struct Lit { /// with a weight has lights. fn blend(lights: [Option; 4], fx: f64, fy: f64) -> Option { let weights = [(1.0 - fx) * (1.0 - fy), fx * (1.0 - fy), (1.0 - fx) * fy, fx * fy]; - let (mut direct, mut ambient, mut total) = (0.0, 0.0, 0.0); + let (mut direct, mut ambient, mut rock, mut total) = (0.0, 0.0, 0.0, 0.0); for (light, w) in lights.into_iter().zip(weights) { if let Some(light) = light { direct += w * light.direct; ambient += w * light.ambient; + rock += w * light.rock; total += w; } } - (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total }) + (total > 0.0).then(|| Lit { direct: direct / total, ambient: ambient / total, rock: rock / total }) } /// Whether two pixels' band values are the same (NaN, no data, equal to itself). @@ -942,6 +960,11 @@ mod tests { use super::*; + /// A Shaded Relief without a ramp or rock, lit from `azimuth` and `altitude`. + fn grey_relief(azimuth: f64, altitude: f64, z_factor: f64, shadow: f64, sky: f64) -> RasterRenderer { + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor, shadow, sky, rock: None } + } + /// A raster turned by a hair either side of none isn't turned: it is drawn at the view's /// resolution, not from its overview. #[test] @@ -1023,8 +1046,16 @@ mod tests { .collect(); let r = Raster::new("relief", 10, 10, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 0.0 }; + style.renderer = RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth, + altitude: 45.0, + z_factor: 1.0, + shadow: 0.0, + sky: 0.0, + rock: None, + }; style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); @@ -1057,8 +1088,7 @@ mod tests { let data = [0.0, 1_000_000.0, 2_000_000.0, 3_000_000.0].repeat(18); let r = Raster::new("regional relief", 4, 18, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = Resampling::Nearest; let view = View { width: 1.0, @@ -1097,8 +1127,7 @@ mod tests { let dark = vec![0u8; 4 * 18]; let drawn = |shadow: f64, light: Option<&[u8]>| { let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, 0.0); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); draw( @@ -1150,8 +1179,7 @@ mod tests { let (none, dark) = (vec![0u8; 4 * 18], vec![0u8; 4 * 18]); let drawn = |shadow: f64, sky: f64, light: Lights| { let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, sky); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), light); @@ -1164,9 +1192,8 @@ mod tests { assert_eq!(drawn(0.0, 1.0, Lights::default()), today, "no grid"); // No sky at all: the direct light alone. let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 1.0 }; - let want = Colorizer::new(&style, &r, None).color_lit(&[0.0], Some(lit), Some(0)).unwrap(); + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 1.0); + let want = Colorizer::new(&style, &r, None).color_lit(&[0.0], Some(lit), Some(0), None).unwrap(); assert_eq!(drawn(0.0, 1.0, hidden), want); assert!(want[0] < today[0]); // In full shadow only the ambient light is left: a quarter of the colour, scaled by the @@ -1218,8 +1245,7 @@ mod tests { let data: Vec = (0..36 * 18).map(|i| elevations[(i % 36 + shift) % 36]).collect(); let r = Raster::new("relief", 36, 18, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(80, 40).unwrap(); draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); @@ -1305,15 +1331,7 @@ mod tests { "rgb" => RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, "classify" => rustgis_map::raster::classify(&r, 0, 5, Default::default(), Default::default()), "unique" => rustgis_map::raster::unique_values(&r, 0, Default::default()), - _ => RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 315.0, - altitude: 45.0, - z_factor: 1.0, - shadow: 0.0, - sky: 0.0, - }, + _ => grey_relief(315.0, 45.0, 1.0, 0.0, 0.0), }; s.dra = true; s.resampling = Resampling::Bilinear; @@ -1331,15 +1349,7 @@ mod tests { let mut s = style.clone(); s.renderer = match kind { "rgb" => RasterRenderer::Rgb { red: 0, green: 0, blue: 0 }, - "shadedRelief" => RasterRenderer::ShadedRelief { - band: 0, - ramp: None, - azimuth: 315.0, - altitude: 45.0, - z_factor: 1.0, - shadow: 0.0, - sky: 0.0, - }, + "shadedRelief" => grey_relief(315.0, 45.0, 1.0, 0.0, 0.0), _ => s.renderer, }; let mut one = Pixmap::new(420, 300).unwrap(); @@ -1474,7 +1484,7 @@ mod tests { let mut style = RasterStyle::default_for(&r); let full = |grid: Option<&[u8]>| if grid.is_some() { 1.0 } else { 0.0 }; let (shadow, sky) = (full(light.shadow), full(light.sky)); - style.renderer = RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow, sky }; + style.renderer = grey_relief(270.0, 45.0, 1.0, shadow, sky); style.resampling = resampling; style.mask = RasterMask { values: mask.to_vec(), ..RasterMask::default() }; let view = View { @@ -1489,6 +1499,67 @@ mod tests { (0..600).map(|x| pm.pixel(x, 0).filter(|p| p.alpha() > 0).map(|p| p.red())).collect() } + /// The middle row of a white relief rising eastward (cells 100 m, slopes of 0, 5.7, 16.7, 26.6, + /// 35 and 21.8 degrees), lit from the west with `rock` and `z_factor`, as each pixel's colour. + fn rock_row(resampling: Resampling, rock: Option, z_factor: f64) -> Vec<[u8; 3]> { + let gt = GeoTransform { origin_x: 0.0, origin_y: 300.0, pixel_width: 100.0, pixel_height: -100.0 }; + let data = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0].repeat(3); + let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut style = RasterStyle::default_for(&r); + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor, shadow: 0.0, sky: 0.0, rock }; + style.resampling = resampling; + let view = View { + width: 600.0, + height: 1.0, + pixels_per_point: 1.0, + camera: Camera { center: Coord::new(300.5, 150.0), res: 1.0, bearing: 0.0, pitch: 0.0 }, + sky: false, + }; + let mut pm = Pixmap::new(600, 1).unwrap(); + draw(&mut pm, &r, &style, None, &view, 1.0, false, Place::Flat(&Flat::Mercator, "mercator"), Lights::default()); + (0..600).map(|x| pm.pixel(x, 0).map_or([0; 3], |p| [p.red(), p.green(), p.blue()])).collect() + } + + /// Rock on steep slopes (#1913) tints by the ground's own slope before the light: the cells + /// below `from` keep today's pixels, those past `to` are the rock colour lit, those between + /// lean toward it; a Z factor changes the light, not the tint; and Bilinear blends the tint + /// between cell centres as it blends the light. + #[test] + fn rock_tints_steep_slopes_before_the_light() { + let rock = Rock { from: 10.0, to: 30.0, color: rustgis_map::Rgba::rgb(200, 100, 50) }; + let plain = rock_row(Resampling::Nearest, None, 1.0); + let rocky = rock_row(Resampling::Nearest, Some(rock), 1.0); + let centre = |row: &[[u8; 3]], k: usize| row[100 * k + 49]; + // Green over red: 1 on the white relief, 0.5 on the rock, whatever the light. + let tint = |c: [u8; 3]| f64::from(c[1]) / f64::from(c[0]); + for k in [0, 1] { + assert_eq!(centre(&rocky, k), centre(&plain, k), "cell {k} is below from"); + } + assert!((tint(centre(&rocky, 4)) - 0.5).abs() < 0.02, "cell 4 is past to: {:?}", centre(&rocky, 4)); + for k in [2, 3, 5] { + let t = tint(centre(&rocky, k)); + assert!(0.52 < t && t < 0.98, "cell {k} leans toward rock: {t}"); + } + assert!(tint(centre(&rocky, 2)) > tint(centre(&rocky, 3)), "steeper, more rock"); + // Three times the Z factor: other lights, the same tints. + let steeper = rock_row(Resampling::Nearest, Some(rock), 3.0); + for k in 1..6 { + assert_ne!(centre(&steeper, k), centre(&rocky, k), "cell {k}: the light changes"); + assert!((tint(centre(&steeper, k)) - tint(centre(&rocky, k))).abs() < 0.02, "cell {k}: the tint doesn't"); + } + // Bilinear: the tint runs from cell 2's centre to cell 3's, not in a step. + let bilinear = rock_row(Resampling::Bilinear, Some(rock), 1.0); + let tints = |row: &[[u8; 3]]| row[249..=349].iter().map(|c| (tint(*c) * 1000.0).round() as i64).collect::>(); + let mut seen = tints(&bilinear); + // (Each colour channel is rounded to a byte: a tint can step back by a hundredth.) + assert!(seen.windows(2).all(|w| w[1] <= w[0] + 10), "toward more rock all the way: {seen:?}"); + seen.dedup(); + let mut stepped = tints(&rocky); + stepped.dedup(); + assert!(seen.len() > 20 && stepped.len() == 2, "{} tints blended, {} nearest", seen.len(), stepped.len()); + } + /// Bilinear relief blends the four cells' light (#1880): the same as Nearest at each cell's /// centre and in the outer half of the edge cells, and in between from one centre's light to /// the next, not in steps. Nearest keeps one light per cell. @@ -1570,8 +1641,7 @@ mod tests { let data = (0..120).map(|k| (k * 37 % 11) as f32 * 10.0).collect(); let r = Raster::new("relief", 40, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 270.0, altitude: 45.0, z_factor: 1.0, shadow: 0.0, sky: 0.0 }; + style.renderer = grey_relief(270.0, 45.0, 1.0, 0.0, 0.0); style.resampling = resampling; let view = View { width: 24.0, @@ -1611,8 +1681,7 @@ mod tests { }; let row = |resampling: Resampling| { let mut style = RasterStyle::default_for(&r); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 315.0, altitude: 45.0, z_factor: 1.0, shadow: 1.0, sky: 0.0 }; + style.renderer = grey_relief(315.0, 45.0, 1.0, 1.0, 0.0); style.resampling = resampling; let mut pm = Pixmap::new(80, 1).unwrap(); draw( diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index d538fad541..46c56f4501 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -198,6 +198,7 @@ mod tests { z_factor: 1.0, shadow: 1.0, sky: 0.0, + rock: None, }; let e = export(&layer, 2, 2, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); assert!(e.contains("cast shadows") && e.contains("read in place"), "{e}"); @@ -229,6 +230,7 @@ mod tests { z_factor: 1.0, shadow: 1.0, sky: 0.0, + rock: None, }; let _cancelled = rustgis_data::progress::install(Some(std::sync::Arc::new(Cancelled))); let e = export(&layer, 0, 0, 1.0).err().unwrap_or_else(|| panic!("an archive without its shadows")); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 8392ca117b..f278745aec 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -5119,8 +5119,16 @@ mod tests { let r = Raster::new("dem", 4, 4, vec![vec![0.0; 16]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut map = Map::new("Relief"); let id = map.add_raster("dem", RasterLayer::from_path(r, "dem.tif")); - let relief = - |shadow| RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth: 315.0, altitude: 30.0, z_factor: 1.0, shadow, sky: 0.0 }; + let relief = |shadow| RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth: 315.0, + altitude: 30.0, + z_factor: 1.0, + shadow, + sky: 0.0, + rock: None, + }; let set = |map: &mut Map, shadow: f64, visible: bool| { let l = map.layer_mut(id).unwrap(); l.visible = visible; diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index fd2c4f3228..6f637f392d 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -7,7 +7,7 @@ use egui::{Align2, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2}; use rustgis_engine::Session; use rustgis_engine::analysis::{ParamKind, tools}; use rustgis_engine::data::GeometryType; -use rustgis_engine::map::raster::{Normalizer, RasterLegend, RasterStyle}; +use rustgis_engine::map::raster::{Normalizer, RasterLegend, RasterStyle, Rock}; use rustgis_engine::map::symbology::{ ClassRef, ClassStyle, Dash, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, MAX_EXPRESSION_CLASSES, MAX_LABEL, MAX_LINE_MARKER_SIZE, MAX_MARKER_INTERVAL, MAX_STROKE_OFFSET, MAX_STROKE_WIDTH, MAX_STROKES, MIN_MARKER_INTERVAL, OTHER_VALUES, @@ -6732,7 +6732,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { RasterRenderer::Colormap => { ui.label(egui::RichText::new(tl!("Colors from the raster's own color table.")).size(11.5).color(t.text_dim)); } - RasterRenderer::ShadedRelief { band, ramp, azimuth, altitude, z_factor, shadow, sky } => { + RasterRenderer::ShadedRelief { band, ramp, azimuth, altitude, z_factor, shadow, sky, rock } => { let (az, alt, zf, sh, sk, rp) = (*azimuth, *altitude, *z_factor, *shadow, *sky, ramp.as_ref().map(|r| r.name().to_string())); let relief = move |band: usize, az: f64, alt: f64, zf: f64, sh: f64| { let mut p = json!({"type": "shadedRelief", "band": band + 1, "azimuth": az, "altitude": alt, "zFactor": zf, "shadow": sh, "sky": sk}); @@ -6782,6 +6782,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { ui.end_row(); } }); + rock_on_slopes(app, ui, l.id, *rock, relief(*band, az, alt, zf, sh)); let mut tint = ramp.is_some(); if ui.checkbox(&mut tint, tl!("Tint by elevation")).changed() { let mut p = relief(*band, az, alt, zf, sh); @@ -6937,6 +6938,50 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { transparency_row(app, ui, l); } +/// Shaded Relief's Rock on steep slopes (#1913): a check box and, when it is on, the slopes in +/// degrees the rock colour starts and ends at and the colour. `relief` is the layer's Shaded +/// Relief as `raster.symbology` takes it, to which the rock is added. +fn rock_on_slopes(app: &mut RustGisApp, ui: &mut Ui, layer: u32, rock: Option, relief: Value) { + let send = |app: &mut RustGisApp, rock: Value| { + let mut p = relief.clone(); + p["rock"] = rock; + let _ = app.run("raster.symbology", p); + }; + let mut on = rock.is_some(); + if ui + .checkbox(&mut on, tl!("Rock on steep slopes")) + .on_hover_text(tl!("Tints steep ground toward a rock colour before the light shades it, by the ground's own slope")) + .changed() + { + send(app, if on { json!({}) } else { json!(false) }); + } + let Some(rock) = rock else { return }; + egui::Grid::new(("relief_rock", layer)).num_columns(2).spacing(vec2(10.0, 4.0)).show(ui, |ui| { + for (label, v, which) in [("From", rock.from, 0), ("To", rock.to, 1)] { + let input_label = ui.label(tl!(label)); + let mut x = v; + // Kept across a drag until it is let go (#607). + let drag = Dragged::lend(ui, egui::Id::unique(("relief_rock_drag", layer, which)), &mut x); + let r = ui + .add(egui::DragValue::new(&mut x).update_while_editing(false).range(0.0..=90.0).speed(0.5).max_decimals(1).suffix("°")) + .labelled_by(input_label.id); + if drag.settled(ui, &r, &mut x) && x != v { + // The other end moves along rather than cross it. + let (from, to) = + if which == 0 { (x.min(89.0), rock.to.max(x.min(89.0) + 1.0)) } else { (rock.from.min(x.max(1.0) - 1.0), x.max(1.0)) }; + send(app, json!({"from": from, "to": to})); + } + ui.end_row(); + } + let input_label = ui.label(tl!("Color")); + let mut c = egui::Color32::from_rgb(rock.color.r(), rock.color.g(), rock.color.b()); + if crate::widgets::color_button(ui, &mut c).labelled_by(input_label.id).changed() { + send(app, json!({"color": rustgis_engine::map::Rgba::rgb(c.r(), c.g(), c.b()).hex()})); + } + ui.end_row(); + }); +} + /// The Masking section of a raster's symbology (#348): values drawn as no data, and a range of /// values shown. fn raster_masking(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, d: &rustgis_engine::data::raster::Raster, style: &RasterStyle, t: &Tokens) { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index dc67710001..74422ddc47 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1324,8 +1324,20 @@ exports, and said when it can't be drawn (in the browser over 500,000 cells, or GeoTIFF read in place) as cast shadows are. Terrain outside the raster, or farther than 100 cells, hides none of its sky. +**Rock on steep slopes**, on a Shaded Relief layer (`raster.symbology` +`"rock": {"from": 25, "to": 40, "color": "#B2ACA4"}`), tints steep ground toward a rock colour, +so cliffs and scarps stand out from the gentle slopes of the same height. Below **From** degrees +of slope the ramp's colour is kept, above **To** the rock colour is used, and between them the two +are blended on a smooth step. The light (hillshade, cast shadows and sky visibility) then shades +that colour as it shades the ramp. The slope is the ground's own, worked out from the same 3 × 3 +window as the hillshade but without the Z factor, so 35° means 35° whatever the exaggeration +(metres at the cell's latitude for a geographic raster). A 30 m DEM averages a cliff with its +foot, so its walls come out gentler than they are: 25° to 40° suits it, and a finer DEM can start +higher. Missing keys keep the current rock's (or those defaults), and `"rock": false` removes it; +it is off by default and saved with the project only when set. + With **Resampling** set to bilinear, a Shaded Relief layer's light (its hillshade, cast shadows and -sky visibility) is blended between the cells' centres, as its values are, so a cell drawn over many +sky visibility) and its rock tint are blended between the cells' centres, as its values are, so a cell drawn over many pixels shades smoothly instead of in squares; nearest keeps one light per cell, as before. A cell with no data, or masked, is left out of the blend, so it doesn't darken the relief next to it. From edba016b20968af3e3114396878be06246233022 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 14 Nov 2026 15:21:32 -0300 Subject: [PATCH 2/3] fix(render): address the first review round on rock slopes (#1913) - An engine test exports a grey relief with a 63 degree wall and checks the pixels: red on the wall with a red rock, unchanged on the flat half. - hillshade's local `slope` is now `tilt`, so it no longer shadows the `slope` function of the same module. - The bilinear paragraph of the user guide is rewrapped. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 31 +++++++++++++++++++++++++++++-- crates/map/src/raster.rs | 19 +++++++++++++------ crates/render/src/raster.rs | 17 +++++++++++++---- 3 files changed, 55 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cf8b0935f1..59bb371219 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4363,7 +4363,7 @@ fn shaded_relief_keeps_its_fill_light() { /// Shaded Relief's rock on steep slopes (#1913): an object turns it on, its missing keys from the /// current rock or the defaults; kept when left out; `false` removes it; a `from` not below `to` -/// or a bad colour is refused; saved with the project only when set, and drawn in an export. +/// or a bad colour is refused; saved with the project only when set. #[test] fn shaded_relief_keeps_its_rock_on_steep_slopes() { use rustgis_map::raster::Rock; @@ -4387,12 +4387,39 @@ fn shaded_relief_keeps_its_rock_on_steep_slopes() { assert!(s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": bad})).is_err(), "{bad}"); assert_eq!(rock(&s), Some(want), "{bad}: refused, the rock kept"); } - assert!(crate::cmd::share::map_png(&mut s, Some(300.0), Some(200.0), None).unwrap().len() > 1000); s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": false})).unwrap(); assert_eq!(rock(&s), None); assert_eq!(rocks_saved(&mut s), before, "not saved once removed"); } +/// An export draws the rock on steep slopes: a grey relief whose east half is a 63° wall turns +/// red there with a red rock, and keeps the same pixels on the flat west half. +#[test] +fn an_export_draws_the_rock_on_steep_slopes() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + // 41 cells of 30 m a side: flat to column 20, then rising 60 m a cell eastward. + let wall: Vec = (0..41 * 41).map(|i| ((i % 41 - 20).max(0) * 60) as f32).collect(); + let gt = GeoTransform { origin_x: 500_000.0, origin_y: 7_000_000.0, pixel_width: 30.0, pixel_height: -30.0 }; + let r = Raster::new("wall", 41, 41, vec![wall], gt, Crs::from_epsg(31983).unwrap(), None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "wall", rustgis_map::RasterLayer::from_bytes(r, "wall.tif".to_string(), bytes)).unwrap(); + s.run("layer.zoomTo", &json!({"layer": "wall"})).unwrap(); + let drawn = |s: &mut Session, rock: Value| { + s.run("raster.symbology", &json!({"layer": "wall", "type": "shadedRelief", "grey": true, "azimuth": 270, "rock": rock})).unwrap(); + let png = crate::cmd::share::map_png(s, Some(200.0), Some(200.0), None).unwrap(); + crate::render::decode_png(&png).unwrap() + }; + let plain = drawn(&mut s, json!(false)); + let rocky = drawn(&mut s, json!({"from": 10, "to": 20, "color": "#FF0000"})); + let px = |p: &tiny_skia::Pixmap, x: u32| p.pixel(x, 100).map(|c| [c.red(), c.green(), c.blue()]).unwrap(); + // The flat west half: the same grey. The wall: grey without the rock, red with it. + assert_eq!(px(&rocky, 70), px(&plain, 70)); + let ([r0, g0, b0], [r1, g1, b1]) = (px(&plain, 130), px(&rocky, 130)); + assert!(r0 == g0 && g0 == b0 && r0 > 0, "a grey wall: {:?}", [r0, g0, b0]); + assert!(r1 > 0 && g1 == 0 && b1 == 0, "a red wall: {:?}", [r1, g1, b1]); +} + /// An export draws the sky a pit hides: its floor darker with `sky` 1 than with 0, the ground /// around it (which sees the whole sky) the same. The first export with the sky, from a cold /// cache, waits for the grid: it is the same image as one drawn once the grid is kept. diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index eec7572bc5..a0c5a2c1d7 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1962,10 +1962,17 @@ impl<'a> Colorizer<'a> { } /// [`Colorizer::color`], with Shaded Relief's ambient light scaled by `ambient` (0–255, the - /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`), and - /// `fill` (0–255, a share of the colour) added for its fill light (its `fill`), and its colour moved - /// `rock` (0–255) of the way to its rock colour (its `rock`, see [`Rock::share`]). - pub fn color_lit(&self, vals: &[f32], hillshade: Option, ambient: Option, fill: Option, rock: Option) -> Option<[u8; 4]> { + /// share of it the sky a cell sees leaves, see [`RasterRenderer::ShadedRelief`]'s `sky`), + /// `fill` (0–255, a share of the colour) added for its fill light (its `fill`), and its colour + /// moved `rock` (0–255) of the way to its rock colour (its `rock`, see [`Rock::share`]). + pub fn color_lit( + &self, + vals: &[f32], + hillshade: Option, + ambient: Option, + fill: Option, + rock: Option, + ) -> Option<[u8; 4]> { // The renderer masks values as it samples them (they arrive as NaN); this is for other callers. let mask = &self.style.mask; if mask.is_empty() || !vals.iter().any(|v| mask.hides(*v)) { @@ -2046,11 +2053,11 @@ fn horn(z: &[f64; 9], cell_x: f64, cell_y: f64) -> (f64, f64) { /// Hillshade (0–255) from a 3×3 window of elevations (row by row), Horn's method. pub fn hillshade(z: &[f64; 9], cell_x: f64, cell_y: f64, azimuth: f64, altitude: f64, z_factor: f64) -> u8 { let (dzdx, dzdy) = horn(z, cell_x, cell_y); - let slope = (z_factor * (dzdx * dzdx + dzdy * dzdy).sqrt()).atan(); + let tilt = (z_factor * (dzdx * dzdx + dzdy * dzdy).sqrt()).atan(); let aspect = if dzdx != 0.0 || dzdy != 0.0 { dzdy.atan2(-dzdx) } else { 0.0 }; let zenith = (90.0 - altitude.clamp(0.0, 90.0)).to_radians(); let az = (360.0 - azimuth + 90.0).rem_euclid(360.0).to_radians(); - let v = zenith.cos() * slope.cos() + zenith.sin() * slope.sin() * (az - aspect).cos(); + let v = zenith.cos() * tilt.cos() + zenith.sin() * tilt.sin() * (az - aspect).cos(); (v.max(0.0) * 255.0).round().clamp(0.0, 255.0) as u8 } diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 8109f10bcd..dbd4dc9d15 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -693,7 +693,6 @@ struct Pass1<'a> { impl Pass1<'_> { /// Fills the band values (and hillshade, alpha, ambient and fill light and share of rock, when /// kept) of the screen rows from `py0` on, as many as `vals` holds. - #[allow(clippy::too_many_arguments)] fn rows( &self, py0: usize, @@ -1262,8 +1261,17 @@ mod tests { let r = Raster::new("relief", 3, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); let (azimuth, altitude) = (270.0, 45.0); - style.renderer = - RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude, z_factor: 1.0, shadow: 0.0, sky: 0.0, fill, rock: None }; + style.renderer = RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth, + altitude, + z_factor: 1.0, + shadow: 0.0, + sky: 0.0, + fill, + rock: None, + }; style.resampling = Resampling::Nearest; let view = View { width: 1.0, @@ -1595,7 +1603,8 @@ mod tests { let data = [0.0, 0.0, 20.0, 60.0, 120.0, 200.0].repeat(3); let r = Raster::new("relief", 6, 3, vec![data], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); let mut style = RasterStyle::default_for(&r); - style.renderer = RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude: 45.0, z_factor, shadow: 0.0, sky: 0.0, fill, rock }; + style.renderer = + RasterRenderer::ShadedRelief { band: 0, ramp: None, azimuth, altitude: 45.0, z_factor, shadow: 0.0, sky: 0.0, fill, rock }; style.resampling = resampling; let view = View { width: 600.0, From 144d817bd488781fe16adcb077abf6420267e730 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 14 Nov 2026 15:52:58 -0300 Subject: [PATCH 3/3] fix(engine): refuse a rock colour with alpha instead of dropping it (#1913) `raster.symbology`'s rock colour went through `Rgba::from_hex`, which also reads `#RRGGBBAA`, and its alpha was then dropped without a word. A colour that isn't opaque is now refused, as the schema says `#RRGGBB`. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/raster.rs | 5 ++++- crates/engine/src/tests.rs | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c847c7f6c9..efc71bcdc3 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -840,7 +840,10 @@ fn relief_rock(v: &Value, cur: Option) -> Result, String> { if from >= to { return Err(format!("rock's from ({from}°) must be below its to ({to}°)")); } - let color = super::layout::color(v, "color", was.color)?.with_alpha(255); + let color = super::layout::color(v, "color", was.color)?; + if color.a() != 255 { + return Err("rock's color must be #RRGGBB: the rock is opaque".into()); + } Ok(Some(Rock { from, to, color })) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 59bb371219..9c591af191 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4383,7 +4383,9 @@ fn shaded_relief_keeps_its_rock_on_steep_slopes() { let want = Rock { from: 25.0, to: 50.0, color: rustgis_map::Rgba::rgb(0x80, 0x60, 0x40) }; assert_eq!(rock(&s), Some(want), "left out, kept; its missing keys too"); assert_eq!(rocks_saved(&mut s), before + 1, "saved when set"); - for bad in [json!({"from": 40, "to": 30}), json!({"from": 30, "to": 30}), json!({"color": "rock"}), json!(3)] { + for bad in + [json!({"from": 40, "to": 30}), json!({"from": 30, "to": 30}), json!({"color": "rock"}), json!({"color": "#B2ACA480"}), json!(3)] + { assert!(s.run("raster.symbology", &json!({"type": "shadedRelief", "rock": bad})).is_err(), "{bad}"); assert_eq!(rock(&s), Some(want), "{bad}: refused, the rock kept"); }