diff --git a/crates/engine/src/cmd/layer_copy.rs b/crates/engine/src/cmd/layer_copy.rs index 68aa385570..a0a08eb8d7 100644 --- a/crates/engine/src/cmd/layer_copy.rs +++ b/crates/engine/src/cmd/layer_copy.rs @@ -128,6 +128,8 @@ pub(crate) struct Placed { pub groups: Vec, pub unmasked: Vec, names_cut: usize, + /// How many of `unmasked`, at its end, lost a raster mask (#3147) rather than a polygon one. + raster_unmasked: usize, } impl Placed { @@ -141,11 +143,17 @@ impl Placed { false, ); } - match self.unmasked.as_slice() { + let (polygons, rasters) = self.unmasked.split_at(self.unmasked.len().saturating_sub(self.raster_unmasked)); + match polygons { [] => {} [one] => s.notify(format!("{one} lost its mask: {map} has no polygon layer by that name"), false), many => s.notify(format!("{} lost their masks: {map} has no polygon layers by those names", many.join(", ")), false), } + match rasters { + [] => {} + [one] => s.notify(format!("{one} lost its mask: {map} has no raster layer by that name"), false), + many => s.notify(format!("{} lost their masks: {map} has no raster layers by those names", many.join(", ")), false), + } } } @@ -217,16 +225,22 @@ pub(crate) fn place(s: &mut Session, mi: usize, clip: LayerClip, p: &Value) -> R } // A mask follows its layer when that was pasted too; one the map lacks is cleared. Masks are // found as the renderer finds them: the first polygon layer of that name, case aside (ASCII). - let mut unmasked: Vec = Vec::new(); + // A raster mask (#3147) follows its raster the same way, found as a raster layer. + let (mut unmasked, mut raster_unmasked): (Vec, Vec) = (Vec::new(), Vec::new()); for id in &pasted { - let Some(mask) = m.layer(*id).and_then(|l| l.mask.clone()) else { continue }; - let found = mask_target(&mask, copied.iter().filter_map(|(name, id)| m.layer(*id).map(|l| (name.as_str(), l))), m).map(|l| l.id); + let Some((mask, raster)) = m.layer(*id).and_then(mask_name).map(|(n, r)| (n.clone(), r)) else { continue }; + let pasted_layers = copied.iter().filter_map(|(name, id)| m.layer(*id).map(|l| (name.as_str(), l))); + let found = mask_target(&mask, raster, pasted_layers, m, &pasted).map(|l| l.id); let target = found.and_then(|c| m.layer(c)).map(|l| l.name.clone()); if let Some(l) = m.layer_mut(*id) { if target.is_none() { - unmasked.push(l.name.clone()); + if raster { &mut raster_unmasked } else { &mut unmasked }.push(l.name.clone()); + } + match (raster, target) { + (false, target) => l.mask = target, + (true, Some(target)) => l.raster_mask.iter_mut().for_each(|r| r.raster = target.clone()), + (true, None) => l.raster_mask = None, } - l.mask = target; } } let mut group_ids = Vec::new(); @@ -254,7 +268,9 @@ pub(crate) fn place(s: &mut Session, mi: usize, clip: LayerClip, p: &Value) -> R { s.active_layer = Some(*first); } - Ok(Placed { map, layers: pasted, groups: group_ids, unmasked, names_cut }) + let rasters = raster_unmasked.len(); + unmasked.extend(raster_unmasked); + Ok(Placed { map, layers: pasted, groups: group_ids, unmasked, names_cut, raster_unmasked: rasters }) } /// Resolves explicit layer lists and expanded groups with copy's precise active-layer fallback. @@ -311,21 +327,35 @@ fn paste_inputs(input: &super::InputContext<'_>, p: &Value) -> Result>(),"groups":clip.groups.iter().map(|g|(g.id,g.parent,&g.children)).collect::>()}); + inputs.state = json!({"group":group,"clipboard":clip.layers.iter().map(|l|(l.instance_id(),&l.name,&l.mask,&l.raster_mask,crate::policy::input_source(l))).collect::>(),"groups":clip.groups.iter().map(|g|(g.id,g.parent,&g.children)).collect::>()}); Ok(inputs) } -/// Copied polygons win over the destination's first matching polygon, exactly as paste remaps masks. -fn mask_target<'a>(name: &str, copied: impl IntoIterator, destination: &'a Map) -> Option<&'a Layer> { +/// The layer a pasted layer is masked by, and whether it is a raster (#3147). +fn mask_name(l: &Layer) -> Option<(&String, bool)> { + l.mask.as_ref().map(|n| (n, false)).or_else(|| l.raster_mask.as_ref().map(|r| (&r.raster, true))) +} + +/// Copied polygons (or with `raster`, rasters) win over the destination's first matching one, +/// exactly as paste remaps masks. The destination's are those it had: not the `pasted` layers, +/// which a copy's new name could match. +fn mask_target<'a>( + name: &str, + raster: bool, + copied: impl IntoIterator, + destination: &'a Map, + pasted: &[u32], +) -> Option<&'a Layer> { + let masks = |l: &Layer| if raster { l.is_raster() } else { l.geometry_type() == GeometryType::Polygon }; copied .into_iter() - .find(|(was, l)| was.eq_ignore_ascii_case(name) && l.geometry_type() == GeometryType::Polygon) + .find(|(was, l)| was.eq_ignore_ascii_case(name) && masks(l)) .map(|(_, l)| l) - .or_else(|| destination.layers.iter().find(|l| l.name.eq_ignore_ascii_case(name) && l.geometry_type() == GeometryType::Polygon)) + .or_else(|| destination.layers.iter().find(|l| !pasted.contains(&l.id) && l.name.eq_ignore_ascii_case(name) && masks(l))) } diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index f802fc5e2c..571e117f6c 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -1392,6 +1392,30 @@ fn permission_policy_stored_cross_map_clipboard_and_managed_share_targets() { std::fs::remove_dir_all(dir).unwrap(); } +/// A planned paste binds a raster mask's range, not only its raster (#3147): the layer copied again +/// with another range is a changed plan. +#[test] +fn permission_policy_paste_binds_a_raster_masks_range() { + let mut s = world(); + s.leave_downloads = true; + s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": dem_b64()})).unwrap(); + let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone(); + s.run("layer.mask", &json!({"layer": "Cities", "mask": {"raster": dem, "min": 250}})).unwrap(); + s.run("layer.copy", &json!({"layer": "Cities"})).unwrap(); + let steps = json!([ + {"title": "Step", "command": "layer.paste", "params": {}}, + {"title": "Step", "command": "layer.addUrl", "params": {"url": "https://example.invalid/no-send.csv"}} + ]); + s.run("task.new", &json!({"name": "Paste", "steps": steps})).unwrap(); + let (scope, _) = assistant(3147); + let call = Call::command("task.run", json!({"task": "Paste"})); + let p = pending(&s, &scope, &call); + s.run("layer.mask", &json!({"layer": "Cities", "mask": {"raster": dem, "min": 290}})).unwrap(); + s.run("layer.copy", &json!({"layer": "Cities"})).unwrap(); + let e = s.run_permitted(scope, p.allow(), &call).unwrap_err(); + assert!(e.contains("changed"), "{e}"); +} + /// Plugin preparation reads a held streamed source before returning its pinned job. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/engine/src/tests/raster_mask.rs b/crates/engine/src/tests/raster_mask.rs index 928d3ecacc..3b9d2070b8 100644 --- a/crates/engine/src/tests/raster_mask.rs +++ b/crates/engine/src/tests/raster_mask.rs @@ -98,3 +98,54 @@ fn a_layer_shows_only_where_the_rasters_values_are_in_its_range() { 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"); } + +/// A pasted layer's raster mask follows its raster when that was pasted too, else the destination's +/// raster of that name; with none, it is cleared and said, as a polygon mask is. +#[test] +fn a_pasted_layer_takes_its_raster_mask_to_the_raster_of_that_name() { + let (mut s, dem) = with_dem(); + let range = json!({"raster": dem, "min": 250, "feather": 5}); + s.run("layer.mask", &json!({"layer": "Countries", "mask": range})).unwrap(); + let mask_of = + |s: &Session, layer: &str| s.map().layer_by_name(layer).unwrap().raster_mask.clone().map(|m| (m.raster, m.min, m.feather)); + let lost = |s: &Session, mark| s.notices_since(mark).iter().filter(|n| n.text.contains("lost its mask")).count(); + // With its raster, into the same map: the copy is masked by the copied raster. + let clean = s.notice_mark(); + s.run("group.add", &json!({"name": "Relief", "layers": ["Countries", dem]})).unwrap(); + s.run("layer.copy", &json!({"group": "Relief"})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + assert_eq!(mask_of(&s, "Countries copy"), Some((format!("{dem} copy"), Some(250.0), 5.0))); + // Alone, into the same map: still the map's raster of that name. + s.run("layer.copy", &json!({"layer": "Countries"})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + assert_eq!(mask_of(&s, "Countries copy 2"), Some((dem.clone(), Some(250.0), 5.0))); + assert_eq!(lost(&s, clean), 0, "a mask that found its raster is said lost nowhere"); + // Into a map with no raster of that name: cleared, and said. + s.run("map.new", &json!({"name": "Second"})).unwrap(); + let mark = s.notice_mark(); + let r = s.run("layer.paste", &Value::Null).unwrap(); + assert_eq!((r["unmasked"].clone(), mask_of(&s, "Countries")), (json!(["Countries"]), None)); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n.contains("Countries lost its mask") && n.contains("no raster layer")), "{said:?}"); +} + +/// A pasted layer is never its own mask: renamed on paste to its mask's name, it isn't found as +/// that raster in the destination, so with none other there its mask is cleared and said. +#[test] +fn a_pasted_layer_named_as_its_mask_isnt_masked_by_itself() { + let (mut s, dem) = with_dem(); + let first = s.map().name.clone(); + // A second map with the DEM alone, and in the first a copy of it masking the DEM. + s.run("layer.copy", &json!({"layer": dem})).unwrap(); + s.run("map.new", &json!({"name": "Second"})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + s.run("map.activate", &json!({"name": first})).unwrap(); + s.run("layer.paste", &Value::Null).unwrap(); + s.run("layer.mask", &json!({"layer": dem, "mask": {"raster": format!("{dem} copy"), "min": 250}})).unwrap(); + // The masked DEM pasted alone into the second map is renamed " copy", its mask's name. + s.run("layer.copy", &json!({"layer": dem})).unwrap(); + s.run("map.activate", &json!({"name": "Second"})).unwrap(); + let r = s.run("layer.paste", &Value::Null).unwrap(); + let pasted = s.map().layer_by_name(&format!("{dem} copy")).unwrap(); + assert_eq!((pasted.raster_mask.clone(), r["unmasked"].clone()), (None, json!([format!("{dem} copy")]))); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f4621419d2..0e4f9904ca 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -7431,7 +7431,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, 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`. +/// `None` when a mask can't be allocated or its read failed; a failed read returns its source +/// layer's identity through `failed_source`. fn layer_masks( map: &mut Map, ctx: &Ctx, @@ -7456,7 +7457,8 @@ fn layer_masks( let mut out = Vec::new(); let mut paths = std::collections::HashMap::new(); for (id, by, values, swipe) in wanted { - let Some(mut m) = tiny_skia::Mask::new(w, h) else { continue }; + // A mask that can't be allocated fails the frame: drawn unmasked, its layer would be whole. + let mut m = tiny_skia::Mask::new(w, h)?; match by .as_deref() .and_then(|n| map.layers.iter().position(|l| l.name.eq_ignore_ascii_case(n) && l.geometry_type() == GeometryType::Polygon)) @@ -7558,13 +7560,10 @@ fn layer_masks( 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 { + // A raster of that name, past any other layer named so, as a polygon mask finds polygons. + let raster = map.layers.iter().find(|l| l.id != id && l.is_raster() && l.name.eq_ignore_ascii_case(&values.raster)); + if let Some(rl) = raster.and_then(|l| l.raster.as_ref()) { + let shares = value_mask::shares(rl, &values, ctx.view, place, w, h, full_res)?; for (a, s) in m.data_mut().iter_mut().zip(shares) { *a = ((u16::from(*a) * u16::from(s) + 127) / 255) as u8; } diff --git a/crates/render/src/value_mask.rs b/crates/render/src/value_mask.rs index 8a0659e94b..5a2df05660 100644 --- a/crates/render/src/value_mask.rs +++ b/crates/render/src/value_mask.rs @@ -50,7 +50,8 @@ pub(crate) fn shares(rl: &RasterLayer, mask: &ValueMask, view: &View, place: Pla }; let mut pm = Pixmap::new(w, h)?; raster::draw(&mut pm, data, &style, None, view, 1.0, full_res, place, Lights::default()); - Some(pm) + // Each pixel's grey and alpha, the frame dropped as soon as they are read. + Some(pm.data().as_chunks::<4>().0.iter().map(|px| (px[0], px[3])).collect::>()) }; // 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 @@ -65,8 +66,6 @@ pub(crate) fn shares(rl: &RasterLayer, mask: &ValueMask, view: &View, place: Pla }; // 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 @@ -132,4 +131,49 @@ mod tests { let got = shares(&rl, &mask, &view, Place::Flat(&Flat::Mercator, "mercator"), 4, 4, true).unwrap(); assert_eq!(got, vec![0; 16]); } + + /// The masks `layer_masks` gives `map` over a `w` × 4 frame at 5° E 5° N. + fn masks_of(map: &mut rustgis_map::Map, w: u32) -> Option> { + 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 ctx = crate::Ctx { + view: &view, + ppp: 1.0, + wireframe: false, + cull: rustgis_geom::Extent::EMPTY, + globe: None, + sprites: Default::default(), + bursts: Default::default(), + }; + let (flat, scale) = (map.flat(), map.ground_res_at(&view.camera) / rustgis_geom::PIXEL_M); + crate::layer_masks(map, &ctx, w, 4, &flat, "test", scale, false, &mut None) + } + + /// A mask that can't be allocated fails the frame rather than drawing its layer whole. + #[test] + fn a_mask_that_cant_be_allocated_fails_the_frame() { + let mut map = rustgis_map::Map::new("masks"); + let id = map.add_dataset(rustgis_data::Dataset::new("target", rustgis_data::GeometryType::Polygon, vec![])); + map.layer_mut(id).unwrap().raster_mask = + Some(ValueMask { raster: "v".into(), min: Some(1.0), max: None, inside: true, feather: 0.0 }); + assert!(masks_of(&mut map, 0).is_none()); + } + + /// A raster mask reads the raster of its name, past a polygon layer of the same name before it. + #[test] + fn a_raster_mask_reads_its_raster_past_a_polygon_of_that_name() { + let mut map = rustgis_map::Map::new("masks"); + map.add_dataset(rustgis_data::Dataset::new("v", rustgis_data::GeometryType::Polygon, vec![])); + 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![10.0; 100]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + map.add_raster("v", RasterLayer::from_path(r, "v.tif")); + let id = map.add_dataset(rustgis_data::Dataset::new("target", rustgis_data::GeometryType::Polygon, vec![])); + // The polygon layer first, as the lookup meets it. + map.layers.sort_by_key(|l| l.is_raster()); + map.layer_mut(id).unwrap().raster_mask = + Some(ValueMask { raster: "v".into(), min: Some(1000.0), max: None, inside: true, feather: 0.0 }); + let masks = masks_of(&mut map, 4).unwrap(); + let mask = masks.iter().find(|(m, _)| *m == id).map(|(_, m)| m.data().to_vec()); + assert_eq!(mask, Some(vec![0; 16]), "no value of the raster is 1000 or more"); + } } diff --git a/crates/ui-egui/src/layerprops.rs b/crates/ui-egui/src/layerprops.rs index e3d5ecc66b..9b09c06ca1 100644 --- a/crates/ui-egui/src/layerprops.rs +++ b/crates/ui-egui/src/layerprops.rs @@ -449,18 +449,24 @@ fn blend_row(app: &mut RustGisApp, ui: &mut Ui, l: &Layer) { }); } -/// The polygon layer the layer shows only inside (`layer.mask`), as the ribbon's Masking menu -/// offers it. +/// The polygon layer the layer shows only inside, or the raster whose values it shows by +/// (`layer.mask`), as the ribbon's Masking menu offers them. fn mask_row(app: &mut RustGisApp, ui: &mut Ui, l: &Layer) { let choices = crate::ribbon::mask_choices(app, l); + let unmasked = l.mask.is_none() && l.raster_mask.is_none(); ui.horizontal(|ui| { let input_label = ui.label(tl!("Masking")); let none = tl!("No mask").to_string(); + let shown = match (&l.mask, &l.raster_mask) { + (Some(n), _) => n.clone(), + (None, Some(m)) => crate::i18n::fmt("{raster} values", &[("raster", &m.raster)]), + (None, None) => none.clone(), + }; egui::ComboBox::from_id_salt("layer_properties_mask") - .selected_text(l.mask.clone().unwrap_or_else(|| none.clone())) + .selected_text(shown) .width(130.0) .show_ui(ui, |ui| { - if ui.selectable_label(l.mask.is_none(), none).clicked() && l.mask.is_some() { + if ui.selectable_label(unmasked, none).clicked() && !unmasked { run(app, "layer.mask", json!({"layer": l.id, "mask": null})); } for n in &choices { @@ -473,6 +479,10 @@ fn mask_row(app: &mut RustGisApp, ui: &mut Ui, l: &Layer) { .response .labelled_by(input_label.id); }); + egui::CollapsingHeader::new(tl!("Mask by a raster's values")) + .id_salt(("layer_properties_raster_mask", l.id)) + .default_open(l.raster_mask.is_some()) + .show(ui, |ui| crate::ribbon::raster_mask_form(ui, app, l)); } /// The layer's binding to the time slider (`time.bind`, `time.unbind`), as the slider's Layers diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 5f69e2710c..f91b6a9767 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4,6 +4,7 @@ use egui::{Align2, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2}; use rustgis_engine::Tool; use rustgis_engine::data::GeometryType; +use rustgis_engine::map::effects::ValueMask; use rustgis_engine::map::planets::EARTH_BASEMAP; use rustgis_engine::map::view::Weather; use rustgis_engine::map::{Basemap, RasterRenderer, Renderer, Resampling, Stretch}; @@ -4518,12 +4519,14 @@ pub(crate) fn mask_choices(app: &RustGisApp, layer: &rustgis_engine::map::Layer) .collect() } -/// The polygon layers that could mask `layer`. +/// The polygon layers that could mask `layer`, and a raster's values (#3147). fn mask_menu(ui: &mut Ui, app: &mut RustGisApp, layer: &rustgis_engine::map::Layer) { let polys = mask_choices(app, layer); let cur = layer.mask.clone(); - small_menu(ui, app, "polygon_layer", "Masking", "Show the layer only inside another layer's polygons.", move |ui, app| { - if ui.radio(cur.is_none(), tl!("No mask")).clicked() { + let unmasked = cur.is_none() && layer.raster_mask.is_none(); + let desc = "Show the layer only inside another layer's polygons, or where a raster's values are in a range."; + small_form_menu(ui, app, "polygon_layer", "Masking", desc, |ui, app| { + if ui.radio(unmasked, tl!("No mask")).clicked() { let _ = app.run("layer.mask", json!({"mask": null})); ui.close(); } @@ -4533,9 +4536,97 @@ fn mask_menu(ui: &mut Ui, app: &mut RustGisApp, layer: &rustgis_engine::map::Lay ui.close(); } } + ui.separator(); + raster_mask_form(ui, app, layer); }); } +/// The raster mask being set in [`raster_mask_form`]: the raster, the ends (blank for an open +/// one) and the feather as typed, and whether the layer shows outside the range. +#[derive(Clone, Default)] +struct RasterMaskForm { + raster: String, + min: String, + max: String, + feather: String, + outside: bool, +} + +impl RasterMaskForm { + /// The form for a layer's raster mask `mask`, or for a new one on `raster`. + fn of(mask: Option<&ValueMask>, raster: &str) -> RasterMaskForm { + match mask { + Some(m) => RasterMaskForm { + raster: m.raster.clone(), + min: m.min.map(|v| v.to_string()).unwrap_or_default(), + max: m.max.map(|v| v.to_string()).unwrap_or_default(), + feather: m.feather.to_string(), + outside: !m.inside, + }, + None => RasterMaskForm { raster: raster.to_string(), feather: "0".into(), ..RasterMaskForm::default() }, + } + } +} + +/// The form [`raster_mask_form`] shows, with the layer's mask it started from: the one `kept` +/// from the last frame while the layer's raster mask `mask` is still that one, else one from +/// `mask` (or a new one on `raster`), so an undo or another command shows in it. +fn raster_mask_draft( + kept: Option<(RasterMaskForm, Option)>, + mask: Option<&ValueMask>, + raster: &str, +) -> (RasterMaskForm, Option) { + match kept { + Some((form, started)) if started.as_ref() == mask => (form, started), + _ => (RasterMaskForm::of(mask, raster), mask.cloned()), + } +} + +/// Masks `layer` by a raster's values (`layer.mask` with a range, #3147): the raster, the range +/// (either end left blank), the feather in the raster's units and whether it shows outside. It +/// starts from the layer's raster mask; the command says what it refuses. The ribbon's Masking +/// menu and the Layer Properties pane show the same form. +pub(crate) fn raster_mask_form(ui: &mut Ui, app: &mut RustGisApp, layer: &rustgis_engine::map::Layer) { + let rasters: Vec = + app.session.map().layers.iter().filter(|l| l.id != layer.id && l.is_raster()).map(|l| l.name.clone()).collect(); + if rasters.is_empty() { + ui.label(egui::RichText::new(tl!("Add a raster to mask by its values.")).small().weak()); + return; + } + let id = egui::Id::unique(("raster_mask_form", layer.id)); + let kept = ui.data(|d| d.get_temp::<(RasterMaskForm, Option)>(id)); + let (mut f, started) = raster_mask_draft(kept, layer.raster_mask.as_ref(), &rasters[0]); + ui.label(egui::RichText::new(tl!("Where a raster's values are in a range:")).small().weak()); + egui::Grid::new(("raster_mask_grid", layer.id)).num_columns(2).show(ui, |ui| { + let label = ui.label(tl!("Raster")); + egui::ComboBox::from_id_salt(("raster_mask_raster", layer.id)) + .selected_text(f.raster.as_str()) + .show_ui(ui, |ui| { + for r in &rasters { + ui.selectable_value(&mut f.raster, r.clone(), r.as_str()); + } + }) + .response + .labelled_by(label.id); + ui.end_row(); + for (name, text, hint) in [("Min", &mut f.min, "open"), ("Max", &mut f.max, "open"), ("Feather", &mut f.feather, "0")] { + let label = ui.label(tl!(name)); + ui.add(egui::TextEdit::singleline(text).hint_text(tl!(hint)).desired_width(80.0)).labelled_by(label.id); + ui.end_row(); + } + }); + ui.checkbox(&mut f.outside, tl!("Show it outside the range")) + .on_hover_text(tl!("Past an end, the layer fades in or out over the feather, in the raster's units.")); + if ui.button(tl!("Mask by Values")).clicked() { + let end = |t: &str| if t.trim().is_empty() { Value::Null } else { json!(t.trim()) }; + let range = json!({"raster": f.raster, "min": end(&f.min), "max": end(&f.max), "inside": !f.outside, "feather": end(&f.feather)}); + if app.run("layer.mask", json!({"layer": layer.id, "mask": range})).is_ok() { + ui.close(); + } + } + ui.data_mut(|d| d.insert_temp(id, (f, started))); +} + /// Masking, display filters, aggregation and extrusion for feature layers. fn effects_groups(app: &mut RustGisApp, ui: &mut Ui, layer: &rustgis_engine::map::Layer) { let gt = layer.geometry_type(); @@ -5878,6 +5969,20 @@ fn language_menu(app: &mut RustGisApp, ui: &mut Ui) { #[cfg(test)] mod tests { + /// The raster mask form keeps what is typed while the layer's mask stays as it was, and starts + /// again from the mask when an undo or another command changes it (#3147). + #[test] + fn the_raster_mask_form_starts_again_when_the_layers_mask_changes() { + let m = |min| ValueMask { raster: "Slope".into(), min: Some(min), max: None, inside: true, feather: 5.0 }; + let (mut typed, started) = raster_mask_draft(None, Some(&m(25.0)), "Slope"); + assert_eq!((typed.min.as_str(), typed.feather.as_str()), ("25", "5")); + typed.min = "40".into(); + let kept = Some((typed, started)); + assert_eq!(raster_mask_draft(kept.clone(), Some(&m(25.0)), "Slope").0.min, "40"); + assert_eq!(raster_mask_draft(kept.clone(), Some(&m(30.0)), "Slope").0.min, "30"); + assert_eq!(raster_mask_draft(kept, None, "Slope").0.min, ""); + } + use super::*; use egui_kittest::kittest::Queryable; diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index bff2bf87ac..62aeb51ea0 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -972,6 +972,15 @@ For a raster layer, the **Style** tab also has **Layer Blend** (multiply, screen darken, lighten, difference), **Swipe** (the layer shows only left of a divider you slide, to compare it with what's beneath), **Masking** and **Rotation**. +**Masking** can also show a layer only where a raster's values are in a range, such as a rock +texture on slopes above 25° or a shading on the plains below 300 m. Pick the **Raster** (a slope +or height raster made by a tool, or any other), a **Min** and a **Max** (leave either blank for an +open end) and a **Feather** in the raster's units: past an end the layer fades out over that width +instead of being cut, so a feather of 5 on a minimum of 25° fades it in from 20°. **Show it outside +the range** turns it round. Where the raster has no value, the layer is hidden. The raster is read +as the map draws it, and it may be hidden itself. The Layer Properties pane's Display tab has the +same choices (`layer.mask` with `{"raster", "min", "max", "inside", "feather"}`). + ## Graphics **Edit › Graphics** draws shapes in a graphics layer (**Home › Add › Add Data › Graphics Layer**, or