From 53c501e488dd413f65894e6a5d6fcdc7fba788fc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:28:50 +0000 Subject: [PATCH] Layers: hold R over the model to see the layers there and pick one Holding R over the 3D view with any tool shows a label at the pointer naming the top layer laying something down there (any channel in the material view, the shown one in a single-channel view) and how many more. A click selects the layer when it is the only one there; with several it opens a list at the pointer, top first, each row with the layer's thumbnail, name and the channels it changes at that spot. A row click (or Up/Down and Enter) selects that layer, Esc or a click elsewhere closes the list. The click never paints. Hidden layers, masked-out layers and channels at zero opacity are left out. Closed folders holding the picked layer open and its row scrolls into view. The shortcut window lists the gesture. Automation lists the layers with layer.layersAt and selects one with layer.pickAt. --- crates/compose/src/eval.rs | 2 + crates/compose/src/eval/layers_at.rs | 84 ++++++++++ crates/compose/src/lib.rs | 4 +- crates/engine/src/layer_cmds.rs | 40 +++++ crates/engine/src/layer_pick.rs | 69 ++++++++ crates/engine/src/lib.rs | 1 + crates/engine/tests/it/layer_pick.rs | 102 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 6 +- crates/ui-egui/src/keymap.rs | 3 + crates/ui-egui/src/layer_panel.rs | 15 +- crates/ui-egui/src/layer_pick_list.rs | 209 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/viewport.rs | 75 ++++++++- crates/ui-egui/tests/it/layers_panel.rs | 71 +++++++- docs/features.md | 5 + 16 files changed, 681 insertions(+), 10 deletions(-) create mode 100644 crates/compose/src/eval/layers_at.rs create mode 100644 crates/engine/src/layer_pick.rs create mode 100644 crates/engine/tests/it/layer_pick.rs create mode 100644 crates/ui-egui/src/layer_pick_list.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index f96dd739..09041f47 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,6 +4,7 @@ mod draw_placement; mod evaluation_inputs; +mod layers_at; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -42,6 +43,7 @@ use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; +pub use layers_at::layers_at; const NCH: usize = Channel::ALL.len(); diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs new file mode 100644 index 00000000..648dcb4c --- /dev/null +++ b/crates/compose/src/eval/layers_at.rs @@ -0,0 +1,84 @@ +//! Which layers lay something down at one texel, for the viewport's Pick layer tool + +use super::{ + BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, + evaluation_fields, plan, +}; + +/// Below this weight a layer leaves the texel unchanged (one 16-bit step) +const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0; + +/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down +pub fn layers_at(inputs: &Inputs, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec)> { + let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() }; + let gbuf = inputs.gbuf; + let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI); + if !covered { + return Vec::new(); + } + + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); + let channels = evaluation_channels(inputs, set.channel_list()); + + // Filters and anchors can read texels outside this one's tile: the fields cover what it reads + let (tile_x, tile_y) = (x / TILE, y / TILE); + let fields = evaluation_fields(inputs, &channels, &[(tile_x, tile_y)]); + let nodes = plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)); + let offset = ((y % TILE) * TILE + x % TILE) as usize; + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + + // The whole stack runs first, so masks and fills that read anchors find them + let mut values = Channel::ALL.map(Channel::default_value); + texel.eval(&nodes, &mut values); + + let mut found = Vec::new(); + texel.layers_laying_down(&nodes, [1.0; NCH], shown, &mut found); + + // The stack runs bottom first + found.reverse(); + found +} + +impl Texel<'_, '_> { + /// Push the leaf layers among `nodes` (bottom first) that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them) + fn layers_laying_down(&mut self, nodes: &[Node], weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { + for node in nodes { + let mask = self.node_mask(node); + if mask <= 0.0 { + continue; + } + + let mut node_weights = [0.0; NCH]; + for chan in node.chans.iter().filter(|chan| shown.iter().any(|channel| channel.index() == chan.ch)) { + if let (Some(weight), Some(slot)) = (weights.get(chan.ch), node_weights.get_mut(chan.ch)) { + *slot = weight * chan.opacity * mask; + } + } + + match &node.content { + Content::Group(children) => self.layers_laying_down(children, node_weights, shown, found), + content => { + let changed: Vec = shown + .iter() + .copied() + .filter(|channel| { + node.chans.iter().filter(|chan| chan.ch == channel.index()).any(|chan| { + let weight = node_weights.get(chan.ch).copied().unwrap_or(0.0); + + // Replace lays its value down at full weight wherever the layer has content + weight > SMALLEST_WEIGHT + && self + .content(content, chan) + .is_some_and(|(_, coverage)| chan.blend == BlendMode::Replace || weight * coverage > SMALLEST_WEIGHT) + }) + }) + .collect(); + if !changed.is_empty() { + found.push((node.draw.0, changed)); + } + } + } + } + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f931da06..1f4ff850 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -55,8 +55,8 @@ pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, - stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_texels, mask_values, + pad_tiles, stack_reads_neighbours, }; pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 4a1f6c7b..7b377ba8 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -87,6 +87,24 @@ pub fn specs() -> Vec { always, select ), + cmd!( + "layer.layersAt", + "Layers under the cursor", + [], + None, + "{x, y, viewport?: [w,h]} a point on the mesh — {layers: [{layer, name, channels}]}: the layers laying something down there in the shown channels, top first, each with the channels it changes there (R + click lists them)", + always, + layers_at + ), + cmd!( + "layer.pickAt", + "Pick layer under the cursor", + [], + None, + "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects `layer` if it lays something down there, else the top layer laying something down there in the shown channels (R + click)", + always, + pick_at + ), cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename), cmd!( "layer.visible", @@ -282,6 +300,28 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { folder } +fn pick_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) }; + let viewport = crate::tool_cmds::viewport_of(s, p); + let wanted = u64p(p, "layer").map(LayerId); + let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?; + Ok(json!({ "layer": id.0 })) +} + +fn layers_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.layersAt", "`x` and `y` are required")) }; + let viewport = crate::tool_cmds::viewport_of(s, p); + let (_, layers) = s.layers_under(texturecraft_geom::glam::Vec2::new(x, y), viewport)?; + let layers: Vec = layers + .iter() + .map(|(id, channels)| { + let name = s.doc.project.layers.get(id).map(|layer| layer.name.as_str()).unwrap_or_default(); + json!({ "layer": id.0, "name": name, "channels": channels.iter().map(|channel| channel.id()).collect::>() }) + }) + .collect(); + Ok(json!({ "layers": layers })) +} + fn select(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { return crate::layer_selection::select_all(s); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs new file mode 100644 index 00000000..9107fb3e --- /dev/null +++ b/crates/engine/src/layer_pick.rs @@ -0,0 +1,69 @@ +//! Picking a layer on the mesh (R + click in the viewport, `layer.layersAt` and `layer.pickAt`): the layers laying something down where the mesh is clicked, and selecting one of them + +use texturecraft_core::{Channel, LayerId, LayerKind}; +use texturecraft_geom::glam::Vec2; + +use crate::session::ViewMode; +use crate::{EngineError, Result, Session, StackTarget}; + +/// A texture set and the layers laying something down at one of its texels, top first, each with the channels it changes there +pub type LayersUnder = (usize, Vec<(LayerId, Vec)>); + +impl Session { + /// The texture set and texel of the mesh under `screen`, None off the mesh + pub fn texel_under(&self, screen: Vec2, viewport: Vec2) -> Option<(usize, (u32, u32))> { + let hit = self.pick(screen, viewport)?; + let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); + let (width, height) = self.caches.get(ts).map(|cache| (cache.size.0 as f32, cache.size.1 as f32))?; + let texel = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + Some((ts, texel)) + } + + /// The layers laying something down at `texel` of texture set `ts` in the shown channels (every channel outside a single-channel view), top first, each with the channels it changes there + pub fn layers_at_texel(&self, ts: usize, texel: (u32, u32)) -> Vec<(LayerId, Vec)> { + let shown = match self.view { + ViewMode::Channel(channel) => vec![channel], + _ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(), + }; + self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, texel, &shown))).unwrap_or_default() + } + + /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) + pub fn layers_under(&self, screen: Vec2, viewport: Vec2) -> Result { + let (ts, texel) = self.texel_under(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + Ok((ts, self.layers_at_texel(ts, texel))) + } + + /// Select `wanted` when it lays something down under `screen`, else the top layer there + pub fn pick_layer(&mut self, screen: Vec2, viewport: Vec2, wanted: Option) -> Result { + let (ts, layers) = self.layers_under(screen, viewport)?; + let picked = match wanted { + Some(wanted) => layers.iter().find(|(id, _)| *id == wanted).ok_or_else(|| EngineError::Other("that layer lays nothing down here".into()))?, + None => layers.first().ok_or_else(|| EngineError::Other("no visible layer lays anything down here".into()))?, + }; + let id = picked.0; + + // Paths paint into the active set, and the clone source is a point of the set it was picked in + if ts != self.ts() { + self.finish_path()?; + self.tool.clone_source = None; + } + self.active_set = ts; + self.select_one(ts, id); + self.open_folders_holding(id); + self.target = StackTarget::Content; + self.revision = self.revision.wrapping_add(1); + Ok(id) + } + + /// Expand every collapsed folder holding `id`, so the Layers panel shows its row + fn open_folders_holding(&mut self, id: LayerId) { + let mut child = id; + while let Some((_, Some(folder), _)) = self.doc.project.locate(child) { + if let Some(LayerKind::Group { collapsed, .. }) = self.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = false; + } + child = folder; + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7a700ca5..c6decb59 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; pub mod layer_ops; +mod layer_pick; pub mod layer_selection; pub mod link_cmds; pub mod log; diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs new file mode 100644 index 00000000..dcd8d38d --- /dev/null +++ b/crates/engine/tests/it/layer_pick.rs @@ -0,0 +1,102 @@ +//! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerKind; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The middle of the sphere in the test viewport, where the lower paint layer is painted +const MIDDLE: [f32; 2] = [200.0, 200.0]; + +/// A spot on the sphere left of the middle, where only the upper paint layer is painted +const LEFT: [f32; 2] = [130.0, 200.0]; + +/// The test stack: (session, the fill at the bottom, a paint layer over the middle, a paint layer over the left spot above it) +fn stack() -> (Session, u64, u64, u64) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let middle = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 100})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[190, 200], [210, 200]]})).unwrap(); + let left = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.stroke", &json!({"points": [[125, 200], [135, 200]]})).unwrap(); + s.update(); + (s, fill, middle, left) +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn click(s: &mut Session, [x, y]: [f32; 2]) -> Option { + execute(s, "layer.pickAt", &json!({"x": x, "y": y})).ok().map(id) +} + +/// The layers `layer.layersAt` lists at a spot, top first, each with the channels it changes there +fn layers_at(s: &mut Session, [x, y]: [f32; 2]) -> Vec<(u64, Vec)> { + let reply = execute(s, "layer.layersAt", &json!({"x": x, "y": y})).unwrap(); + let channels = |row: &Value| row["channels"].as_array().unwrap().iter().map(|channel| channel.as_str().unwrap().to_owned()).collect(); + reply["layers"].as_array().unwrap().iter().map(|row| (id(row.clone()), channels(row))).collect() +} + +#[test] +fn a_spot_lists_the_layers_laying_something_there_top_first_and_a_pick_selects_the_one_asked_for() { + let (mut s, fill, middle, left) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "roughness", "opacity": 0.0})).unwrap(); + + let listed = layers_at(&mut s, MIDDLE); + let order: Vec = listed.iter().map(|(layer, _)| *layer).collect(); + assert_eq!(order, [middle, fill], "the layer painted elsewhere is left out; the top one comes first"); + assert!( + !listed[0].1.contains(&"roughness".to_owned()) && listed[1].1.contains(&"roughness".to_owned()), + "a channel at zero opacity is not among the ones the layer changes there" + ); + + assert_eq!(click(&mut s, MIDDLE), Some(middle), "a plain pick selects the top layer"); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the same spot again keeps the top layer"); + let picked = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": fill})).map(id).ok(); + assert_eq!(picked, Some(fill), "a listed layer is selected when asked for"); + assert_eq!(s.selected_layer_id().map(|layer| layer.0), Some(fill)); + assert!( + execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": left})).is_err(), + "a layer not laying anything down there is refused" + ); + assert_eq!(click(&mut s, LEFT), Some(left), "another spot picks its own top layer"); +} + +#[test] +fn hidden_layers_and_channels_out_of_view_lay_nothing_down() { + let (mut s, fill, middle, _) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "baseColor", "opacity": 0.0})).unwrap(); + execute(&mut s, "viewport.view", &json!({"mode": "baseColor"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "in the base colour view the layer at zero base colour opacity shows nothing"); + + execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the material view counts its other channels"); + + execute(&mut s, "layer.visible", &json!({"layer": middle, "visible": false})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "a hidden layer is skipped"); +} + +#[test] +fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() { + let (mut s, _, middle, _) = stack(); + execute(&mut s, "layer.group", &json!({"layer": middle})).unwrap(); + let inner = s.selected_layer_id().unwrap(); + execute(&mut s, "layer.group", &json!({"layer": inner.0})).unwrap(); + let outer = s.selected_layer_id().unwrap(); + for folder in [inner, outer] { + if let Some(LayerKind::Group { collapsed, .. }) = s.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = true; + } + } + + assert_eq!(click(&mut s, MIDDLE), Some(middle)); + + let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. }); + assert!(open(inner) && open(outer), "both folders holding the picked layer are open"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a1cf0a97..3aaf5cc2 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -42,6 +42,7 @@ mod gradient_map; mod high_poly_missed; mod instances; mod layer_multi_select; +mod layer_pick; mod mask_clone_smudge; mod mask_export; mod mask_fill_source; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3204a6e6..9a503041 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -271,7 +271,7 @@ const SELECTED_LAYER_TINT: f32 = 0.3; const EYE_CHIP_INSET: f32 = 1.0; const EYE_CHIP_ROUNDING: f32 = 4.0; /// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. -const THUMBNAIL_ROUNDING: f32 = 2.0; +pub(crate) const THUMBNAIL_ROUNDING: f32 = 2.0; const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; const HIDDEN_STRIKE_WIDTH: f32 = 1.5; const DROP_LINE_WIDTH: f32 = 2.0; @@ -455,6 +455,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let row_height = layer_row_height(preferred_size); let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); + if app.layer_panel.reveal == Some(layer.id) { + app.layer_panel.reveal = None; + row.scroll_to_me(None); + } // Background, folder lines, the selected rows' accent edge and the colour tag let painter = ui.painter().clone(); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index ee29ac48..7b318972 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -642,6 +642,7 @@ pub fn fixed_gestures_grid(ui: &mut egui::Ui) { pub fn fixed_gestures() -> Vec<(String, String)> { let stencil = crate::viewport::STENCIL_KEY.name(); let clone = crate::viewport::CLONE_SOURCE_KEY.name(); + let pick = crate::viewport::PICK_LAYER_KEY.name(); let keyed = |template: &str| trf(template, &[("key", &stencil)]); vec![ (tr("Alt + LMB drag").into(), tr("Orbit").into()), @@ -663,6 +664,7 @@ pub fn fixed_gestures() -> Vec<(String, String)> { (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), + (trf("{key} + LMB", &[("key", &pick)]), tr("Select the layer under the cursor; several there: pick one from a list").into()), (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), (tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()), @@ -696,6 +698,7 @@ mod tests { let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name()); assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move")); assert!(has(&format!("{v} + LMB"), "Clone")); + assert!(has(&format!("{} + LMB", crate::viewport::PICK_LAYER_KEY.name()), "Select the layer")); for (gesture, what) in [ ("Shift + LMB", "straight line"), ("Shift + RMB drag", "environment light"), diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index d5390546..b3efe33b 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -7,6 +7,7 @@ use std::time::Duration; use egui::{Context, TextureHandle, TextureId, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::LayerId; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use crate::TextureCraftApp; @@ -44,18 +45,28 @@ pub struct LayerPanel { pictures_begun: bool, /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. pub(crate) folded: HashSet<(u64, bool)>, + /// The selected layer the panel last drew, and the one whose row scrolls into view because the selection moved to it (a pick on the mesh, a command) + shown_selection: Option, + pub(crate) reveal: Option, } /// How soon to look again for pictures still rendering (milliseconds) const POLL_INTERVAL_MS: u64 = 40; impl LayerPanel { - /// Start drawing the panel for this frame. + /// Start drawing the panel for this frame pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.begin_pictures(session, now); + // A newly selected layer scrolls into view once + let selected = session.selected_layer(); + if selected != self.shown_selection { + self.shown_selection = selected; + self.reveal = selected; + } + // Deleted layer IDs must not accumulate in panel state - self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); + self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&LayerId(*layer))); } /// Advance the picture frame once, whether the panel or a picture outside it asks first diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs new file mode 100644 index 00000000..39558758 --- /dev/null +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -0,0 +1,209 @@ +//! The layers under the pointer while R is held over the 3D view: a label names the top one live, and a click lists every layer there to pick from + +use egui::{Color32, Key, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::session::ViewMode; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The list's row height, thumbnail side and the room around a row's contents (points) +const ROW_HEIGHT: f32 = 36.0; +const THUMBNAIL_SIZE: f32 = 28.0; +const ROW_PADDING: f32 = 6.0; + +/// The narrowest the list gets, so short names still give a comfortable click target (points) +const MIN_LIST_WIDTH: f32 = 160.0; + +/// How far the list sits right of and below the click, clear of the pointer (points) +const LIST_OFFSET: f32 = 8.0; + +/// Gap the list keeps from the view's edges +const VIEW_MARGIN: f32 = 4.0; + +/// Room between the list's frame and its rows (points) +const LIST_MARGIN: i8 = 2; + +/// Text sizes of a row's name and of the channels line under it +const NAME_FONT_SIZE: f32 = 12.0; +const CHANNELS_FONT_SIZE: f32 = 11.0; + +/// Width of the accent edge around the focused row (points) +const FOCUS_EDGE_WIDTH: f32 = 1.0; + +/// The list of layers laying something down where R + click landed +#[derive(Clone, Debug, PartialEq)] +pub struct LayerPickList { + /// Where the click landed on screen, and in viewport pixels for `layer.pickAt` + at: Pos2, + point: Vec2, + /// The view the list stays inside + bounds: Rect, + /// The layers there, top first, each with the channels it changes there + rows: Vec<(LayerId, Vec)>, + /// The list's first frame: its top row takes the keyboard focus + opening: bool, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + closing: bool, +} + +/// The cached label for the texel under the pointer: (texture set, texel, document revision, view) and its text +type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String); + +/// R + click at `at` (`point` in viewport pixels) in the view `bounds`: one layer there is selected straight away, several open the list +pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Rect) { + let viewport = app.session.viewport; + match app.session.layers_under(point, viewport) { + Ok((_, rows)) if rows.len() > 1 => app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, opening: true, closing: false }), + _ => { + app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); + } + } +} + +/// Whether the list takes the views' clicks: open, or closing until the press that closed it ends +pub(crate) fn blocks_view_input(app: &TextureCraftApp) -> bool { + app.layer_pick_list.is_some() +} + +/// What the label at the pointer says over viewport pixel `point`: the top layer there and how many more, None off the mesh; recomputed only when the texel, document or view changes +pub(crate) fn hover_label(app: &TextureCraftApp, ui: &Ui, point: Vec2) -> Option { + let session = &app.session; + let (ts, texel) = session.texel_under(point, session.viewport)?; + let key = (ts, texel, session.revision, session.view); + let id = egui::Id::unique("layer_pick_hover_label"); + if let Some((cached, label)) = ui.data(|data| data.get_temp::(id)) + && cached == key + { + return Some(label); + } + + let layers = session.layers_at_texel(ts, texel); + let name = |id: &LayerId| session.doc.project.layers.get(id).map(|layer| layer.name.clone()).unwrap_or_default(); + let label = match layers.as_slice() { + [] => tr("No layer here").to_owned(), + [(top, _)] => name(top), + [(top, _), more @ ..] => trf("{name} +{n} more", &[("name", &name(top)), ("n", &more.len())]), + }; + ui.data_mut(|data| data.insert_temp::(id, (key, label.clone()))); + Some(label) +} + +/// The list's area, whose rect egui remembers between frames +fn area_id() -> egui::Id { + egui::Id::unique("layer_pick_list") +} + +/// Draws the open list; a row click selects its layer, Esc or a press outside closes it +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at, escape) = + ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape))); + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + match &mut app.layer_pick_list { + Some(_) if app.ui.mode != Mode::Painting || escape => app.layer_pick_list = None, + Some(list) if list.closing => { + if !any_down { + app.layer_pick_list = None; + } + } + Some(list) if pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))) => list.closing = true, + _ => {} + } + + let Some(list) = app.layer_pick_list.clone().filter(|list| !list.closing) else { return }; + let tokens = Tokens::get(ctx); + let mut picked = None; + let width = list_width(app, ctx, &list.rows); + + // Right of and below the click; past the view's right edge it opens left of the click, so it never covers the spot + let bounds = list.bounds.shrink(VIEW_MARGIN); + let frame_width = width + 2.0 * f32::from(LIST_MARGIN); + let left = if list.at.x + LIST_OFFSET + frame_width > bounds.right() { list.at.x - LIST_OFFSET - frame_width } else { list.at.x + LIST_OFFSET }; + let at = pos2(left, list.at.y + LIST_OFFSET); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::same(LIST_MARGIN)).show(ui, |ui| { + // A deep stack scrolls inside the view + egui::ScrollArea::vertical().max_height(bounds.height() - 2.0 * f32::from(LIST_MARGIN)).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + // Up and Down move the keyboard focus along the rows (egui's arrow navigation), Enter picks the focused one + for (index, (layer, channels)) in list.rows.iter().enumerate() { + let response = row(app, ui, *layer, channels, width); + if list.opening && index == 0 { + response.request_focus(); + } + if response.clicked() { + picked = Some(*layer); + } + } + }); + }); + }); + + if let Some(list) = &mut app.layer_pick_list { + list.opening = false; + } + if let Some(layer) = picked { + let viewport = app.session.viewport; + app.run("layer.pickAt", json!({"x": list.point.x, "y": list.point.y, "viewport": [viewport.x, viewport.y], "layer": layer.0})); + app.layer_pick_list = None; + } +} + +/// The rows' width: the widest name or channels line beside the thumbnail +fn list_width(app: &TextureCraftApp, ctx: &egui::Context, rows: &[(LayerId, Vec)]) -> f32 { + let text_width = |text: String, font: egui::FontId| ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text, font, Color32::WHITE).size().x); + let widest = rows + .iter() + .map(|(layer, channels)| { + let name = text_width(layer_name(app, *layer), crate::theme::semibold(NAME_FONT_SIZE)); + name.max(text_width(channels_line(channels), egui::FontId::proportional(CHANNELS_FONT_SIZE))) + }) + .fold(0.0, f32::max); + (THUMBNAIL_SIZE + widest + ROW_PADDING * 3.0).max(MIN_LIST_WIDTH) +} + +/// One row: the layer's content thumbnail, its name and the channels it changes at the spot +fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Channel], width: f32) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let name = layer_name(app, layer); + let channels = channels_line(channels); + let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, egui::Id::unique("layer_pick_row").with(layer.0), Sense::click()); + let selected = app.session.selected_layer() == Some(layer); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &name)); + + // The pointed or focused row takes the selected layer's tint; focus adds an accent edge + let painter = ui.painter(); + if response.hovered() || response.has_focus() { + painter.rect_filled(rect, tokens.radius, crate::dock::selected_layer_fill(&tokens)); + } + if response.has_focus() { + painter.rect_stroke(rect, tokens.radius, Stroke::new(FOCUS_EDGE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + } + + let thumbnail = Rect::from_min_size(pos2(rect.left() + ROW_PADDING, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.rect_filled(thumbnail, crate::dock::THUMBNAIL_ROUNDING, tokens.field); + let target = ThumbTarget::Content { layer, channel: app.ui.layer_channel }; + if let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target) { + painter.image(texture, thumbnail, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + + let text_left = thumbnail.right() + ROW_PADDING; + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_BOTTOM, name, crate::theme::semibold(NAME_FONT_SIZE), tokens.text_strong); + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_TOP, channels, egui::FontId::proportional(CHANNELS_FONT_SIZE), tokens.text_dim); + response +} + +fn layer_name(app: &TextureCraftApp, layer: LayerId) -> String { + app.session.doc.project.layers.get(&layer).map(|layer| layer.name.clone()).unwrap_or_default() +} + +/// The channels a layer changes at the spot, by their names +fn channels_line(channels: &[Channel]) -> String { + channels.iter().map(|channel| tr(channel.label())).collect::>().join(", ") +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9bc2866a..a73eb546 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -57,6 +57,7 @@ mod inactive_set_hint; mod instance_properties; pub mod keymap; pub mod layer_panel; +pub mod layer_pick_list; mod layer_toolbar; mod layout_dialog; mod levels_display; @@ -291,6 +292,8 @@ pub struct TextureCraftApp { pub moving_on_model: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + /// The layers under an R + click in the 3D view to pick one from + pub layer_pick_list: Option, properties_scroll: property_sheet::PropertiesScroll, /// The color selection the next click in the 3D or 2D view picks an ID color for pub picking_id_color: Option, @@ -422,6 +425,7 @@ impl TextureCraftApp { last_paint_uv: None, moving_on_model: None, properties_popup: None, + layer_pick_list: None, properties_scroll: property_sheet::PropertiesScroll::default(), picking_id_color: None, picking_symmetry_plane: false, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..3914782c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -27,6 +27,8 @@ use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; pub const STENCIL_KEY: egui::Key = egui::Key::S; /// Hold this key with the Clone tool and click to set the source pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V; +/// Hold this key with any tool and click the mesh to select the layer laying something down there +pub const PICK_LAYER_KEY: egui::Key = egui::Key::R; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -146,6 +148,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } crate::properties_popup::show(app, ui.ctx()); + crate::layer_pick_list::show(app, ui.ctx()); if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); @@ -864,6 +867,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // Layer pick: R + click lists the layers laying something down there (one is selected straight away), whatever the tool + let r_held = layer_pick_key(app, ui); + if r_held + && !alt + && app.layer_pick_list.is_none() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + crate::layer_pick_list::click(app, pointer, local(pointer), rect); + } + // Depth of field focus pick: a click focuses there instead of painting let focus_pick = focus_picking(ui.ctx()); if focus_pick { @@ -881,11 +895,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // A dismissing click cannot paint or place a decal through the rail popup let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); - crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held || r_held); // A press that closes an open colour picker only closes it: it neither paints nor moves a projection let picker = crate::color_picker::blocks_view_press(ui.ctx()); - let popup = app.properties_popup.is_some() || rail_popup || picker; + let popup = app.properties_popup.is_some() || crate::layer_pick_list::blocks_view_input(app) || rail_popup || picker; // A pending ID color pick or eyedropper takes the next click instead of the brush let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); @@ -916,8 +930,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Only a press on a projection handle moves the selected fill - let gizmo_free = - !adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()); + let gizmo_free = !adjusting + && !alt + && !holding + && !s_held + && !v_held + && !r_held + && !focus_pick + && !popup + && !picking + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()); let gizmo = ShownGizmo::of(app, rect); let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at))); let frame_drag = gizmo_free && began_on_handle && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); @@ -934,6 +957,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let plane_pick = !popup && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -945,6 +969,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !popup && !picking @@ -965,6 +990,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -1038,6 +1064,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); + // Over the 3D image: the layer under the pointer while the layer pick key is held + if r_held + && app.layer_pick_list.is_none() + && let Some(hover) = response.hover_pos() + && let Some(label) = crate::layer_pick_list::hover_label(app, ui, local(hover)) + { + layer_pick_hint(ui, rect, hover, &label); + } + // Route shelf drops by asset type to a layer, decal, or brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1045,6 +1080,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let mut symmetry_cursor = None; if tool_acts(app) && !navigating + && !r_held && response.hovered() && brush_tool(app.session.tool.tool) && (app.session.tool.tool != Tool::Path || adjusting) @@ -1689,6 +1725,37 @@ fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input() } +/// R held over a view in painting mode, outside a text field: clicks select the layer under the cursor +fn layer_pick_key(app: &TextureCraftApp, ui: &Ui) -> bool { + app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(PICK_LAYER_KEY)) && !ui.ctx().egui_wants_keyboard_input() +} + +/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held +fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let font = egui::TextStyle::Small.resolve(ui.style()); + let galley = painter.layout_no_wrap(label.to_owned(), font, tokens.text); + let at = hover + vec2(LAYER_PICK_HINT_OFFSET, LAYER_PICK_HINT_OFFSET); + let frame = Rect::from_min_size(at, galley.size()).expand(LAYER_PICK_HINT_PADDING); + painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel); + painter.rect_stroke( + frame, + egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), + Stroke::new(LAYER_PICK_HINT_BORDER_WIDTH, tokens.separator), + egui::StrokeKind::Inside, + ); + painter.galley(at, galley, tokens.text); +} + +/// How far the layer pick label sits right of and below the pointer, and the room around its text (points) +const LAYER_PICK_HINT_OFFSET: f32 = 16.0; +const LAYER_PICK_HINT_PADDING: f32 = 4.0; + +/// Width of the layer pick label's border (points) +const LAYER_PICK_HINT_BORDER_WIDTH: f32 = 1.0; + /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { if let Some(center) = project(app, rect, pos) { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index a0255023..a2dc1368 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -2,7 +2,7 @@ //! fold without touching the document, and the thumbnails arrive from the worker. use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{Channel, LayerId}; @@ -517,3 +517,72 @@ fn dragging_a_row_opacity_adds_one_undo_step() { assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h)); assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step"); } + +/// When the selection moves to a layer below the panel's visible rows (a pick on the mesh, a command), its row scrolls into view +#[test] +fn a_newly_selected_layer_out_of_view_scrolls_into_view() { + let (mut h, _) = harness(); + for index in 0..20 { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": format!("Filler {index}")})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + let bottom = h.state().session.doc.project.texture_sets[h.state().session.ts()].stack[0]; + let name = h.state().session.doc.project.layers[&bottom].name.clone(); + + let before = h.get_by_label(&name).rect(); + assert!(before.top() > properties_top(&h), "the bottom layer starts out of view"); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": bottom.0})).unwrap(); + h.run_steps(SETTLE_FRAMES); + + let after = h.get_by_label(&name).rect(); + assert!(after.bottom() <= properties_top(&h), "its row is inside the panel"); +} + +/// The top of the Properties tab, which sits under the Layers panel +fn properties_top(h: &Harness<'_, TextureCraftApp>) -> f32 { + h.query_all(by().role(egui::Role::Tab).label_contains("Properties")).next().map(|tab| tab.rect().top()).unwrap_or(f32::MAX) +} + +/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer +#[test] +fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() { + let (mut h, _) = harness(); + let session = &mut h.state_mut().session; + let lower = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Lower fill", "color": "#aa3322"})).unwrap(), "layer")); + let upper = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Upper fill", "color": "#2233aa"})).unwrap(), "layer")); + let empty = LayerId(id(execute(session, "layer.add.paint", &json!({"name": "Empty on top"})).unwrap(), "layer")); + h.run_steps(SETTLE_FRAMES); + let steps = h.state().session.history_labels().len(); + let view = h.state().viewport_rect; + let in_list = |h: &Harness<'_, TextureCraftApp>, name: &str| h.get_all_by_label(name).map(|node| node.rect()).find(|rect| view.contains(rect.center())); + let open_list = |h: &mut Harness<'_, TextureCraftApp>| { + let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + h.event(key(true)); + h.hover_at(view.center()); + h.run_steps(1); + click(h, view.center()); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + }; + + open_list(&mut h); + + assert!(in_list(&h, "Upper fill").is_some() && in_list(&h, "Lower fill").is_some(), "both fills under the click are listed over the view"); + assert!(in_list(&h, "Empty on top").is_none(), "the empty top layer lays nothing down there"); + assert_eq!(h.state().session.selected_layer(), Some(empty), "opening the list selects nothing yet"); + + h.key_press(egui::Key::ArrowDown); + h.key_press(egui::Key::Enter); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(lower), "Down from the top row and Enter select the second layer"); + assert!(h.state().layer_pick_list.is_none(), "picking closes the list"); + + open_list(&mut h); + let row = in_list(&h, "Upper fill").unwrap().center(); + click(&mut h, row); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(upper), "the clicked row's layer is selected"); + assert_eq!(h.state().session.history_labels().len(), steps, "no stroke was painted"); +} diff --git a/docs/features.md b/docs/features.md index 42ea07a6..d4ed5f7b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -45,6 +45,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA one layer alone in the 3D and 2D views, optionally without its mask (Alt+Shift+click, or **Solo layer without its mask**), to judge a material hidden behind a mask. It is only a view: the document, the undo history, saving, exporting and baking never see it. +- **Pick a layer on the model:** hold R over the 3D view, with any tool: a label at the pointer + names the top layer laying something down there (the shown channel in a single-channel view) + and how many more. Click: one layer there is selected; several open a list at the pointer with + each one's thumbnail, name and the channels it changes there, to pick from (Up/Down, Enter, Esc + work too). Closed folders holding the picked layer open and its row scrolls into view. - **Several layers at once:** Shift+click a layer to select the rows from the last clicked one, Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer over the Layers panel to select every shown row (folder rows and the layers of open folders).