diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index e6536a90df..b66453217f 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -486,7 +486,7 @@ raster.rotation layer? angle raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? resampling? reset? raster.spectral layer lon? lat? points? zone? raster.stretch layer? type low? high? n? min? max? like? -raster.symbology layer? type band? ramp? invert? classes? method? azimuth? altitude? zFactor? shadow? sky? fill? ambient? balanced? rock? grey? +raster.symbology layer? type band? ramp? invert? classes? method? azimuth? altitude? zFactor? shadow? sky? fill? ambient? balanced? shadowSoftness? rock? grey? raster.zarrInfo path url bbox? variable? report.activate report report.attachments report? field diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index de03019725..a092a6a1ce 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -39,7 +39,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|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "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), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "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)}"#, + 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), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "shadowSoftness"?: 0.5..15|null (shadedRelief: how soft the edges of its cast shadows are, as half the sun's apparent size in degrees; left out, kept; outside 0.5 to 15, refused; null, the default: 5), "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) @@ -1034,13 +1034,13 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { RasterRenderer::Colormap } "shadedrelief" | "hillshade" => { - // Left out, a Shaded Relief keeps its own shadows, sky, fill light, rock, ambient - // and balanced light; a new one has none (and the default ambient). - let (cur_shadow, cur_sky, cur_fill, cur_rock, cur_ambient, cur_balanced) = match rl.style.renderer { - RasterRenderer::ShadedRelief { shadow, sky, fill, rock, ambient, balanced, .. } => { - (shadow, sky, fill, rock, ambient, balanced) + // Left out, a Shaded Relief keeps its own shadows (and their softness), sky, fill + // light, rock, ambient and balanced light; a new one has none (and the defaults). + let (cur_shadow, cur_sky, cur_fill, cur_rock, cur_ambient, cur_balanced, cur_softness) = match rl.style.renderer { + RasterRenderer::ShadedRelief { shadow, sky, fill, rock, ambient, balanced, shadow_softness, .. } => { + (shadow, sky, fill, rock, ambient, balanced, shadow_softness) } - _ => (0.0, 0.0, 0.0, None, None, false), + _ => (0.0, 0.0, 0.0, None, None, false, None), }; RasterRenderer::ShadedRelief { band: bi, @@ -1062,6 +1062,11 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { Some(_) => Some(f(p, "ambient").ok_or("\"ambient\" must be a number from 0 to 1, or null")?.clamp(0.0, 1.0)), }, balanced: b(p, "balanced").unwrap_or(cur_balanced), + shadow_softness: match p.get("shadowSoftness") { + None => cur_softness, + Some(Value::Null) => None, + Some(_) => relief_shadow_softness(f(p, "shadowSoftness"))?, + }, } } other => return Err(format!("unknown raster symbology '{other}'")), @@ -1075,6 +1080,19 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { }) } +/// A Shaded Relief's `"shadowSoftness"` (see `raster.symbology`), `v` being the number given, if +/// it is one: refused by name outside the range, never brought into it. The default's own value +/// is kept as none, so a project that sets nothing new saves as it did. +fn relief_shadow_softness(v: Option) -> Result, String> { + use rustgis_map::shadow::{SOFT_EDGE, SOFT_EDGE_MAX, SOFT_EDGE_MIN}; + match v { + Some(v) if (SOFT_EDGE_MIN..=SOFT_EDGE_MAX).contains(&v) => Ok(Some(v).filter(|v| *v != SOFT_EDGE)), + _ => Err(format!( + "\"shadowSoftness\" must be a number of degrees from {SOFT_EDGE_MIN} to {SOFT_EDGE_MAX}, or null for the default ({SOFT_EDGE})" + )), + } +} + /// 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> { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 434a272492..83fc51ea45 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -130,6 +130,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-text-statistics", "layout-publication-parts", "layout-publication-legend", + "shaded-relief-shadow-softness", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index ab5a6b486d..48cbb27b53 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -181,6 +181,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-text-statistics", command_uses_text_statistics), ("layout-publication-parts", command_sets_publication_parts), ("layout-publication-legend", command_sets_publication_legend), + ("shaded-relief-shadow-softness", command_sets_shadow_softness), ]; /// A saved `layout.publication` that leaves out or sets up its grid, scale bar or north arrow @@ -213,6 +214,17 @@ fn command_sets_publication_legend(id: &str, params: &Value) -> bool { } } +/// A saved `raster.symbology` that sets a Shaded Relief's shadow softness (#3144): an older reader +/// runs it without the key, saying nothing, so the shadows would be traced at the default disc. +/// `null` asks for that default. +fn command_sets_shadow_softness(id: &str, params: &Value) -> bool { + match id { + "raster.symbology" => params.get("shadowSoftness").is_some_and(|v| !v.is_null()), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_sets_shadow_softness)), + _ => false, + } +} + /// A saved `labels.placement` that has a class remove duplicates, read as the command reads it /// (#2847): an older reader runs it without the key, saying nothing, so every label would show. /// False or null is what an older reader keeps. @@ -953,6 +965,15 @@ fn relief_light(layer: &Layer) -> bool { ) } +/// Whether a layer sets how soft its Shaded Relief's cast shadows are (#3144): an older reader +/// would trace them at the default and save the layer again without the setting. +fn sets_shadow_softness(layer: &Layer) -> bool { + layer + .raster + .as_ref() + .is_some_and(|r| matches!(&r.style.renderer, RasterRenderer::ShadedRelief { shadow_softness, .. } if shadow_softness.is_some())) +} + /// Whether a layer is a window of a Zarr variable following the time slider (#1720): an older /// reader would drop the window and read the whole map at each step. fn zarr_window(layer: &Layer) -> bool { @@ -995,6 +1016,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ (relief_effects(layer), "shaded-relief-effects"), (relief_light(layer), "shaded-relief-light"), + (sets_shadow_softness(layer), "shaded-relief-shadow-softness"), (layer.size_by.is_some(), super::SIZE_BY_CAPABILITY), (layer.has_picture_markers(), "picture-markers"), (layer.any_picture(svg_picture), "svg-markers"), @@ -1031,7 +1053,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) = (false, false); + let (mut crisp, mut bed, mut soft) = (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. @@ -1066,6 +1088,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static } relief |= map.layers.iter().any(relief_effects); light |= map.layers.iter().any(relief_light); + soft |= map.layers.iter().any(sets_shadow_softness); sized |= map.layers.iter().any(|layer| layer.size_by.is_some()); pictures |= map.layers.iter().any(Layer::has_picture_markers); svg |= map.layers.iter().any(|layer| layer.any_picture(svg_picture)); @@ -1086,6 +1109,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (walls_layer, "terrain-block-walls-layer"), (relief, "shaded-relief-effects"), (light, "shaded-relief-light"), + (soft, "shaded-relief-shadow-softness"), (legends, "normalized-legend-urls"), (sized, super::SIZE_BY_CAPABILITY), (pictures, "picture-markers"), @@ -1548,6 +1572,9 @@ mod tests { (&["layout-text-statistics"], "layout.addElement", json!({"kind": "text", "text": "{count:Cities}"})), (&["layout-publication-parts"], "layout.publication", json!({"grid": "none"})), (&["layout-publication-legend"], "layout.publication", json!({"legend": "none"})), + (&["shaded-relief-shadow-softness"], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": 1.5})), + // `null` is the default an older reader draws. + (&[], "raster.symbology", json!({"type": "shadedRelief", "shadowSoftness": null})), // An SVG image is a picture marker as well, in a node as in a saved command. (&["picture-markers", "svg-markers"], "layer.marker", json!({"image": svg})), (&[], "buffer", json!({"input": "Cities", "distance": 1})), @@ -3167,7 +3194,7 @@ mod tests { })) .unwrap(); let clean = Layer::new_raster(1, "DEM", raster); - for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced"] { + for field in ["shadow", "sky", "fill", "rock", "ambient", "balanced", "shadow_softness"] { let mut value = serde_json::to_value(&clean).unwrap(); value["raster"]["style"]["renderer"]["ShadedRelief"][field] = match field { "rock" => serde_json::to_value(rustgis_map::raster::Rock::DEFAULT).unwrap(), @@ -3182,7 +3209,11 @@ mod tests { json_bytes(&map_file_bytes(p.map()).unwrap()), json_bytes(&layer_file_bytes(&layer).unwrap()), ] { - let needs = if matches!(field, "ambient" | "balanced") { "shaded-relief-light" } else { "shaded-relief-effects" }; + let needs = match field { + "ambient" | "balanced" => "shaded-relief-light", + "shadow_softness" => "shaded-relief-shadow-softness", + _ => "shaded-relief-effects", + }; assert_eq!(document["requires"], json!([needs]), "{field}: {document}"); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index acc58a9f9a..d979a7bdcf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7804,6 +7804,58 @@ fn shaded_relief_keeps_its_ambient_and_balanced_light() { assert_eq!(light(&t), (Some(0.35), true), "back when opened"); } +/// Shaded Relief's shadow softness (#3144) is set, kept when left out, refused by name outside its +/// range (never brought into it), saved only when set, and back when the project is opened again; +/// null, or the default's own value, is the default again, which saves nothing new. +#[test] +fn shaded_relief_keeps_its_shadow_softness() { + let mut s = with_raster(); + let softness = |s: &Session| match s.map().layers.iter().find_map(|l| l.raster.as_ref()).map(|r| &r.style.renderer) { + Some(rustgis_map::RasterRenderer::ShadedRelief { shadow_softness, .. }) => *shadow_softness, + other => panic!("{other:?}"), + }; + let saved = |s: &mut Session| s.project.saved_text(None).unwrap().0; + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadow": 0.8})).unwrap(); + assert_eq!(softness(&s), None); + assert!(!saved(&mut s).contains("shadow_softness") && !saved(&mut s).contains("shaded-relief-shadow-softness")); + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 1.5})).unwrap(); + s.run("raster.symbology", &json!({"type": "shadedRelief", "azimuth": 200})).unwrap(); + assert_eq!(softness(&s), Some(1.5), "left out, kept"); + for refused in [json!(0.4), json!(15.5), json!(-1), json!("soft"), json!(true)] { + let e = s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": refused})).unwrap_err(); + assert!(e.contains("\"shadowSoftness\"") && e.contains("0.5 to 15"), "{refused}: {e}"); + assert_eq!(softness(&s), Some(1.5), "{refused}: refused, nothing changed"); + } + for bound in [0.5, 15.0] { + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": bound})).unwrap(); + assert_eq!(softness(&s), Some(bound)); + } + let text = saved(&mut s); + assert!(text.contains("\"shadow_softness\":15.0") && text.contains("shaded-relief-shadow-softness"), "saved, and required by name"); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = std::env::temp_dir().join(format!("rustgis-softness-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("softness.rgis"); + s.run("project.saveAs", &json!({"path": path.display().to_string()})).unwrap(); + let mut t = Session::new(Project::default()); + t.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(softness(&t), Some(15.0), "back when opened"); + for default in [json!(null), json!(5)] { + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 2})).unwrap(); + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": default})).unwrap(); + assert_eq!(softness(&s), None, "{default}: the default"); + } + s.run("raster.symbology", &json!({"type": "shadedRelief", "shadowSoftness": 2})).unwrap(); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(softness(&s), None, "undone"); + assert!(!saved(&mut s).contains("shadow_softness"), "the default saves nothing new"); + // The fixture reads back as saved, requiring what it sets by name. + let fixture = Project::from_json(include_str!("../../../schema/fixtures/shaded_relief_shadow_softness.rgis")).unwrap(); + assert_eq!(softness(&Session::new(fixture.clone())), Some(1.5)); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["shaded-relief-effects", "shaded-relief-shadow-softness"])); +} + /// 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. diff --git a/crates/map/src/layout/tests.rs b/crates/map/src/layout/tests.rs index 25481a8566..20150e905c 100644 --- a/crates/map/src/layout/tests.rs +++ b/crates/map/src/layout/tests.rs @@ -769,6 +769,7 @@ fn a_balanced_reliefs_colour_bar_is_its_flat_ground() { rock: None, ambient: None, balanced, + shadow_softness: None, }; let Some(ColorScale::Ramp { lo, hi, colors }) = color_scale(&rl) else { panic!("a ramp") }; let colorizer = Colorizer::new(&rl.style, &r, None); diff --git a/crates/map/src/qgis/raster.rs b/crates/map/src/qgis/raster.rs index 59c7f1230c..26c65f0363 100644 --- a/crates/map/src/qgis/raster.rs +++ b/crates/map/src/qgis/raster.rs @@ -100,6 +100,7 @@ fn renderer_style(node: Node, pipe: Node, r: Node, kind: &str, layer: &str, repo rock: None, ambient: None, balanced: false, + shadow_softness: None, }; (renderer, Stretch::None) } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 52fea9ceea..9c877e8929 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -912,6 +912,7 @@ fn raster_renderers_read_as_rustgis_raster_styles() { rock: None, ambient: None, balanced: false, + shadow_softness: None, } ); assert!(report.notes.iter().any(|n| n.text.contains("saturation"))); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index badc93063c..c5fdd76a67 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -963,8 +963,8 @@ impl RasterLayer { } /// The light its cast shadows leave on each cell (see [`crate::shadow::light`]), when it is - /// drawn as Shaded Relief with shadows. Worked out once per pixels, band, sun, Z factor and - /// mask and kept: each owner's latest, and a few of suns left, for going back. + /// drawn as Shaded Relief with shadows. Worked out once per pixels, band, sun (its softness + /// too), Z factor and mask and kept: each owner's latest, and a few of suns left, for going back. /// `owner` is who draws it (its map's and its layer's live identities, see /// [`crate::Layer::instance_id`]; a layer's id repeats from map to map): a new sun from the /// same owner stops the work @@ -973,11 +973,13 @@ impl RasterLayer { /// export does, this waits for it. The browser, which has one thread, works it out here, for /// at most [`crate::shadow::MAX_BROWSER_CELLS`] cells. pub fn cast_shadows(&self, wait: bool, owner: (u64, u64), landed: impl FnOnce() + Send + 'static) -> CastShadows { - let RasterRenderer::ShadedRelief { azimuth, altitude, shadow, .. } = self.style.renderer else { + let RasterRenderer::ShadedRelief { azimuth, altitude, shadow, shadow_softness, .. } = self.style.renderer else { return CastShadows::None; }; let finite = azimuth.is_finite() && altitude.is_finite(); - self.light_grid(Grid::Shadows { azimuth, altitude }, shadow > 0.0 && finite, wait, owner, landed) + // The half disc traced, not the setting: none and the default's own value share a grid. + let soft_edge = crate::shadow::soft_edge(shadow_softness); + self.light_grid(Grid::Shadows { azimuth, altitude, soft_edge }, shadow > 0.0 && finite, wait, owner, landed) } /// The share of the sky each cell sees (see [`crate::shadow::sky`]), when it is drawn as @@ -1094,7 +1096,7 @@ struct LightKey { /// Which grid: the light cast shadows leave for a sun, or the sky seen. #[derive(Clone, Copy, Debug, PartialEq)] enum Grid { - Shadows { azimuth: f64, altitude: f64 }, + Shadows { azimuth: f64, altitude: f64, soft_edge: f64 }, Sky, } @@ -1260,8 +1262,8 @@ fn start_light(r: Arc, key: LightKey, work: Arc) { drop(LIGHT_HOLD.read().unwrap_or_else(|e| e.into_inner())); let threads = rustgis_data::threads::max(); let traced = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match key.grid { - Grid::Shadows { azimuth, altitude } => { - crate::shadow::light(&r, key.band, &key.mask, azimuth, altitude, key.z_factor, threads, &work.stop) + Grid::Shadows { azimuth, altitude, soft_edge } => { + crate::shadow::light(&r, key.band, &key.mask, azimuth, altitude, soft_edge, key.z_factor, threads, &work.stop) } Grid::Sky => crate::shadow::sky(&r, key.band, &key.mask, key.z_factor, threads, &work.stop), })); @@ -1667,7 +1669,10 @@ pub enum RasterRenderer { /// share of the colour a slope turned fully from the sun keeps; none, the default, is /// [`relief_ambient`]'s. `balanced` divides the sun's light by its value on flat ground, so flat /// ground keeps the ramp's colour and slopes facing the sun brighten (#1977); off, the default, - /// lights as before. + /// lights as before. `shadow_softness` is half the sun's apparent size its cast shadows are + /// traced with, in degrees ([`crate::shadow::SOFT_EDGE_MIN`] to + /// [`crate::shadow::SOFT_EDGE_MAX`]): how soft their edges are (#3144); none, the default, is + /// [`crate::shadow::SOFT_EDGE`]. ShadedRelief { band: usize, ramp: Option, @@ -1686,6 +1691,8 @@ pub enum RasterRenderer { ambient: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] balanced: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + shadow_softness: Option, }, } @@ -2717,6 +2724,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, } } @@ -3307,6 +3315,7 @@ mod tests { rock, ambient: None, balanced: false, + shadow_softness: None, }; let (mut rocky, mut plain) = (RasterStyle::default_for(&r), RasterStyle::default_for(&r)); (rocky.renderer, plain.renderer) = (relief(Some(rock)), relief(None)); @@ -3362,6 +3371,7 @@ mod tests { rock: None, ambient, balanced, + shadow_softness: None, }; let relief = |altitude, ambient, balanced| tinted_relief(None, altitude, ambient, balanced); // Grey relief: white shaded, so a channel is 255 times the light. @@ -3454,6 +3464,21 @@ mod tests { *shadow = 0.3; } assert!(matches!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Ready(g) if Arc::ptr_eq(&g, &grid))); + // The default softness set by its value traces the same disc: the grid is kept. Another + // softness is worked out again (another grid: this tower's shadow is whole under both), + // and going back to the default finds its grid kept (#3144). + let soften = |rl: &mut RasterLayer, to: Option| { + if let RasterRenderer::ShadedRelief { shadow_softness, .. } = &mut rl.style.renderer { + *shadow_softness = to; + } + }; + soften(&mut rl, Some(crate::shadow::SOFT_EDGE)); + assert!(matches!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Ready(g) if Arc::ptr_eq(&g, &grid))); + soften(&mut rl, Some(1.0)); + let CastShadows::Ready(crisp) = rl.cast_shadows(true, (0, 1), || {}) else { panic!("waited for") }; + assert!(!Arc::ptr_eq(&crisp, &grid), "another softness, another grid"); + soften(&mut rl, None); + assert!(matches!(rl.cast_shadows(false, (0, 1), || {}), CastShadows::Ready(g) if Arc::ptr_eq(&g, &grid))); // Another sun: worked out again, lit from the west now. if let RasterRenderer::ShadedRelief { azimuth, .. } = &mut rl.style.renderer { *azimuth = 270.0; @@ -3551,7 +3576,7 @@ mod tests { // The worker stops and says so (the map draws again), with no grid. assert!(landings.recv_timeout(std::time::Duration::from_secs(60)).is_ok(), "landed"); let work = rl.cast.0.lock().unwrap().first().map(|j| j.work.clone()).unwrap(); - assert!(work.was_stopped(Grid::Shadows { azimuth: 0.0, altitude: 0.0 }.stopped())); + assert!(work.was_stopped(Grid::Shadows { azimuth: 0.0, altitude: 0.0, soft_edge: 0.0 }.stopped())); // Asked again, it starts over. rl.cast_shadows(false, (0, 1), || {}); let again = rl.cast.0.lock().unwrap().first().map(|j| j.work.clone()).unwrap(); diff --git a/crates/map/src/shadow.rs b/crates/map/src/shadow.rs index d17fa1e3e4..31bcf3ad8f 100644 --- a/crates/map/src/shadow.rs +++ b/crates/map/src/shadow.rs @@ -2,10 +2,11 @@ //! each cell of an elevation raster sees over the terrain between it and the sun ([`light`]), and //! how much of the sky it sees over the terrain around it ([`sky`]). //! -//! The sun is a disc [`SOFT_EDGE`] degrees either side of its altitude, so a shadow has a soft -//! edge. Each cell traces the terrain toward the sun's azimuth one column or row at a time, -//! reading heights between cells (bilinear: reading the nearest cell instead over-shadows diagonal -//! suns, franciscoparrao/surtgis#153), and keeps the steepest angle up to the terrain it passes. +//! The sun is a disc some degrees either side of its altitude ([`SOFT_EDGE`] unless the layer sets +//! its shadow softness), so a shadow has a soft edge. Each cell traces the terrain toward the sun's +//! azimuth one column or row at a time, reading heights between cells (bilinear: reading the +//! nearest cell instead over-shadows diagonal suns, franciscoparrao/surtgis#153), and keeps the +//! steepest angle up to the terrain it passes. //! The share of the disc above that angle is the light the cell keeps. The trace stops once //! nothing farther can change it: the terrain left can't rise above the angle kept (or the disc's //! lower edge), or the disc is already hidden. The sky is traced likewise, in [`SKY_DIRECTIONS`] @@ -19,9 +20,24 @@ use rustgis_data::raster::Raster; use crate::raster::RasterMask; /// Half the sun's apparent size, in degrees: how wide a shadow's soft edge is. Far larger than the -/// real sun's quarter of a degree, for a soft edge at map scale. +/// real sun's quarter of a degree, for a soft edge at map scale. A layer's shadow softness +/// replaces it (see [`soft_edge`]). pub const SOFT_EDGE: f64 = 5.0; +/// The narrowest half disc a layer's shadow softness sets, in degrees (#3144): a much smaller disc +/// would step at the cell size. +pub const SOFT_EDGE_MIN: f64 = 0.5; +/// The widest half disc a layer's shadow softness sets, in degrees (#3144): a much larger one would +/// blur the shadows away. +pub const SOFT_EDGE_MAX: f64 = 15.0; + +/// The half disc a layer's shadow softness `setting` gives, in degrees: [`SOFT_EDGE`] with none +/// (or one that isn't a number), and within [`SOFT_EDGE_MIN`] to [`SOFT_EDGE_MAX`] whatever a +/// file holds (`raster.symbology` refuses a value outside them). +pub fn soft_edge(setting: Option) -> f64 { + setting.filter(|v| v.is_finite()).map_or(SOFT_EDGE, |v| v.clamp(SOFT_EDGE_MIN, SOFT_EDGE_MAX)) +} + /// The most cells a raster's shadows, or its sky, are worked out for in the browser, which has one /// thread: past it, the relief is drawn without them, and said. pub const MAX_BROWSER_CELLS: usize = 500_000; @@ -42,23 +58,28 @@ pub enum Unlit { /// The light left by cast shadows on each cell of `band` (`0` in shadow to `255` lit), row by row /// as the raster's pixels are, for a sun at `azimuth` (degrees clockwise from north) and `altitude` -/// (degrees above the horizon), heights scaled by `z_factor`. Cells that are no data or masked are -/// lit and cast no shadow. Rows are split over up to `threads` threads, each the same as on one. -/// Looks at `stop` between rows, and at the run's Cancel (see [`rustgis_data::progress`]) on a -/// thread that has one (the browser, which works it out where it is asked). On the desktop the -/// worker has none: a cancelled export that waited for it alone sets `stop`. A sun under about 5° -/// traces far over gentle ground: the cost grows with the raster's width as well as its cells. +/// (degrees above the horizon), its disc `soft_edge` degrees either side of it (see [`soft_edge`]), +/// heights scaled by `z_factor`. Cells that are no data or masked are lit and cast no shadow. Rows +/// are split over up to `threads` threads, each the same as on one. Looks at `stop` between rows, +/// and at the run's Cancel (see [`rustgis_data::progress`]) on a thread that has one (the browser, +/// which works it out where it is asked). On the desktop the worker has none: a cancelled export +/// that waited for it alone sets `stop`. The trace runs down to the disc's lower edge +/// (`altitude` less `soft_edge`): with that edge near the horizon or below it (a sun under about +/// 5° at the default disc, under about 15° at the widest), each cell traces far over gentle ground +/// and the cost grows with the raster's width as well as its cells, some ten times that of an edge +/// at 5°. No softness costs much more than a sun on the horizon does at the default disc. pub fn light( r: &Raster, band: usize, mask: &RasterMask, azimuth: f64, altitude: f64, + soft_edge: f64, z_factor: f64, threads: usize, stop: &AtomicBool, ) -> Result, Unlit> { - let sun = Sun::new(r, azimuth, altitude); + let sun = Sun::new(r, azimuth, altitude, soft_edge); each_row(r, band, mask, z_factor, threads, stop, |trace, row, out| { for (col, cell) in out.iter_mut().enumerate() { if let Some(z0) = trace.at(col, row) { @@ -248,17 +269,34 @@ impl Way { /// The sun as each cell's trace needs it. struct Sun { way: Way, - /// The tangents of the disc's lower and upper edges. + /// The tangents of the disc's lower and upper edges. A softness set has the upper one infinite + /// when the disc reaches the zenith; the default disc's are held under 90°, as they always were. low: f64, high: f64, altitude: f64, + /// Half the disc, in degrees. + soft: f64, } impl Sun { - fn new(r: &Raster, azimuth: f64, altitude: f64) -> Self { + fn new(r: &Raster, azimuth: f64, altitude: f64, soft: f64) -> Self { let altitude = altitude.clamp(0.0, 90.0); - let edge = |a: f64| a.clamp(-89.9, 89.9).to_radians().tan(); - Sun { way: Way::new(r, azimuth), low: edge(altitude - SOFT_EDGE), high: edge(altitude + SOFT_EDGE), altitude } + let soft = soft_edge(Some(soft)); + let (low, high) = if soft == SOFT_EDGE { + // The default disc keeps the edges it was traced with before a softness could be set, + // held under 90°, so a layer that sets none draws the pixels it did (#3144). + let held = |a: f64| a.clamp(-89.9, 89.9).to_radians().tan(); + (held(altitude - soft), held(altitude + soft)) + } else { + // The altitude is 0° to 90° and the half disc 0.5° to 15°, so the lower edge lies from + // 15° below the horizon to 89.5° and an upper edge short of the zenith has a finite + // tangent: neither is held under 90°, which would hide the whole of a disc nearer the + // zenith. A disc reaching the zenith has no upper edge any terrain hides it past: the + // share above the terrain is still lit, however steep that is. + let edge = |a: f64| a.to_radians().tan(); + (edge(altitude - soft), if altitude + soft >= 90.0 { f64::INFINITY } else { edge(altitude + soft) }) + }; + Sun { way: Way::new(r, azimuth), low, high, altitude, soft } } /// The share of the disc above the steepest tangent `t` seen toward it, 0 to 255. @@ -270,7 +308,7 @@ impl Sun { return 0; } let seen = t.atan().to_degrees(); - let share = (self.altitude + SOFT_EDGE - seen) / (2.0 * SOFT_EDGE); + let share = (self.altitude + self.soft - seen) / (2.0 * self.soft); (share.clamp(0.0, 1.0) * 255.0).round() as u8 } } @@ -396,7 +434,12 @@ mod tests { } fn lit(r: &Raster, azimuth: f64, altitude: f64) -> Vec { - light(r, 0, &RasterMask::default(), azimuth, altitude, 1.0, 4, &AtomicBool::new(false)).unwrap_or_else(|e| panic!("{e:?}")) + soft(r, azimuth, altitude, SOFT_EDGE) + } + + fn soft(r: &Raster, azimuth: f64, altitude: f64, soft_edge: f64) -> Vec { + light(r, 0, &RasterMask::default(), azimuth, altitude, soft_edge, 1.0, 4, &AtomicBool::new(false)) + .unwrap_or_else(|e| panic!("{e:?}")) } fn sky_of(r: &Raster, threads: usize) -> Vec { @@ -433,26 +476,44 @@ mod tests { assert!((127..=128).contains(&g[20 * 40 + 20]), "{}", g[20 * 40 + 20]); } - /// A wall casts a shadow as long as its height over the sun's tangent, at each main azimuth. + /// A wall casts a shadow as long as its height over the sun's tangent, its edge as wide as the + /// softness set: the default's, a crisp one's and a wide one's (#3144). #[test] fn a_walls_shadow_has_the_length_its_height_gives() { let (height, altitude) = (300.0, 45.0); // Lit from the east, a north–south wall at column 40 shades the cells west of it. let r = dem(60, 20, |e, _| if (e / CELL).round() == 40.0 { height } else { 0.0 }); - let g = lit(&r, 90.0, altitude); - let row = &g[10 * 60..11 * 60]; - // The whole disc is hidden up to height / tan(45° + 5°) away, none of it past - // height / tan(45° − 5°). - let full = (height / f64::to_radians(altitude + SOFT_EDGE).tan() / CELL).floor() as usize; - let none = (height / f64::to_radians(altitude - SOFT_EDGE).tan() / CELL).ceil() as usize; - for d in 1..=full { - assert_eq!(row[40 - d], 0, "{d} cells west"); - } - for d in none + 1..30 { - assert_eq!(row[40 - d], 255, "{d} cells west"); + let mut edges = Vec::new(); + for half in [SOFT_EDGE_MIN, SOFT_EDGE, SOFT_EDGE_MAX] { + let g = soft(&r, 90.0, altitude, half); + let row = &g[10 * 60..11 * 60]; + // The whole disc is hidden up to height / tan(45° + half) away, none of it past + // height / tan(45° − half). + let full = (height / f64::to_radians(altitude + half).tan() / CELL).floor() as usize; + let none = (height / f64::to_radians(altitude - half).tan() / CELL).ceil() as usize; + for d in 1..=full { + assert_eq!(row[40 - d], 0, "{half}°: {d} cells west"); + } + for d in none + 1..30 { + assert_eq!(row[40 - d], 255, "{half}°: {d} cells west"); + } + // East of the wall, facing the sun, nothing is shaded. + assert!(row[41..].iter().all(|v| *v == 255)); + edges.push(row.iter().filter(|v| (1..255).contains(*v)).count()); } - // East of the wall, facing the sun, nothing is shaded. - assert!(row[41..].iter().all(|v| *v == 255)); + // The wider the disc, the more cells are part lit. + assert!(edges[0] < edges[1] && edges[1] < edges[2], "{edges:?}"); + } + + /// No setting, or one that isn't a number, is the default; a file's value outside the range + /// traces at its nearest bound, never a disc of no size or one past the zenith. + #[test] + fn a_softness_outside_the_range_traces_at_its_bound() { + assert_eq!([soft_edge(None), soft_edge(Some(f64::NAN)), soft_edge(Some(1.5))], [SOFT_EDGE, SOFT_EDGE, 1.5]); + assert_eq!([soft_edge(Some(-3.0)), soft_edge(Some(0.0)), soft_edge(Some(1e9))], [SOFT_EDGE_MIN, SOFT_EDGE_MIN, SOFT_EDGE_MAX]); + let r = dem(60, 20, |e, _| if (e / CELL).round() == 40.0 { 300.0 } else { 0.0 }); + assert_eq!(soft(&r, 90.0, 45.0, 0.0), soft(&r, 90.0, 45.0, SOFT_EDGE_MIN)); + assert_eq!(soft(&r, 90.0, 45.0, f64::INFINITY), soft(&r, 90.0, 45.0, SOFT_EDGE)); } /// A trace stopped part-way gives no grid; flat ground, no data and a mask cast nothing. @@ -460,7 +521,7 @@ mod tests { fn stopped_flat_and_missing_cells() { let flat = dem(300, 300, |_, _| 100.0); let stop = AtomicBool::new(true); - assert_eq!(light(&flat, 0, &RasterMask::default(), 315.0, 30.0, 1.0, 4, &stop), Err(Unlit::Stopped)); + assert_eq!(light(&flat, 0, &RasterMask::default(), 315.0, 30.0, SOFT_EDGE, 1.0, 4, &stop), Err(Unlit::Stopped)); assert_eq!(sky(&flat, 0, &RasterMask::default(), 1.0, 4, &stop), Err(Unlit::Stopped)); assert!(lit(&flat, 315.0, 30.0).iter().all(|v| *v == 255)); assert!(sky_of(&flat, 4).iter().all(|v| *v == 255), "flat ground sees the whole sky"); @@ -470,12 +531,12 @@ mod tests { assert!(sky_of(&tower, 1).iter().any(|v| *v < 255)); assert_eq!(sky_of(&tower, 1)[20 * 40 + 20], 255, "its top sees the whole sky"); let masked = RasterMask { values: vec![1000.0], ..RasterMask::default() }; - let g = light(&tower, 0, &masked, 90.0, 30.0, 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); + let g = light(&tower, 0, &masked, 90.0, 30.0, SOFT_EDGE, 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); assert!(g.iter().all(|v| *v == 255)); let g = sky(&tower, 0, &masked, 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); assert!(g.iter().all(|v| *v == 255)); // A band that isn't there leaves every cell lit. - let g = light(&tower, 3, &RasterMask::default(), 90.0, 30.0, 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); + let g = light(&tower, 3, &RasterMask::default(), 90.0, 30.0, SOFT_EDGE, 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); assert!(g.iter().all(|v| *v == 255)); let g = sky(&tower, 3, &RasterMask::default(), 1.0, 1, &AtomicBool::new(false)).unwrap_or_default(); assert!(g.iter().all(|v| *v == 255)); @@ -485,8 +546,8 @@ mod tests { #[test] fn threads_give_the_same_grid() { let r = dem(300, 300, |e, n| 400.0 * ((e / 900.0).sin() * (n / 700.0).cos()) + e * 0.05); - let one = light(&r, 0, &RasterMask::default(), 315.0, 25.0, 1.0, 1, &AtomicBool::new(false)); - let many = light(&r, 0, &RasterMask::default(), 315.0, 25.0, 1.0, 7, &AtomicBool::new(false)); + let one = light(&r, 0, &RasterMask::default(), 315.0, 25.0, SOFT_EDGE, 1.0, 1, &AtomicBool::new(false)); + let many = light(&r, 0, &RasterMask::default(), 315.0, 25.0, SOFT_EDGE, 1.0, 7, &AtomicBool::new(false)); assert_eq!(one, many); assert!(one.unwrap_or_default().iter().any(|v| *v < 255)); let one = sky_of(&r, 1); @@ -565,4 +626,49 @@ mod tests { } } } + + /// A disc of a softness set reaching past the zenith (a high sun, a wide disc), or just short + /// of it, keeps the share of it above the terrain seen, however steep: none of it is hidden + /// whole at an edge held under 90°. The default disc is traced as it was (see + /// `the_default_disc_is_traced_as_it_was`). + #[test] + fn a_disc_past_the_zenith_keeps_its_share_above_steep_terrain() { + let r = dem(3, 3, |_, _| 0.0); + for (altitude, soft, t) in [(80.0, 15.0, 1000.0), (88.0, 3.0, 1000.0), (89.45, 0.5, f64::to_radians(89.92).tan())] { + let share = (altitude + soft - t.atan().to_degrees()) / (2.0 * soft); + let lit = Sun::new(&r, 315.0, altitude, soft).lit(t); + assert_eq!(lit, (share * 255.0).round() as u8, "{altitude}° ± {soft}°"); + assert!(lit > 0, "{altitude}° ± {soft}°"); + } + } + + /// The default disc is traced as it was before a softness could be set (#3144), its edges held + /// under 90° even near the zenith, so a layer that sets none draws the pixels it did: the + /// same edges (where the trace stops) and the same light, at every altitude from 80° to 90° + /// and every tangent up to 89.95°'s. + #[test] + fn the_default_disc_is_traced_as_it_was() { + let r = dem(3, 3, |_, _| 0.0); + let held = |a: f64| a.clamp(-89.9, 89.9).to_radians().tan(); + for a in 0..=100 { + let altitude = 80.0 + f64::from(a) / 10.0; + let (low, high) = (held(altitude - SOFT_EDGE), held(altitude + SOFT_EDGE)); + let was = |t: f64| { + if t <= low { + 255 + } else if t >= high { + 0 + } else { + let share = (altitude + SOFT_EDGE - t.atan().to_degrees()) / (2.0 * SOFT_EDGE); + (share.clamp(0.0, 1.0) * 255.0).round() as u8 + } + }; + let sun = Sun::new(&r, 315.0, altitude, SOFT_EDGE); + assert_eq!((sun.low.to_bits(), sun.high.to_bits()), (low.to_bits(), high.to_bits()), "edges at {altitude}°"); + for d in 0..=2000 { + let t = f64::to_radians(70.0 + f64::from(d) * 0.00995).tan(); + assert_eq!(sun.lit(t), was(t), "{altitude}° seeing {t}"); + } + } + } } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index e3308ccb5f..7d23d7ae91 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -2892,6 +2892,7 @@ fn a_page_says_why_a_frame_drew_no_cast_shadows() { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; for shadow in [0.0, 1.0] { let map = ramp_map(relief(shadow), rustgis_map::raster::Stretch::MinMax); @@ -2944,6 +2945,7 @@ fn page_settles_with_suns(suns: &[f64]) { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; let mut m = Map::new(name.clone()); assert_eq!(m.add_raster("dem", copy), 1); @@ -2990,6 +2992,68 @@ fn many_maps_lit_otherwise_on_a_page_all_get_their_shadows() { page_settles_with_suns(&[315.0, 135.0, 45.0, 225.0, 0.0]); } +/// A page exported with a relief's shadow softness (#3144): left out or set to the default's own +/// value it draws today's pixels; a crisp or a wide one draws other pixels, the change growing +/// with the distance from the default. +#[test] +fn a_reliefs_shadow_softness_changes_its_page_only_off_the_default() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let n = 300usize; + let heights: Vec = (0..n * n).map(|i| (((i % n) as f32 / 9.0).sin() + ((i / n) as f32 / 7.0).cos()) * 400.0).collect(); + let gt = GeoTransform { origin_x: -1.0, origin_y: 1.0, pixel_width: 2.0 / n as f64, pixel_height: -2.0 / n as f64 }; + let dem = Raster::new("dem", n as u32, n as u32, vec![heights], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let page = |softness: Option| { + let mut rl = rustgis_map::raster::RasterLayer::from_path(dem.clone(), "dem.tif"); + rl.style.renderer = rustgis_map::raster::RasterRenderer::ShadedRelief { + band: 0, + ramp: None, + azimuth: 315.0, + altitude: 15.0, + // Slopes up to about 35°, so that much of the page lies in or at the edge of a shadow. + z_factor: 12.0, + shadow: 1.0, + sky: 0.0, + fill: 0.0, + rock: None, + ambient: None, + balanced: false, + shadow_softness: softness, + }; + let mut m = Map::new("m"); + assert_eq!(m.add_raster("dem", rl), 1); + let mut l = Layout::new("Layout", 100.0, 100.0); + let frame = ElementKind::MapFrame { + map: "m".into(), + center: Coord::new(0.0, 0.0), + scale: 2.5e6, + shape: FrameShape::Rectangle, + grid: None, + sections: Vec::new(), + extent_of: None, + extent_color: rustgis_map::layout::INDICATOR_COLOR, + extent_width: rustgis_map::layout::INDICATOR_WIDTH, + border_color: rustgis_map::layout::FRAME_BORDER_COLOR, + border_width: rustgis_map::layout::FRAME_BORDER_WIDTH, + bearing: 0.0, + pitch: 0.0, + }; + l.add("m", (5.0, 5.0, 90.0, 90.0), frame); + let (drawn, said) = crate::shadows_said(|| render(&l, &mut [m], 48.0, &PageInfo::default())); + assert!(said.notices.is_empty() && !said.to_come, "{softness:?}: {said:?}"); + drawn.unwrap().data().to_vec() + }; + let today = page(None); + assert_eq!(page(Some(rustgis_map::shadow::SOFT_EDGE)), today, "the default's own value draws today's page"); + // The mean change of a channel from today's page. + let change = |other: &[u8]| { + assert_eq!(other.len(), today.len()); + other.iter().zip(&today).map(|(a, b)| f64::from(a.abs_diff(*b))).sum::() / today.len() as f64 + }; + let (crisp, wide, widest) = (change(&page(Some(1.0))), change(&page(Some(10.0))), change(&page(Some(15.0)))); + assert!(crisp > 0.0 && wide > 0.0, "crisp {crisp}, wide {wide}"); + assert!(widest > wide, "wide {wide}, widest {widest}"); +} + /// A map with one 100 × 1 raster valued 0–99 by column, styled by `renderer`. fn ramp_map(renderer: rustgis_map::raster::RasterRenderer, stretch: rustgis_map::raster::Stretch) -> Map { use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 70f8841bd1..951ff2afa5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -12301,6 +12301,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; }; let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1200.0, bearing: 0.0, pitch: 0.0 }; @@ -12338,6 +12339,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: 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); @@ -12386,6 +12388,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: 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 3ee8c63f41..516fe90b18 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -1138,6 +1138,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, } } @@ -1234,6 +1235,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; style.resampling = Resampling::Nearest; let mut pm = Pixmap::new(1, 1).unwrap(); @@ -1409,6 +1411,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; style.resampling = Resampling::Nearest; let view = View { @@ -1774,6 +1777,7 @@ mod tests { rock, ambient: None, balanced: false, + shadow_softness: None, }; style.resampling = resampling; let view = View { diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 32c586e2a2..3e0c768f73 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -265,6 +265,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: 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}"); @@ -299,6 +300,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: 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/render/src/terrain/water.rs b/crates/render/src/terrain/water.rs index 3a2728da6a..98c94cd61f 100644 --- a/crates/render/src/terrain/water.rs +++ b/crates/render/src/terrain/water.rs @@ -1391,6 +1391,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.35, -0.05)), res: 300.0, bearing: 0.0, pitch: 0.0 }; @@ -1446,6 +1447,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; camera.center = lonlat_to_merc(Coord::new(0.35, -0.3)); let view = crate::View { width: 300.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1497,6 +1499,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.25, -0.1)), res: 300.0, bearing: 0.0, pitch: 0.0 }; let view = crate::View { width: 200.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1531,6 +1534,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; let camera = rustgis_map::Camera { center: lonlat_to_merc(Coord::new(0.35, -0.05)), res: 300.0, bearing: 0.0, pitch: 0.0 }; let view = crate::View { width: 200.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; @@ -1576,6 +1580,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; m.view.terrain.as_mut().unwrap().water.as_mut().unwrap().glint = glint; camera.center = lonlat_to_merc(Coord::new(0.35, -0.3)); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 2678b0a495..dddaf738d0 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -5821,6 +5821,7 @@ mod tests { rock: None, ambient: None, balanced: false, + shadow_softness: None, }; let set = |map: &mut Map, shadow: f64, visible: bool| { let l = map.layer_mut(id).unwrap(); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 3421738961..aa1b9ca889 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -7514,8 +7514,23 @@ 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, fill, rock, ambient, balanced } => { + RasterRenderer::ShadedRelief { + band, + ramp, + azimuth, + altitude, + z_factor, + shadow, + sky, + fill, + rock, + ambient, + balanced, + shadow_softness, + } => { + use rustgis_engine::map::shadow::{SOFT_EDGE_MAX, SOFT_EDGE_MIN, soft_edge}; let (az, alt, zf, sh, sk, fl) = (*azimuth, *altitude, *z_factor, *shadow, *sky, *fill); + let ss = soft_edge(*shadow_softness); let am = relief_ambient(*ambient, *balanced); let rp = ramp.as_ref().map(|r| r.name().to_string()); let relief = move |band: usize, az: f64, alt: f64, zf: f64, sh: f64| { @@ -7535,6 +7550,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { ("Altitude", alt, 0.0..=90.0, 0.5, 1), ("Z factor", zf, 0.001..=1000.0, 0.01, 2), ("Cast shadows", sh, 0.0..=1.0, 0.01, 3), + ("Shadow softness", ss, SOFT_EDGE_MIN..=SOFT_EDGE_MAX, 0.1, 7), ("Sky visibility", sk, 0.0..=1.0, 0.01, 4), ("Fill light", fl, 0.0..=1.0, 0.01, 5), ("Ambient", am, 0.0..=1.0, 0.01, 6), @@ -7555,6 +7571,9 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { "A light from the side opposite the sun that lightens the slopes turned toward it, from 0 (none) to 1" )), 6 => r.on_hover_text(tl!("The share of the colour a slope turned fully from the sun keeps, from 0 to 1")), + 7 => r.on_hover_text(tl!( + "How soft the edges of the cast shadows are: half the sun's apparent size, from 0.5° (crisp) to 15°" + )), _ => r, }; if drag.settled(ui, &r, &mut x) && x != v { @@ -7570,6 +7589,7 @@ fn raster_symbology(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { 4 => p["sky"] = json!(x), 5 => p["fill"] = json!(x), 6 => p["ambient"] = json!(x), + 7 => p["shadowSoftness"] = json!(x), _ => {} } let _ = app.run("raster.symbology", p); diff --git a/docs/maintaining.md b/docs/maintaining.md index f013f97bfd..f626343054 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -117,6 +117,8 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `terrain-block-walls-layer` (the layer a block diagram's walls are coloured by), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light), +`shaded-relief-shadow-softness` (a softness stored for a Shaded Relief's cast shadows, or set by a saved step; +`raster.symbology` stores the default as none), `blank-paper` (a blank basemap's paper colour) and `normalized-legend-urls` for normalized legend addresses. Project requirements include offline map snapshots. `table-export-order` protects saved task commands, diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9a25c89312..b930ff1f48 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1750,6 +1750,16 @@ whole image is held: either way the layer is drawn without them, and a notice sa outside the raster casts nothing on it, and a grid spanning 0 to 360° casts nothing across its seam. +**Shadow softness**, on a Shaded Relief layer (`raster.symbology` `"shadowSoftness"`, 0.5 to 15 +degrees), is how soft the edges of its cast shadows are: half the apparent size of the sun they are +traced with. A shadow's edge is the share of the sun's disc the terrain hides, so a wider disc +keeps a shadow sharp near what casts it and fades it farther away, as real shadows do; it isn't a +blur. 5, the default, draws the shadows as before; a small value gives a crisp shadow line, for a +large-scale map of a cliff, and a large one fades the shadows of a mountain range at a small scale. +Changing it works the shadows out again, as moving the sun does, and going back to a softness used +before draws at once. A value outside 0.5 to 15 is refused; `"shadowSoftness": null` goes back to +the default. It changes nothing while Cast shadows is 0. + **Sky visibility**, on a Shaded Relief layer (`raster.symbology` `"sky"`, 0 to 1), dims the relief's ambient light where the terrain around a cell hides part of the sky: valley floors, pits and the foot of a cliff get less of it than a plain or a ridge, whatever the sun. Each cell's sky is diff --git a/schema/fixtures/shaded_relief_shadow_softness.rgis b/schema/fixtures/shaded_relief_shadow_softness.rgis new file mode 100644 index 0000000000..1a3608612e --- /dev/null +++ b/schema/fixtures/shaded_relief_shadow_softness.rgis @@ -0,0 +1 @@ +{"requires":["shaded-relief-effects","shaded-relief-shadow-softness"],"format":2,"name":"Shaded relief shadow softness","maps":[{"name":"Map","layers":[{"id":1,"name":"dem","visible":true,"dataset":{"name":"dem","geometry_type":"None","fields":[],"features":[],"source":null},"renderer":{"Single":{"fill":[224,123,57,170],"stroke":[134,74,34,255],"stroke_width":0.7,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"","size":10.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto"},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":false,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"raster":{"path":"dem.tif","file_name":null,"style":{"renderer":{"ShadedRelief":{"band":0,"ramp":"Terrain","azimuth":315.0,"altitude":45.0,"z_factor":2.0,"shadow":0.8,"shadow_softness":1.5}},"stretch":{"PercentClip":{"low":0.5,"high":0.5}},"dra":false,"resampling":"Nearest","brightness":0.0,"contrast":0.0,"gamma":1.0,"rotation":0.0}},"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":-4654314.293187932,"y":-2329385.2820357964},"res":64.69445270508425,"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":null},"animation":[],"next_layer_id":2}],"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":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index bd859d561d..64c46ad9cd 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1291,7 +1291,8 @@ "layout-page-color", "layout-text-statistics", "layout-publication-parts", - "layout-publication-legend" + "layout-publication-legend", + "shaded-relief-shadow-softness" ], "type": "string" }, @@ -1411,7 +1412,8 @@ "layout-page-color", "layout-text-statistics", "layout-publication-parts", - "layout-publication-legend" + "layout-publication-legend", + "shaded-relief-shadow-softness" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2