diff --git a/crates/engine/src/cmd/effects.rs b/crates/engine/src/cmd/effects.rs index 5a83fb75e1..134bdf49bb 100644 --- a/crates/engine/src/cmd/effects.rs +++ b/crates/engine/src/cmd/effects.rs @@ -2,7 +2,7 @@ //! filters, point aggregation, and extrusion with face culling, lighting and shadows. use rustgis_data::GeometryType; -use rustgis_map::effects::{Aggregation, Blend, DisplayFilter, Extrusion}; +use rustgis_map::effects::{Aggregation, Blend, DisplayFilter, Extrusion, ValueMask}; use serde_json::{Value, json}; use super::layer::with; @@ -39,14 +39,17 @@ pub fn commands() -> Vec { .params(r#"{"layer"?, "mode": "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference"}"#), C::new("layer.mask", "Masking", "Style › Drawing", |s, p| { let id = s.layer_id(p)?; - let mask = mask_of(s, p, id)?; - with(s, p, |l| l.mask = mask.clone()) + let (mask, values) = mask_of(s, p, id)?; + with(s, p, |l| { + l.mask = mask; + l.raster_mask = values; + }) }) .inputs(mask_inputs) .roles(&[]) .effects(crate::policy::Effects::NONE) .when(need_layer) - .params(r#"{"layer"?, "mask": polygon layer|null}"#), + .params(r#"{"layer"?, "mask": polygon layer|{"raster", "min"?, "max"?, "inside"?: bool, "feather"?: raster units}|null}"#), C::new("layer.swipe", "Swipe", "Style › Compare", |s, p| { let id = s.layer_id(p)?; let pos = match p.get("position") { @@ -349,41 +352,69 @@ fn change_extrusion(s: &mut Session, p: &Value, f: impl FnOnce(&mut Extrusion)) /// Binds the primary target and literal mask, retaining names resolved by earlier planned steps. fn mask_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { let mut inputs = super::Inputs::single_layer(input, p)?; - if let Some(name) = mask_name(p)? { + if let Some((name, values)) = mask_name(p)? { // Preserve known live validation; future names are bound by the planner and checked - // against the actual polygon and target when the handler runs. + // against the actual polygon or raster and target when the handler runs. if input.map().layer_by_name(name).is_some() { - mask_layer(input.map(), name, input.layer_id(p).ok())?; + mask_layer(input.map(), name, values.is_some(), input.layer_id(p).ok())?; } inputs.extend(super::Inputs::named(input.map(), [name])?); } Ok(inputs) } -/// Parses the optional literal name exactly as the mask handler consumes it. -fn mask_name(p: &Value) -> Result, String> { +/// Parses the optional literal mask exactly as the mask handler consumes it: the layer it names, +/// and for a raster's values (#3147) the range they show the layer in. +fn mask_name(p: &Value) -> Result)>, String> { match p.get("mask") { None | Some(Value::Null) => Ok(None), Some(Value::String(n)) if n.trim().is_empty() => Ok(None), - Some(Value::String(n)) => Ok(Some(n)), - Some(_) => Err("mask is a polygon layer's name, or null".into()), + Some(Value::String(n)) => Ok(Some((n, None))), + Some(m @ Value::Object(_)) => { + let name = ps(m, "raster").ok_or(r#"a raster mask names its raster: {"raster": layer, "min"?, "max"?}"#)?; + // A number, or a numeric string as forms send it; left out or null, an open end. + let number = |k: &str, what: &str| match m.get(k) { + None | Some(Value::Null) => Ok(None), + Some(_) => f(m, k).map(Some).ok_or_else(|| format!("{k} is {what}")), + }; + let inside = match m.get("inside") { + None | Some(Value::Null) => true, + Some(v) => super::bool_value(v).ok_or("inside is true or false")?, + }; + let values = ValueMask { + raster: name.to_string(), + min: number("min", "a number, or null for an open end")?, + max: number("max", "a number, or null for an open end")?, + inside, + feather: number("feather", "0 or more, in the raster's units")?.unwrap_or(0.0), + }; + values.check()?; + Ok(Some((name, Some(values)))) + } + Some(_) => Err(r#"mask is a polygon layer's name, {"raster": layer, …} or null"#.into()), } } -/// Validates a live polygon mask, including the existing self-mask refusal. -fn mask_layer<'a>(map: &'a rustgis_map::Map, name: &str, id: Option) -> Result<&'a rustgis_map::Layer, String> { +/// Validates a live polygon (or with `values`, raster) mask, including the self-mask refusal. +fn mask_layer<'a>(map: &'a rustgis_map::Map, name: &str, values: bool, id: Option) -> Result<&'a rustgis_map::Layer, String> { let mask = map .layer_by_name(name) - .filter(|l| l.geometry_type() == GeometryType::Polygon) - .ok_or_else(|| format!("no polygon layer '{name}'"))?; + .filter(|l| if values { l.is_raster() } else { l.geometry_type() == GeometryType::Polygon }) + .ok_or_else(|| format!("no {} layer '{name}'", if values { "raster" } else { "polygon" }))?; if Some(mask.id) == id { return Err("a layer can't mask itself".into()); } Ok(mask) } -/// Resolves and validates the literal mask against the actual execution map. -fn mask_of(input: &impl super::InputSource, p: &Value, id: u32) -> Result, String> { +/// Resolves and validates the literal mask against the actual execution map: a polygon layer's +/// name, or a raster's values, under the layer's own name. +fn mask_of(input: &impl super::InputSource, p: &Value, id: u32) -> Result<(Option, Option), String> { let context = input.input_context(); - mask_name(p)?.map(|name| mask_layer(context.map(), name, Some(id)).map(|mask| mask.name.clone())).transpose() + let Some((name, values)) = mask_name(p)? else { return Ok((None, None)) }; + let name = mask_layer(context.map(), name, values.is_some(), Some(id))?.name.clone(); + Ok(match values { + Some(values) => (None, Some(ValueMask { raster: name, ..values })), + None => (Some(name), None), + }) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a670435610..6f1ca09eab 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7474,6 +7474,9 @@ fn references_follow_layer(s: &mut Session, old: &str, new: &str) { if let Some(mask) = &mut layer.mask { replace(mask); } + if let Some(values) = &mut layer.raster_mask { + replace(&mut values.raster); + } } // The terrain's water layer (#1915), kept by name as a mask is. if let Some(water) = s.map_mut().view.terrain.as_mut().and_then(|t| t.water.as_mut()) { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9f4881b3fb..47c2672f39 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -131,6 +131,7 @@ pub const CAPABILITIES: &[&str] = &[ "label-clearance", "svg-markers", "label-duplicates", + "layer-raster-mask", "tile-resampling", "layout-page-color", "layout-text-statistics", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 853a66410c..52d5900d4e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -181,6 +181,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("label-weight", command_weighs_labels), ("label-clearance", command_clears_labels), ("label-duplicates", command_removes_duplicate_labels), + ("layer-raster-mask", command_masks_by_raster), ("tile-resampling", command_resamples_tiles), ("layout-page-color", command_colours_the_page), ("layout-text-statistics", command_uses_text_statistics), @@ -260,6 +261,16 @@ fn command_sets_terrain_type(id: &str, params: &Value) -> bool { } } +/// A saved `layer.mask` that masks by a raster's values (#3147): an older reader refuses the +/// object, so the step fails where it would mask. +fn command_masks_by_raster(id: &str, params: &Value) -> bool { + match id { + "layer.mask" => params.get("mask").is_some_and(Value::is_object), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_masks_by_raster)), + _ => 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. @@ -1150,6 +1161,8 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (layer.has_picture_markers(), "picture-markers"), (layer.any_picture(svg_picture), "svg-markers"), (zarr_window(layer), "zarr-window"), + // Masked by a raster's values (#3147): an older reader would draw it whole and save it so. + (layer.raster_mask.is_some(), "layer-raster-mask"), (label_guide(layer), "label-guide"), (label_weight(layer), "label-weight"), (label_clearance(layer), "label-clearance"), @@ -1179,7 +1192,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut on_top, mut grid_color, ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); - let (mut polygon, mut svg) = (false, false); + let (mut polygon, mut svg, mut raster_mask) = (false, false, false); let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type) = (false, false, false, false, false, false); @@ -1227,6 +1240,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static svg |= map.layers.iter().any(|layer| layer.any_picture(svg_picture)); zarr |= map.layers.iter().any(zarr_window); native |= map.layers.iter().any(|layer| held_natively(&layer.dataset)); + raster_mask |= map.layers.iter().any(|layer| layer.raster_mask.is_some()); legends |= map.tiles.iter().any(|tile| { tile.legends.iter().any(|legend| rustgis_data::login_address::inner(&legend.url).len() > rustgis_map::tiles::MAX_LEGEND_URL) }); @@ -1251,6 +1265,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (pictures, "picture-markers"), (svg, "svg-markers"), (zarr, "zarr-window"), + (raster_mask, "layer-raster-mask"), (guided, "label-guide"), (weighed, "label-weight"), (cleared, "label-clearance"), @@ -1785,6 +1800,9 @@ mod tests { (&[], "raster.symbology", json!({"type": "hillshade", "terrain": "0"})), (&[], "raster.symbology", json!({"type": "stretch", "terrain": 0.6})), (&[], "raster.symbology", json!({"terrain": 0.6})), + (&["layer-raster-mask"], "layer.mask", json!({"mask": {"raster": "Slope", "min": 25}})), + (&[], "layer.mask", json!({"mask": "Countries"})), + (&[], "layer.mask", json!({"mask": 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})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ebca733592..30f5bc6ba2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -14,6 +14,8 @@ mod held_databases; mod own_grid_edits; #[path = "tests/own_segments.rs"] mod own_segments; +#[path = "tests/raster_mask.rs"] +mod raster_mask; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/scene_losses.rs"] mod scene_losses; diff --git a/crates/engine/src/tests/raster_mask.rs b/crates/engine/src/tests/raster_mask.rs new file mode 100644 index 0000000000..928d3ecacc --- /dev/null +++ b/crates/engine/src/tests/raster_mask.rs @@ -0,0 +1,100 @@ +//! `layer.mask` by a raster's values (#3147). + +use rustgis_map::effects::ValueMask; +use serde_json::{Value, json}; + +use crate::Session; + +/// The sample world with the hill DEM (values 200 to 300, and a column of 400): its name. +fn with_dem() -> (Session, String) { + let mut s = super::world(); + s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": super::dem_b64()})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + (s, dem) +} + +fn masks(s: &Session, layer: &str) -> (Option, Option) { + let l = s.map().layer_by_name(layer).unwrap(); + (l.mask.clone(), l.raster_mask.clone()) +} + +#[test] +fn layer_mask_takes_a_rasters_values_in_place_of_polygons() { + let (mut s, dem) = with_dem(); + s.run("layer.mask", &json!({"layer": "Cities", "mask": "Countries"})).unwrap(); + let range = json!({"raster": dem.to_uppercase(), "min": 250, "max": "280", "inside": false, "feather": 5}); + s.run("layer.mask", &json!({"layer": "Cities", "mask": range})).unwrap(); + let values = ValueMask { raster: dem.clone(), min: Some(250.0), max: Some(280.0), inside: false, feather: 5.0 }; + assert_eq!(masks(&s, "Cities"), (None, Some(values.clone())), "under the raster's own name, in place of the polygons"); + // Saved, it is named for a reader that would draw the layer whole. + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["layer-raster-mask"])); + // It follows the raster's new name, as a polygon mask does. + s.run("layer.rename", &json!({"layer": dem, "name": "Altitude"})).unwrap(); + assert_eq!(masks(&s, "Cities").1.map(|m| m.raster), Some("Altitude".to_string())); + s.run("layer.mask", &json!({"layer": "Cities", "mask": "Countries"})).unwrap(); + assert_eq!(masks(&s, "Cities"), (Some("Countries".to_string()), None), "the polygons in place of the values"); + s.run("layer.mask", &json!({"layer": "Cities", "mask": {"raster": "Altitude"}})).unwrap(); + let open = ValueMask { raster: "Altitude".into(), min: None, max: None, inside: true, feather: 0.0 }; + assert_eq!(masks(&s, "Cities").1, Some(open), "both ends open, inside, with no feather"); + s.run("layer.mask", &json!({"layer": "Cities", "mask": null})).unwrap(); + assert_eq!(masks(&s, "Cities"), (None, None)); +} + +#[test] +fn a_raster_mask_that_cant_mask_is_refused_and_changes_nothing() { + let (mut s, dem) = with_dem(); + s.run("layer.mask", &json!({"layer": "Cities", "mask": {"raster": dem, "min": 250}})).unwrap(); + let (before, depth) = (masks(&s, "Cities"), s.undo_depth()); + for (bad, says) in [ + (json!({"raster": "Countries", "min": 1}), "no raster layer 'Countries'"), + (json!({"min": 1}), "names its raster"), + (json!({"raster": dem, "min": 5, "max": 1}), "min 5 is above max 1"), + (json!({"raster": dem, "min": "steep"}), "min is a number"), + (json!({"raster": dem, "feather": -1}), "feather is 0 or more"), + (json!({"raster": dem, "inside": "maybe"}), "inside is true or false"), + (json!(7), "mask is a polygon layer's name"), + ] { + let err = s.run("layer.mask", &json!({"layer": "Cities", "mask": bad})).expect_err(&bad.to_string()); + assert!(err.contains(says), "{bad}: {err}"); + } + let err = s.run("layer.mask", &json!({"layer": dem, "mask": {"raster": dem}})).unwrap_err(); + assert!(err.contains("can't mask itself"), "{err}"); + assert_eq!((masks(&s, "Cities"), s.undo_depth()), (before, depth)); +} + +#[test] +fn a_layer_shows_only_where_the_rasters_values_are_in_its_range() { + use crate::render::View; + let (mut s, dem) = with_dem(); + // Over the DEM only, and only the countries drawn. + s.run("map.goToXY", &json!({"lon": 10.02, "lat": 45.02, "scale": 20_000})).unwrap(); + let others: Vec = s.map().layers.iter().map(|l| l.name.clone()).filter(|n| n != "Countries").collect(); + for l in others { + s.run("layer.visibility", &json!({"layer": l, "visible": false})).unwrap(); + } + let frame = |s: &mut Session| { + let v = View { width: 200.0, height: 150.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + crate::render::render(s.map_mut(), &v).unwrap().pixmap.data().to_vec() + }; + let shown = frame(&mut s); + s.run("layer.visibility", &json!({"layer": "Countries", "visible": false})).unwrap(); + let hidden = frame(&mut s); + s.run("layer.visibility", &json!({"layer": "Countries", "visible": true})).unwrap(); + assert_ne!(shown, hidden, "the countries are drawn here"); + let mut masked = |range: Value| { + s.run("layer.mask", &json!({"layer": "Countries", "mask": range})).unwrap(); + frame(&mut s) + }; + assert!(masked(json!({"raster": dem, "min": 1000})) == hidden, "no value in the range: hidden"); + assert!(masked(json!({"raster": dem, "max": 1000})) == shown, "every value in it: shown whole"); + assert!(masked(json!({"raster": dem, "min": 1000, "inside": false})) == shown, "outside a range nothing is in"); + let hill = masked(json!({"raster": dem, "min": 250})); + assert!(hill != shown && hill != hidden, "only on the hill"); + let soft = masked(json!({"raster": dem, "min": 250, "feather": 40})); + assert!(soft != hill, "a feather fades it in below the hill's top"); + // A mask raster with no pixels (a read that failed) has no value anywhere: hidden. + let id = s.map().layer_by_name(&dem).unwrap().id; + s.map_mut().layer_mut(id).unwrap().raster.as_mut().unwrap().data = None; + s.run("layer.mask", &json!({"layer": "Countries", "mask": {"raster": dem, "max": 1000}})).unwrap(); + assert!(frame(&mut s) == hidden, "no pixels: hidden, as no value is"); +} diff --git a/crates/map/src/effects.rs b/crates/map/src/effects.rs index 51038aad90..162c337d91 100644 --- a/crates/map/src/effects.rs +++ b/crates/map/src/effects.rs @@ -67,6 +67,58 @@ impl DisplayFilter { } } +/// A layer shown only where a raster's values are in a range (#3147): read at its first band, as +/// the map draws that raster. Either end may be open. Past an end the layer fades out over +/// `feather` (in the raster's units) instead of being cut; `inside: false` shows it outside the +/// range instead. Where the raster has no value, the layer is hidden either way. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ValueMask { + /// The raster layer, by name, as a polygon mask names its layer. + pub raster: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub min: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max: Option, + #[serde(default = "yes")] + pub inside: bool, + #[serde(default)] + pub feather: f64, +} + +impl ValueMask { + /// Why the range can't mask: an end or the feather that is no number, an end past the other, + /// or a feather below 0. + pub fn check(&self) -> Result<(), String> { + if self.min.iter().chain(&self.max).any(|v| !v.is_finite()) { + return Err("min and max are numbers, or null for an open end".into()); + } + if let (Some(lo), Some(hi)) = (self.min, self.max) + && lo > hi + { + return Err(format!("min {lo} is above max {hi}")); + } + if !(self.feather.is_finite() && self.feather >= 0.0) { + return Err("feather is 0 or more, in the raster's units".into()); + } + Ok(()) + } + + /// How much of the layer shows where the raster's value is `v`: 1 in the range, falling to 0 + /// a feather past either end (at once with no feather), the reverse outside; 0 with no value. + pub fn share(&self, v: f64) -> f64 { + if !v.is_finite() { + return 0.0; + } + let edge = |past: f64| match past { + p if p <= 0.0 => 1.0, + p if self.feather > 0.0 => (1.0 - p / self.feather).max(0.0), + _ => 0.0, + }; + let inside = self.min.map_or(1.0, |lo| edge(lo - v)) * self.max.map_or(1.0, |hi| edge(v - hi)); + if self.inside { inside } else { 1.0 - inside } + } +} + /// Points drawn as bins coloured by how many fall in each. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Aggregation { @@ -152,6 +204,37 @@ fn yes() -> bool { true } +#[cfg(test)] +mod value_mask_tests { + use super::ValueMask; + + fn mask(min: Option, max: Option, inside: bool, feather: f64) -> ValueMask { + ValueMask { raster: "slope".into(), min, max, inside, feather } + } + + #[test] + fn a_layer_fades_out_a_feather_past_either_end() { + let m = mask(Some(20.0), Some(40.0), true, 5.0); + let shares = [10.0, 15.0, 17.5, 20.0, 30.0, 40.0, 42.5, 45.0, 50.0].map(|v| m.share(v)); + assert_eq!(shares, [0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 0.5, 0.0, 0.0]); + let outside = ValueMask { inside: false, ..m.clone() }; + assert_eq!([17.5, 30.0, 50.0].map(|v| outside.share(v)), [0.5, 0.0, 1.0], "the reverse outside"); + let cut = mask(Some(25.0), None, true, 0.0); + assert_eq!([24.999, 25.0, 1e9].map(|v| cut.share(v)), [0.0, 1.0, 1.0], "no feather: cut at the end, the other open"); + for m in [m, outside, cut, mask(None, None, false, 0.0)] { + assert_eq!(m.share(f64::NAN), 0.0, "no value hides the layer either way"); + } + } + + #[test] + fn a_saved_value_mask_reads_back_and_its_defaults_are_inside_with_no_feather() { + let m = mask(Some(300.0), None, false, 50.0); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&m).unwrap()).unwrap(), m); + let plain: ValueMask = serde_json::from_str(r#"{"raster":"dem"}"#).unwrap(); + assert_eq!(plain, ValueMask { raster: "dem".into(), min: None, max: None, inside: true, feather: 0.0 }); + } +} + #[cfg(test)] mod extrusion_tests { use super::*; diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 09f9e9dbf3..d3a2e0153b 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -230,6 +230,10 @@ pub struct Layer { /// A polygon layer (by name) outside whose shapes this layer is hidden. #[serde(default)] pub mask: Option, + /// A raster whose values say where this layer shows (#3147); `layer.mask` sets this or + /// `mask`, never both. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub raster_mask: Option, /// Scale-dependent feature filters. #[serde(default)] pub display_filters: Vec, @@ -432,6 +436,7 @@ impl Layer { graphics: _, blend: _, mask: _, + raster_mask: _, display_filters: _, aggregation: _, extrusion: _, @@ -685,6 +690,7 @@ impl Layer { graphics: false, blend: effects::Blend::Normal, mask: None, + raster_mask: None, display_filters: Vec::new(), aggregation: None, extrusion: None, @@ -4085,6 +4091,7 @@ impl Layer { graphics: _, blend: _, mask: _, + raster_mask: _, display_filters: _, aggregation: _, extrusion: _, diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index c3a458a8f4..9c641a9f13 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -59,6 +59,7 @@ fn bare(layer: &Layer) -> Layer { graphics, blend, mask, + raster_mask, display_filters, aggregation, extrusion, @@ -132,6 +133,7 @@ fn bare(layer: &Layer) -> Layer { graphics: *graphics, blend: *blend, mask: mask.clone(), + raster_mask: raster_mask.clone(), display_filters: display_filters.clone(), aggregation: *aggregation, extrusion: extrusion.clone(), @@ -236,6 +238,7 @@ impl LayerLook { graphics, blend, mask, + raster_mask, display_filters, aggregation, extrusion, @@ -300,6 +303,7 @@ impl LayerLook { && *graphics == layer.graphics && *blend == layer.blend && *mask == layer.mask + && *raster_mask == layer.raster_mask && *display_filters == layer.display_filters && *aggregation == layer.aggregation && *extrusion == layer.extrusion diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 824ea48ccb..a8aa56d70f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -43,6 +43,7 @@ mod stroke_paths; pub mod svg; pub mod terrain; mod text; +mod value_mask; pub use text::CALLOUT_WIDTH; mod frame_cache; mod layer_meshes; @@ -3689,6 +3690,7 @@ pub fn gpu_may_turn(map: &Map, view: &View) -> bool { && l.opacity() >= 0.999 && !faded.contains_key(&l.id) && l.mask.is_none() + && l.raster_mask.is_none() && l.blend == rustgis_map::effects::Blend::Normal && map.swipe.is_none_or(|(id, _)| id != l.id) && l.aggregation.is_none() @@ -4010,6 +4012,7 @@ fn stands_up(map: &Map, layer: &rustgis_map::Layer) -> bool { && layer.aggregation.is_none() && !layer.graphics && layer.mask.is_none() + && layer.raster_mask.is_none() && layer.blend == rustgis_map::effects::Blend::Normal && map.swipe.is_none_or(|(id, _)| id != layer.id) // Marks and turned markers stay on the ground, drawn as the flat map draws them. @@ -4757,7 +4760,10 @@ fn keeps_pictures(map: &Map, view: &View) -> bool { && !map.projection.is_globe() && map.swipe.is_none() && map.view.terrain.as_ref().is_none_or(|t| t.water.is_none()) - && map.layers.iter().all(|l| l.mask.is_none() && l.labels.in_order().all(|c| c.square_to.is_none() && c.guide.is_none())) + && map + .layers + .iter() + .all(|l| l.mask.is_none() && l.raster_mask.is_none() && l.labels.in_order().all(|c| c.square_to.is_none() && c.guide.is_none())) } /// Draws one north-up frame. `labels_to` says where its labels go: a turned or tilted view the @@ -5210,8 +5216,9 @@ fn render_frame( } let tokens = rustgis_map::graphics::TokenValues::of(map, scale); let n_layers = map.layers.len(); - // Masks: layers shown only inside another layer's polygons, or left of the swipe divider. - let masks = layer_masks(map, &ctx, w, h, &flat, &key, scale, failed_source)?; + // Masks: layers shown only inside another layer's polygons or where a raster's values say, + // or left of the swipe divider. + let masks = layer_masks(map, &ctx, w, h, &flat, &key, scale, full_res_rasters, failed_source)?; // The lines point labels are turned square to (#2263), on the screen. // Of those held in another system, the ids, noted read once a label is squared to them. let mut square_held = std::collections::HashMap::new(); @@ -7420,8 +7427,8 @@ pub(crate) fn blend_mode(b: rustgis_map::effects::Blend) -> tiny_skia::BlendMode } } -/// The mask of every masked or swiped layer: inside its mask layer's polygons and left of the -/// swipe divider. +/// The mask of every masked or swiped layer: inside its mask layer's polygons, where its mask +/// raster's values show it (#3147, `full_res` as rasters are drawn) and left of the swipe divider. /// A failed mask read returns its source layer's identity through `failed_source`. fn layer_masks( map: &mut Map, @@ -7431,20 +7438,22 @@ fn layer_masks( flat: &rustgis_map::projection::Flat, key: &str, scale: f64, + full_res: bool, failed_source: &mut Option, ) -> Option> { - let wanted: Vec<(u32, Option, Option)> = map + type Wanted = (u32, Option, Option, Option); + let wanted: Vec = map .layers .iter() .filter(|l| map.draws_at(l, scale)) .filter_map(|l| { let swipe = map.swipe.filter(|(id, _)| *id == l.id).map(|(_, x)| x.clamp(0.0, 1.0)); - (l.mask.is_some() || swipe.is_some()).then(|| (l.id, l.mask.clone(), swipe)) + (l.mask.is_some() || l.raster_mask.is_some() || swipe.is_some()).then(|| (l.id, l.mask.clone(), l.raster_mask.clone(), swipe)) }) .collect(); let mut out = Vec::new(); let mut paths = std::collections::HashMap::new(); - for (id, by, swipe) in wanted { + for (id, by, values, swipe) in wanted { let Some(mut m) = tiny_skia::Mask::new(w, h) else { continue }; match by .as_deref() @@ -7540,6 +7549,25 @@ fn layer_masks( { m.intersect_path(&PathBuilder::from_rect(r), FillRule::Winding, false, Transform::identity()); } + if let Some(values) = values { + // No raster of that name: as with no mask layer, everything shows. One with no pixels + // has no value anywhere, so none of the layer shows (`value_mask::shares`). + let place = match &ctx.globe { + Some(g) => raster::Place::Globe(g), + None => raster::Place::Flat(flat, key), + }; + let shares = map + .layers + .iter() + .find(|l| l.id != id && l.name.eq_ignore_ascii_case(&values.raster)) + .and_then(|l| l.raster.as_ref()) + .and_then(|rl| value_mask::shares(rl, &values, ctx.view, place, w, h, full_res)); + if let Some(shares) = shares { + for (a, s) in m.data_mut().iter_mut().zip(shares) { + *a = ((u16::from(*a) * u16::from(s) + 127) / 255) as u8; + } + } + } out.push((id, m)); } Some(out) diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 140369a0a1..755176fece 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1117,13 +1117,13 @@ fn masks_skip_undrawn_targets_and_reuse_one_complete_source_with_distinct_swipes }; let flat = base.flat(); let scale = base.ground_res_at(&view.camera) / rustgis_geom::PIXEL_M; - let expected = layer_masks(&mut base.clone(), &ctx, 120, 90, &flat, "test", scale, &mut None).unwrap(); + let expected = layer_masks(&mut base.clone(), &ctx, 120, 90, &flat, "test", scale, false, &mut None).unwrap(); let info = streamed(base.layer(mask).unwrap(), 1).source.unwrap().info().unwrap().clone(); let calls = Arc::new(AtomicUsize::new(0)); let mut actual = base.clone(); actual.layer_mut(mask).unwrap().source = Some(SourceLayer::from_path("mask.shp", None, Box::new(Counted { chunks: Chunks { info, ds, size: 1 }, calls: calls.clone() }))); - let got = layer_masks(&mut actual, &ctx, 120, 90, &flat, "test", scale, &mut None).unwrap(); + let got = layer_masks(&mut actual, &ctx, 120, 90, &flat, "test", scale, false, &mut None).unwrap(); assert_eq!(calls.load(Ordering::Relaxed), 1); assert_eq!(got.len(), 2); for ((id, got), (expected_id, expected)) in got.iter().zip(&expected) { @@ -1152,7 +1152,7 @@ fn masks_skip_undrawn_targets_and_reuse_one_complete_source_with_distinct_swipes _ => {} } } - let got = layer_masks(&mut map, &ctx, 120, 90, &flat, "test", scale, &mut None); + let got = layer_masks(&mut map, &ctx, 120, 90, &flat, "test", scale, false, &mut None); if mode == 4 { assert!(got.is_none(), "a failed required mask must still fail the frame"); } else { diff --git a/crates/render/src/value_mask.rs b/crates/render/src/value_mask.rs new file mode 100644 index 0000000000..8a0659e94b --- /dev/null +++ b/crates/render/src/value_mask.rs @@ -0,0 +1,135 @@ +//! A layer's mask from a raster's values (#3147): the raster is drawn as the map draws it (its +//! place, resampling, rotation and the values its style hides), in grey from black a feather past +//! an end of the range to white at it, once for each end, and those greys become the share of each +//! pixel the layer shows. + +use rustgis_map::color::{CustomRamp, RampKind}; +use rustgis_map::effects::ValueMask; +use rustgis_map::raster::{RasterLayer, RasterRenderer, RasterStyle, Stretch}; +use rustgis_map::{Ramp, Rgba}; +use tiny_skia::Pixmap; + +use crate::View; +use crate::raster::{self, Lights, Place}; + +/// The raster value (its pixels are `f32`) nearest past `end`, below it or with `up` above: a cut +/// with no feather fades over the gap up to it, which no value falls in, so it cuts. +fn next_value(end: f64, up: bool) -> f64 { + let v = end as f32; + let past = if up { f64::from(v) > end } else { f64::from(v) < end }; + f64::from(match (past, up) { + (true, _) => v, + (false, true) => v.next_up(), + (false, false) => v.next_down(), + }) +} + +/// The share of each of the `w` × `h` pixels the layer shows (0–255, row by row), as `mask` +/// reads raster layer `rl` (none where it has no pixels, as where it has no value); `None` when a +/// frame for it can't be allocated. +pub(crate) fn shares(rl: &RasterLayer, mask: &ValueMask, view: &View, place: Place, w: u32, h: u32, full_res: bool) -> Option> { + let n = w as usize * h as usize; + let Some(data) = rl.data.as_ref() else { return Some(vec![0; n]) }; + let ramp = Ramp::Custom(Box::new( + CustomRamp::new("mask", RampKind::Sequential, vec![(Some(0.0), Rgba::rgb(0, 0, 0)), (Some(1.0), Rgba::rgb(255, 255, 255))]).ok()?, + )); + // White from `lo` to `hi` (black to white, or the other way with `invert`), its alpha where the + // raster has a value. + let grey = |lo: f64, hi: f64, invert: bool| { + let style = RasterStyle { + renderer: RasterRenderer::Stretch { band: 0, ramp: ramp.clone(), invert }, + stretch: Stretch::Custom { min: lo, max: hi, bands: None }, + dra: false, + resampling: rl.style.resampling, + brightness: 0.0, + contrast: 0.0, + gamma: 1.0, + rotation: rl.style.rotation, + // Values its own style hides are no data, as the map draws them. + mask: rl.style.mask.clone(), + }; + let mut pm = Pixmap::new(w, h)?; + raster::draw(&mut pm, data, &style, None, view, 1.0, full_res, place, Lights::default()); + Some(pm) + }; + // Black a feather below the low end, white at it; white at the high end, black a feather above. + // A feather too small to move the end fades no wider than a cut, and an end no raster value + // lies past (its fade reaches past the largest `f32`) leaves nothing out, as an open one. + let low = match mask.min.map(|lo| ((lo - mask.feather).min(next_value(lo, false)), lo)) { + Some((from, lo)) if from.is_finite() => Some(grey(from, lo, false)?), + _ => None, + }; + let high = match mask.max.map(|hi| (hi, (hi + mask.feather).max(next_value(hi, true)))) { + Some((hi, to)) if to.is_finite() => Some(grey(hi, to, true)?), + _ => None, + }; + // With neither end, wherever the raster has a value. + let any = if low.is_none() && high.is_none() { Some(grey(0.0, 1.0, false)?) } else { None }; + let pixels = |pm: &Option| pm.as_ref().map(|p| p.data().as_chunks::<4>().0.iter().map(|px| (px[0], px[3])).collect::>()); + let (low, high, any) = (pixels(&low), pixels(&high), pixels(&any)); + let share = |i: usize| { + let at = |p: &Option>| p.as_ref().and_then(|p| p.get(i).copied()); + // The pixmaps are premultiplied: a grey g where the raster covers a share a of the pixel + // is g·a in each colour, and the alpha is a. + let (shown, cover) = match (at(&low), at(&high), at(&any)) { + (Some((l, a)), Some((r, _)), _) => (if a == 0 { 0 } else { (u32::from(l) * u32::from(r) / u32::from(a)) as u8 }, a), + (Some((g, a)), None, _) | (None, Some((g, a)), _) => (g, a), + (None, None, Some((_, a))) => (a, a), + _ => (0, 0), + }; + if mask.inside { shown } else { cover.saturating_sub(shown) } + }; + Some((0..n).map(share).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_geom::{Coord, lonlat_to_merc}; + use rustgis_map::Camera; + use rustgis_map::projection::Flat; + use rustgis_map::raster::RasterMask; + + /// Over a raster of one value, every pixel shows the share [`ValueMask::share`] gives it. + #[test] + fn each_pixel_shows_the_share_of_its_value() { + let camera = Camera { center: lonlat_to_merc(Coord::new(5.0, 5.0)), res: 1000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 4.0, height: 4.0, pixels_per_point: 1.0, camera, sky: false }; + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; + for v in [-1e-10, 0.0, 1e-10, 10.0, 17.5, 19.0, 20.0, 30.0, 41.0, 42.5, 50.0] { + let r = Raster::new("v", 10, 10, vec![vec![v as f32; 100]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let rl = RasterLayer::from_path(r, "v.tif"); + for (min, max, inside, feather) in [ + (Some(20.0), Some(40.0), true, 5.0), + (Some(20.0), None, false, 5.0), + (None, Some(40.0), true, 0.0), + (None, None, false, 0.0), + // A cut with no feather, past which no value shows, however near. + (Some(0.0), Some(0.0), true, 0.0), + // A feather too small to move the end, and ends no raster value lies past. + (Some(20.0), None, true, 1e-20), + (Some(-f64::from(f32::MAX)), Some(f64::from(f32::MAX)), true, 0.0), + ] { + let mask = ValueMask { raster: "v".into(), min, max, inside, feather }; + let got = shares(&rl, &mask, &view, Place::Flat(&Flat::Mercator, "mercator"), 4, 4, true).unwrap(); + let want = (mask.share(v) * 255.0).round(); + assert!(got.iter().all(|s| (f64::from(*s) - want).abs() <= 2.0), "{v} in {mask:?}: {got:?}, not {want}"); + } + } + } + + /// A value the mask raster's own style hides is drawn as no data, so it is no value here either. + #[test] + fn a_value_the_mask_rasters_style_hides_has_no_share() { + let camera = Camera { center: lonlat_to_merc(Coord::new(5.0, 5.0)), res: 1000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 4.0, height: 4.0, pixels_per_point: 1.0, camera, sky: false }; + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("v", 10, 10, vec![vec![-9999.0; 100]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let mut rl = RasterLayer::from_path(r, "v.tif"); + rl.style.mask = RasterMask { values: vec![-9999.0], ..RasterMask::default() }; + let mask = ValueMask { raster: "v".into(), min: None, max: Some(1000.0), inside: true, feather: 0.0 }; + let got = shares(&rl, &mask, &view, Place::Flat(&Flat::Mercator, "mercator"), 4, 4, true).unwrap(); + assert_eq!(got, vec![0; 16]); + } +} diff --git a/docs/maintaining.md b/docs/maintaining.md index c10fe17765..f5f6843dbc 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -116,6 +116,8 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol `terrain-block-water-bed` (that water's floor read from a bed raster), `terrain-block-walls-layer` (the layer a block diagram's walls are coloured by), `terrain-block-walls-top` (the band along the top of its walls from a second layer), +`layer-raster-mask` (a layer masked by a raster's values, stored as `raster_mask` or set by a saved +`layer.mask` step whose `"mask"` is an object), `shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour), `shaded-relief-light` (a Shaded Relief's ambient or balanced light), `shaded-relief-shadow-softness` (a softness stored for a Shaded Relief's cast shadows, or set by a saved step; diff --git a/schema/fixtures/layer_raster_mask.rgis b/schema/fixtures/layer_raster_mask.rgis new file mode 100644 index 0000000000..b3517fd6c8 --- /dev/null +++ b/schema/fixtures/layer_raster_mask.rgis @@ -0,0 +1 @@ +{"requires":["layer-raster-mask"],"format":2,"name":"Raster mask","maps":[{"name":"Map","layers":[{"id":1,"name":"slope","visible":true,"dataset":{"name":"slope","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":"slope.tif","file_name":null,"style":{"renderer":{"Stretch":{"band":0,"ramp":"Greys","invert":false}},"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},{"id":2,"name":"Huts","visible":true,"dataset":{"name":"Huts","geometry_type":"Point","fields":[{"name":"depth_km","ty":"Integer","alias":null},{"name":"mag","ty":"Double","alias":null}],"features":[{"id":1,"geometry":{"Point":{"x":142.4,"y":38.3}},"attrs":[{"Int":24},{"Float":7.1}]},{"id":2,"geometry":{"Point":{"x":-70.1,"y":-21.5}},"attrs":[{"Int":180},{"Float":4.6}]}]},"renderer":{"Single":{"fill":[142,27,58,255],"stroke":[255,255,255,255],"stroke_width":1.0,"size":7.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"depth_km","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":true,"graphics":false,"blend":"Normal","mask":null,"raster_mask":{"raster":"slope","min":20.0,"inside":true,"feather":5.0},"display_filters":[],"aggregation":null,"extrusion":null,"priority":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":3}],"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 1a5f3cd00f..2cac7dfd16 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1292,6 +1292,7 @@ "label-clearance", "svg-markers", "label-duplicates", + "layer-raster-mask", "tile-resampling", "layout-page-color", "layout-text-statistics", @@ -1420,6 +1421,7 @@ "label-clearance", "svg-markers", "label-duplicates", + "layer-raster-mask", "tile-resampling", "layout-page-color", "layout-text-statistics",