From b01dbe34c67c71697bd873d9c3c3b4b5037d1f78 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:59:40 +0000 Subject: [PATCH 01/29] Layers: add the height-combination mask to the layer row menu --- crates/ui-egui/src/dock.rs | 3 ++- crates/ui-egui/tests/it/layers_panel.rs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e7efb8b9..a66dbdec 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1342,7 +1342,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); - // The row menu can act on several selected layers. A thumbnail identifies one layer. + // The row menu can act on several selected layers; a thumbnail names one let several = if content_thumbnail { None } else { selection_with(app, layer.id) }; let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { let mut button = egui::Button::new(label); @@ -1365,6 +1365,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true); + run(app, ui, tr("Add mask with height combination"), "mask.add.heightCombination", json!({"layer": layer_id}), true); if !content_thumbnail { ui.separator(); mask_management_menu(app, ui, layer, false); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 72b5ad4b..7b70cc7a 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -378,6 +378,19 @@ fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui:: h.run_steps(2); } +#[test] +fn the_row_menu_adds_a_height_combination_to_the_clicked_layers_mask() { + let (mut h, layer) = harness(); + let row = h.get_by_label("Masked fill").rect(); + right_click(&mut h, row.center()); + h.get_by_label("Add mask with height combination").click(); + h.run_steps(3); + + let mask = h.state().session.doc.project.layers[&layer].mask.clone().unwrap(); + assert_eq!(mask.effects.len(), 2, "the compare lands in the existing mask"); + assert!(mask.effects.iter().any(|effect| matches!(effect.kind, texturecraft_engine::core::EffectKind::Compare { .. }))); +} + #[test] fn the_context_menu_solos_a_layer_without_touching_the_document() { let (mut h, layer) = harness(); From 8361234c49ea8b73793657ba51a8d83b5c3a9a53 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:00:50 +0000 Subject: [PATCH 02/29] Layers: move an effect up, down, to the top or bottom from its row menu --- crates/ui-egui/src/dock.rs | 17 ++++++++++++ crates/ui-egui/tests/it/effect_rows.rs | 37 +++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a66dbdec..8c0bdcd4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1135,6 +1135,23 @@ fn effect_row( } } + // Rows list the stack top first and index 0 is its bottom, so up is one index higher + ui.separator(); + if let Some(index) = position(effect_id.0) { + let top = stack.len() - 1; + for (label, to, enabled) in [ + (tr("Move up"), index + 1, index < top), + (tr("Move down"), index.saturating_sub(1), index > 0), + (tr("Move to top"), top, index < top), + (tr("Move to bottom"), 0, index > 0), + ] { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + app.run("effect.move", json!({"effect": effect_id.0, "index": to})); + ui.close(); + } + } + } + // Blending options can apply across channels or effects ui.separator(); let blends = effect.kind.blends(); diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 54157bba..839f252c 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options +//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -59,6 +59,41 @@ fn dragging_an_effect_row_reorders_its_stack() { assert_eq!(order(&harness), [a, c, b]); } +/// An effect row's menu moves it one step or to an end of its stack; a move past an end is greyed +#[test] +fn an_effect_rows_menu_moves_it_within_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| { + harness.get_by_label(row).click_secondary(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); + }; + + menu_item(&mut harness, "Effect A", "Move up"); + assert_eq!(order(&harness), [b, a, c]); + menu_item(&mut harness, "Effect A", "Move to top"); + assert_eq!(order(&harness), [b, c, a]); + menu_item(&mut harness, "Effect C", "Move down"); + assert_eq!(order(&harness), [c, b, a]); + menu_item(&mut harness, "Effect A", "Move to bottom"); + assert_eq!(order(&harness), [a, c, b]); + + harness.get_by_label("Effect A").click_secondary(); + harness.run_steps(3); + assert!(harness.get_by_label("Move down").accesskit_node().is_disabled(), "the bottom effect can't go lower"); + assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); +} + /// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { From a3713d4631e0220dfb803d04d0ac745762b145f7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:03:25 +0000 Subject: [PATCH 03/29] Layers: name generator effects after their kind and remove an effect from its row's cross --- crates/core/src/layer.rs | 8 +++- crates/engine/src/mask_cmds.rs | 8 ++++ crates/engine/tests/it/generator_names.rs | 56 +++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 22 +++++++-- crates/ui-egui/tests/it/effect_rows.rs | 30 ++++++++++-- 6 files changed, 117 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/it/generator_names.rs diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..8bb4a9dc 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -2096,10 +2096,16 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { + // Generators are named after their kind, as filters are + let name = match &kind { + EffectKind::Generator(generator) => generator.kind.label(), + _ => kind.name(), + }; + // Generators and fills that build a mask usually add on top of the background Effect { id, - name: kind.name().to_string(), + name: name.to_string(), visible: true, kind, blend: BlendMode::Normal, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 385447a0..e234f654 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -713,6 +713,9 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The name every generator effect got before they were named after their kind +const FORMER_GENERATOR_NAME: &str = "Generator"; + /// Edit visibility, blending, name, effect parameters, or a filter's type fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; @@ -818,6 +821,11 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(kind) = generator_kind && kind != generator.kind { + // A name taken from the kind follows the new kind + let named_by_kind = edited.name == generator.kind.label() || edited.name == FORMER_GENERATOR_NAME; + if named_by_kind && name_param(params).is_none() { + edited.name = kind.label().to_string(); + } generator.kind = kind; generator.detail = Generator::new(kind).detail; generator.inputs.retain(|map, _| kind.inputs().contains(map)); diff --git a/crates/engine/tests/it/generator_names.rs b/crates/engine/tests/it/generator_names.rs new file mode 100644 index 00000000..f499114b --- /dev/null +++ b/crates/engine/tests/it/generator_names.rs @@ -0,0 +1,56 @@ +//! Generator effects are named after their kind, and a name taken from the kind follows a kind change + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, execute}; + +/// A sample session with a new generator of `kind` on its top layer's mask +fn generator(kind: &str) -> (Session, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let added = execute(&mut session, "effect.add.generator", &json!({"generator": kind})).unwrap(); + + (session, LayerId(added["effect"].as_u64().unwrap())) +} + +fn name(session: &Session, effect: LayerId) -> String { + session.doc.project.effect(effect).unwrap().1.name.clone() +} + +fn set(session: &mut Session, effect: LayerId, params: Value) { + let mut params = params; + params["effect"] = json!(effect.0); + execute(session, "effect.set", ¶ms).unwrap(); +} + +#[test] +fn a_new_generator_takes_its_kinds_name_and_keeps_following_it() { + let (mut session, effect) = generator("dirt"); + assert_eq!(name(&session, effect), "Dirt"); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} + +#[test] +fn a_chosen_name_survives_a_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Grime"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + assert_eq!(name(&session, effect), "Grime"); + + set(&mut session, effect, json!({"generator": "dirt", "name": "Dust"})); + assert_eq!(name(&session, effect), "Dust", "a name given with the change wins"); +} + +#[test] +fn an_older_projects_generic_generator_name_follows_its_next_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Generator"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..2047f670 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_names; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 8c0bdcd4..0eda8d6b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -333,6 +333,8 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; /// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. const EFFECT_BLEND_WIDTH: f32 = 82.0; const EFFECT_OPACITY_WIDTH: f32 = 36.0; +/// Width of the column at an effect row's right end holding its remove cross +const EFFECT_REMOVE_WIDTH: f32 = 17.0; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; @@ -977,7 +979,7 @@ fn blend_controls( (picked, field.changed().then_some((percent / 100.0, merge))) } -/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level` #[allow(clippy::too_many_arguments)] fn effect_row( app: &mut TextureCraftApp, @@ -1037,11 +1039,20 @@ fn effect_row( painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + // The cross at the right end removes the effect: it ends where a layer row's controls end, and takes clicks left of the panel's floating scroll bar + let remove = + Rect::from_min_max(pos2(rect.right() - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH, rect.top()), pos2(rect.right() - ROW_CONTROL_GAP, rect.bottom())); + let remove_hit = Rect::from_min_max(remove.min, pos2(remove.right().min(rect.right() - ui.spacing().scroll.bar_width), remove.bottom())); + let remove_response = ui.interact(remove_hit, ui.scope_id().with(("eff_remove", effect_id.0)), Sense::click()).on_hover_text(tr("Remove effect")); + remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, trf("Remove effect {name}", &[("name", &effect.name)]))); + let remove_color = if remove_response.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(remove.center(), egui::Align2::CENTER_CENTER, ic::X, egui::FontId::proportional(EYE_FONT_SIZE), remove_color); + + // The name, then the blend mode and opacity side by side left of the cross when the name keeps room to be read let name_left = thumbnail.right() + THUMBNAIL_GAP; - let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let controls_left = remove.left() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; - let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { remove.left() - ROW_RIGHT_PADDING }; let name_color = if visible { tokens.text } else { tokens.text_dim }; let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == effect_id.0); if renaming { @@ -1076,6 +1087,9 @@ fn effect_row( if eye_response.clicked() { app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if remove_response.clicked() { + app.run("effect.remove", json!({"effect": effect_id.0})); + return; } else if row.double_clicked() && !renaming { app.ui.rename = Some((effect_id.0, effect.name.clone())); } else if row.clicked() { diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 839f252c..d17882ba 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options +//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its cross removes it, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -94,6 +94,30 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); } +/// The cross at an effect row's right end removes that effect alone, in one undo step +#[test] +fn an_effect_rows_cross_removes_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let a = add("Effect A"); + add("Effect B"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let undo_steps = harness.state().session.history_labels().len(); + + let at = harness.get_by_label("Remove effect Effect B").rect().center(); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + + let remaining = harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(remaining, [a]); + assert_eq!(harness.state().session.history_labels().len(), undo_steps + 1); +} + /// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { @@ -110,9 +134,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.state_mut().ui.layer_material_view = false; harness.run_steps(2); - // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + // Left of the remove cross: a 4-point gap, then the 82-point pair of mode menu and opacity field let row = harness.get_by_label("Effect A").rect(); - let pair_right = row.right() - 4.0; + let pair_right = harness.get_by_label("Remove effect Effect A").rect().left() - 4.0; let pair_left = pair_right - 82.0; let mode_at = egui::pos2(pair_left + 20.0, row.center().y); harness.drag_at(mode_at); From 2f1927397b48cadb62b5abf325633fba9696a5b5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:51:49 +0000 Subject: [PATCH 04/29] Layers: add a smart material from the toolbar's picker The toolbar's smart material button (a caret like Add effect and Add mask) opens the resource picker filtered to smart materials, the user's saved ones after the built-in ones; a pick adds it above the selection. To keep one row in a 1280 pt window the menu buttons narrow to 30 pt, the plain buttons to 23 pt, and the channel list gives up width down to 70 pt ("Material" still whole) before the row wraps. --- crates/ui-egui/src/layer_toolbar.rs | 98 ++++++++++++++++--- .../layer_toolbar/smart_material_choice.rs | 10 ++ crates/ui-egui/src/shelf.rs | 4 +- crates/ui-egui/tests/it/layer_toolbar.rs | 37 ++++++- crates/ui-egui/tests/it/layers_panel.rs | 2 +- 5 files changed, 131 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/layer_toolbar/smart_material_choice.rs diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 83e028db..ec6b1eb5 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -1,10 +1,13 @@ -//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons and remove +//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons, the smart material picker and remove + +use std::path::PathBuf; use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::Session; use texturecraft_engine::core::{Layer, LayerId}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use crate::TextureCraftApp; @@ -21,12 +24,14 @@ mod bitmap_choice; mod item_icon; mod menu_icon; mod pick; +mod smart_material_choice; use add_item::AddItem; use bitmap_choice::BitmapChoice; use item_icon::ItemIcon; use menu_icon::MenuIcon; use pick::Pick; +use smart_material_choice::SmartMaterialChoice; /// The row's height and its controls' height const BAR_HEIGHT: f32 = 40.0; @@ -37,14 +42,16 @@ const CONTROL_ROUNDING: u8 = 5; const SIDE_PADDING: f32 = 8.0; const CHANNEL_WIDTH: f32 = 88.0; +/// The channel list's width when the row gets tight: "Material" and its caret still fit, and the row fits a 1280 pt wide window's Layers panel +const CHANNEL_MIN_WIDTH: f32 = 70.0; /// A menu button: its icon, then its caret -const MENU_BUTTON_WIDTH: f32 = 32.0; +const MENU_BUTTON_WIDTH: f32 = 30.0; const MENU_ICON_X: f32 = 11.0; const MENU_CARET_INSET: f32 = 8.0; const MENU_ICON_SIZE: f32 = 14.0; const MASK_ICON_SIZE: f32 = 12.0; const CARET_SIZE: f32 = 11.0; -const BUTTON_WIDTH: f32 = 24.0; +const BUTTON_WIDTH: f32 = 23.0; const ICON_SIZE: f32 = 14.0; /// Air after the channel list, between the two menu buttons, before the add-layer buttons and between them const CHANNEL_GAP: f32 = 6.0; @@ -52,16 +59,16 @@ const MENU_GAP: f32 = 3.0; const GROUP_GAP: f32 = 8.0; const BUTTON_GAP: f32 = 2.0; const CHANNEL_TEXT_X: f32 = 8.0; -const CHANNEL_CARET_INSET: f32 = 10.0; +const CHANNEL_CARET_INSET: f32 = 9.0; const CHANNEL_CARET_SIZE: f32 = 12.0; const TEXT_SIZE: f32 = 12.0; /// The row's width besides the channel list's: its padding, the two menu buttons and their gaps const MENUS_ROW_WIDTH: f32 = 2.0 * SIDE_PADDING + CHANNEL_GAP + 2.0 * MENU_BUTTON_WIDTH + MENU_GAP; -/// The three add-layer buttons and Remove -const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; -/// The width every control takes in one row -const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; +/// The three add-layer buttons, the smart material button and Remove +const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + MENU_BUTTON_WIDTH + 4.0 * BUTTON_GAP; +/// The smallest width that holds every control in one row, the channel list at its narrowest +const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_MIN_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; /// A hanging menu: its caption, rows, icon and text columns and its smallest width const MENU_PADDING: f32 = 4.0; @@ -105,8 +112,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let mut x = bar.left() + SIDE_PADDING; let control = |x: f32, top: f32, width: f32| Rect::from_min_size(pos2(x, top), vec2(width, CONTROL_HEIGHT)); - // Narrower still, the channel list gives up width before a menu button leaves the panel - let channel_width = CHANNEL_WIDTH.min(width - MENUS_ROW_WIDTH).max(0.0); + // A tight row takes width from the channel list first; narrower still, it gives up width before a menu button leaves the panel + let channel_room = if two_rows { width - MENUS_ROW_WIDTH } else { width - MENUS_ROW_WIDTH - GROUP_GAP - LAYER_BUTTONS_WIDTH }; + let channel_width = CHANNEL_WIDTH.min(channel_room).max(0.0); channel_list(app, ui, control(x, top, channel_width), &tokens); x += channel_width + CHANNEL_GAP; @@ -119,16 +127,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { x += MENU_BUTTON_WIDTH + GROUP_GAP; let (top, mut x) = if two_rows { (top + BAR_HEIGHT, bar.left() + SIDE_PADDING) } else { (top, x) }; - for (glyph, label, command) in [ - (ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), - (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill"), - (ic::FOLDER_SIMPLE, tr("Add folder"), "layer.add.group"), - ] { + for (glyph, label, command) in [(ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill")] { if plain_button(ui, control(x, top, BUTTON_WIDTH), glyph, label, &tokens).clicked() { app.run(command, Value::Null); } x += BUTTON_WIDTH + BUTTON_GAP; } + let smart_materials = ui.scope_id().with("smart_material_picker"); + picker_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add smart material"), MenuIcon::Glyph(ic::STACK), smart_materials, &tokens); + x += MENU_BUTTON_WIDTH + BUTTON_GAP; + if plain_button(ui, control(x, top, BUTTON_WIDTH), ic::FOLDER_SIMPLE, tr("Add folder"), &tokens).clicked() { + app.run("layer.add.group", Value::Null); + } + x += BUTTON_WIDTH + BUTTON_GAP; let remove = control((bar.right() - SIDE_PADDING - BUTTON_WIDTH).max(x), top, BUTTON_WIDTH); if plain_button(ui, remove, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), &tokens).clicked() { app.run("layer.remove", Value::Null); @@ -144,6 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(layer) = selected { bitmap_picker(app, &anchor, popup(layer), layer); } + smart_material_picker(app, &anchor, smart_materials); } /// Layer `id` of the project, when there is one @@ -256,6 +268,19 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s picked } +/// A button drawn like a menu button whose click opens or closes resource picker `popup`; it keeps its button face while the picker is open +fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id, tokens: &Tokens) { + let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + if response.clicked() { + resource_picker::toggle(ui.ctx(), popup); + } + if response.hovered() || egui::Popup::is_id_open(ui.ctx(), popup) { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); + } + button_face(ui.painter(), rect, icon, tokens); +} + /// A menu button's icon and caret fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { let icon_at = pos2(rect.left() + MENU_ICON_X, rect.center().y); @@ -461,3 +486,46 @@ fn bitmap_tabs(session: &Session) -> Vec> { let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }]; vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }] } + +/// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does +fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) { + let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default()); + match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { + Some(SmartMaterialChoice::BuiltIn(id)) => { + app.run("material.apply", json!({"material": id})); + } + Some(SmartMaterialChoice::Saved(path)) => { + app.run("material.load", json!({"path": path.display().to_string()})); + } + None => {} + } +} + +/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved (once the shelf has read them) +fn smart_material_tabs(library: &[PathBuf]) -> Vec> { + let built_in = MATERIALS + .iter() + .filter(|material| material.smart) + .map(|material| ResourcePickerItem { + id: SmartMaterialChoice::BuiltIn(material.id), + label: tr(material.label).to_owned(), + caption: Some(tr(material.category)), + picture: TilePicture::Material(material.id), + }) + .collect(); + let saved: Vec<_> = library + .iter() + .filter(|path| !crate::shelf::is_saved_mask(path)) + .map(|path| ResourcePickerItem { + id: SmartMaterialChoice::Saved(path.clone()), + label: crate::shelf::saved_material_name(path).to_owned(), + caption: None, + picture: TilePicture::Glyph(ic::SPHERE), + }) + .collect(); + let mut groups = vec![PickerGroup { header: Some(tr("Smart materials")), items: built_in }]; + if !saved.is_empty() { + groups.push(PickerGroup { header: Some(tr("Your assets")), items: saved }); + } + vec![PickerTab { icon: ic::STACK, name: tr("Smart materials"), groups }] +} diff --git a/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs new file mode 100644 index 00000000..39e7bf9c --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs @@ -0,0 +1,10 @@ +//! A pick of the Layers toolbar's smart material picker + +use std::path::PathBuf; + +/// A built-in smart material by id, or one the user saved, by file +#[derive(Clone, PartialEq)] +pub(super) enum SmartMaterialChoice { + BuiltIn(&'static str), + Saved(PathBuf), +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..e207b063 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -360,7 +360,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: } /// Whether a library file is a saved smart mask (not a smart material) -fn is_saved_mask(path: &std::path::Path) -> bool { +pub(crate) fn is_saved_mask(path: &std::path::Path) -> bool { path.extension().is_some_and(|extension| extension == texturecraft_engine::smart_masks::SMART_MASK_EXT) } @@ -444,7 +444,7 @@ fn scan_library(app: &mut TextureCraftApp) { fn scan_library(_: &mut TextureCraftApp) {} /// A saved smart material's name: its file name without the extension -fn saved_material_name(path: &std::path::Path) -> &str { +pub(crate) fn saved_material_name(path: &std::path::Path) -> &str { path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) } diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index 9466a76f..2e8bbb5a 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -1,11 +1,12 @@ //! The Layers panel's top row: Add effect greys what can't go where the selection is, Add mask adds a mask with its effect, and -//! Bitmap adds nothing until a texture is picked +//! Bitmap adds nothing until a texture is picked; Add smart material adds the smart material picked use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; @@ -127,6 +128,38 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer() assert!(mask_kinds(&harness, opener).is_empty(), "nor the layer that opened it"); } +/// The selected texture set's top-level layers, bottom to top +fn stack(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let session = &harness.state().session; + session.doc.project.texture_set(session.ts()).unwrap().stack.clone() +} + +/// Add smart material opens a picker of the smart materials only; a pick adds its folder right above the selected layer +#[test] +fn add_smart_material_adds_the_picked_smart_material_above_the_selection() { + let (mut harness, layer) = app(); + let smart = MATERIALS.iter().find(|material| material.smart).unwrap(); + let simple = MATERIALS.iter().find(|material| !material.smart).unwrap(); + let tiles_of = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).map(|node| node.rect()).collect::>(); + let (smart_before, simple_before) = (tiles_of(&harness, smart.label), tiles_of(&harness, simple.label)); + + click_widget(&mut harness, Role::Button, "Add smart material"); + let new_tile = tiles_of(&harness, smart.label).into_iter().find(|tile| !smart_before.contains(tile)); + + assert!(egui::Popup::is_any_open(&harness.ctx), "the button opens the picker"); + assert_eq!(tiles_of(&harness, simple.label).len(), simple_before.len(), "simple materials stay out of it"); + + let before = stack(&harness); + click_at(&mut harness, new_tile.expect("a tile for the smart material").center()); + let after = stack(&harness); + let added: Vec<_> = after.iter().filter(|id| !before.contains(id)).copied().collect(); + + assert_eq!(added.len(), 1, "one folder added: {added:?}"); + let place = |id: LayerId| after.iter().position(|shown| *shown == id).unwrap(); + assert_eq!(place(added[0]), place(layer) + 1, "right above the selection"); + assert!(!egui::Popup::is_any_open(&harness.ctx), "the pick closes the picker"); +} + /// A floating Layers panel this narrow cannot hold the toolbar on one row const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0]; @@ -143,7 +176,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { harness.run_steps(SETTLE_FRAMES); let [left, _, width, _] = NARROW_LAYERS; - for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] { + for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add smart material", "Add folder", "Remove layer"] { let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel"); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7b70cc7a..a0255023 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -266,7 +266,7 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> { #[test] fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { let h = narrow_harness(); - let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); + let buttons = ["Add paint layer", "Add fill layer", "Add smart material", "Add folder"].map(|label| h.get_by_label(label).rect()); let wand = h.get_by_label("Add effect").rect(); let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); From e3b589b070fadfc308f72ddb440954473e4632a5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:07:34 +0000 Subject: [PATCH 05/29] Layers: flatten a folder into a fill layer above it --- crates/compose/src/eval.rs | 124 +++++++++++++++++++- crates/compose/src/lib.rs | 2 +- crates/core/src/layer/sampling.rs | 5 +- crates/engine/src/fill_reset_cmds.rs | 4 +- crates/engine/src/layer_ops.rs | 138 +++++++++++++++++++---- crates/engine/tests/it/flatten_folder.rs | 99 ++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/formats/src/image_res.rs | 11 ++ crates/formats/src/lib.rs | 2 +- crates/ui-egui/src/dock.rs | 3 +- 10 files changed, 363 insertions(+), 26 deletions(-) create mode 100644 crates/engine/tests/it/flatten_folder.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..f96dd739 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3116,7 +3116,30 @@ impl<'a, 'b> Texel<'a, 'b> { None => ch.default_value(), }; let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, fill.sampling, depth) }; - (value, cover) + match source { + Some(Source::Image { name, .. }) if fill.sampling.alpha_coverage && cover > 0.0 => { + (value, cover * self.image_alpha(name, projection, fill.sampling)) + } + _ => (value, cover), + } + } + + /// Image resource `name`'s alpha at this texel through `projection` (0 for a missing image) + fn image_alpha(&mut self, name: &str, projection: &Projection, sampling: Sampling) -> f32 { + let Some(image) = self.inp.images.get(name) else { return 0.0 }; + + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + samples + .into_iter() + .zip(footprints) + .map(|((uv, weight), footprint)| image.sample_alpha(uv.x, uv.y, sampling, footprint) * weight) + .sum::() + .clamp(0.0, 1.0) } /// How much a fill projected by `proj` covers this texel: [`Texel::shape_cover`], then depth culling through the projector's `depth` map @@ -4961,6 +4984,105 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti Some(out.into_iter().flatten().collect()) } +/// One tile of a flattened folder's mask: (tile, mask value + coverage data) +pub type FlatMaskTile = ((u32, u32), Vec); + +/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither); None for a layer that is not a folder +pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<(Vec, Vec)> { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if !inputs.project.content_layer(id)?.is_group() { + return None; + } + + let channels: Vec = set.channel_list(); + + // Plan the folder forced visible so hidden folders flatten too + let mut forced_visible = inputs.project.clone(); + if let Some(layer) = forced_visible.layers.get_mut(&id) { + layer.visible = true; + } + let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let projectors = ProjectorDepthCache::default(); + let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); + let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); + + let out: Vec<(Vec, Option)> = tiles + .par_iter() + .map(|&(tx, ty)| { + let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); + let Some(node) = nodes.first() else { return (Vec::new(), None) }; + let Content::Group(children) = &node.content else { return (Vec::new(), None) }; + let below = below_plan(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields), node.lights); + + // One value + coverage buffer per channel the folder plans; signed channels start at their middle + let mut buffers: Vec<(Channel, Vec, bool)> = node + .chans + .iter() + .filter_map(|planned| Channel::ALL.get(planned.ch).map(|channel| (*channel, vec![0u16; TILE_AREA * (planned.comps + 1)], false))) + .collect(); + for (channel, buffer, _) in &mut buffers { + if channel.kind() == ChannelKind::Signed { + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); + } + } + } + + let masked = node.mask.is_some() || node.parts.is_some(); + let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]); + + for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { + // The texel with the stack below the folder run, so masks and fills that read it or its anchors find them + let texel_over_below = || { + let mut texel = Texel::new(&visible_inputs, x, y, offset, 0.0); + if !below.is_empty() { + texel.anchors_below(&below, (id, 0)); + } + texel + }; + + // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide + let over = |background: f32| { + let mut texel = texel_over_below(); + let mut stack: Acc = [[background; 3]; NCH]; + texel.eval(children, &mut stack); + stack + }; + let (low, high) = (over(0.0), over(1.0)); + for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) { + let (Some(premultiplied), Some(shown)) = (low.get(planned.ch), high.get(planned.ch)) else { continue }; + let comps = planned.comps.min(3); + let hidden = premultiplied.iter().zip(shown).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; + let coverage = hidden.clamp(0.0, 1.0); + if coverage <= 0.0 { + continue; + } + + *laid_down = true; + let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; + for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) { + *slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) }; + } + if let Some(slot) = pixel.get_mut(planned.comps) { + *slot = to_u16(coverage); + } + } + + if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { + pixel.copy_from_slice(&[to_u16(texel_over_below().node_mask(node)), u16::MAX]); + } + } + + let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect(); + (content, mask.map(|mask| ((tx, ty), mask))) + }) + .collect(); + + let (content, masks): (Vec<_>, Vec<_>) = out.into_iter().unzip(); + Some((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2f5c0477..f931da06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -55,7 +55,7 @@ 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_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, + 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, }; pub use mask_gray::MaskGray; diff --git a/crates/core/src/layer/sampling.rs b/crates/core/src/layer/sampling.rs index 9fa568fb..4a1c4b6d 100644 --- a/crates/core/src/layer/sampling.rs +++ b/crates/core/src/layer/sampling.rs @@ -14,12 +14,15 @@ pub struct Sampling { pub scale: ScaleMode, #[serde(default, skip_serializing_if = "FillSymmetry::is_default")] pub symmetry: FillSymmetry, + /// Each channel's image alpha is how much of that channel shows (the images a folder is flattened into) + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub alpha_coverage: bool, } impl Sampling { /// What fills saved before the sampling choices existed did: plain bilinear pub const SAVED_BEFORE: Sampling = - Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF }; + Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF, alpha_coverage: false }; /// Serde default for fills saved before the field existed pub fn saved_before() -> Sampling { diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index b2e10670..0e12f002 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -19,9 +19,9 @@ pub fn specs() -> Vec { )] } -/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) +/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) and its alpha coverage (a flattened folder's shape) pub fn reset_sampling(current: Sampling) -> Sampling { - Sampling { symmetry: current.symmetry, ..Sampling::default() } + Sampling { symmetry: current.symmetry, alpha_coverage: current.alpha_coverage, ..Sampling::default() } } /// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 95631f70..1c0bc970 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -2,8 +2,9 @@ //! pixels when a texture set changes size. use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind}; -use texturecraft_texel::TileImage; +use texturecraft_compose::eval::FlatTile; +use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; use crate::commands::{CommandSpec, boolp, has_layer, layer_param}; use crate::session::{Document, StackTarget}; @@ -19,7 +20,7 @@ pub fn specs() -> Vec { "Flatten layer", ["Layers"], Some("Ctrl+M"), - "{layer?} — a fill or masked paint layer becomes a plain paint layer", + "{layer?} — a fill or masked paint layer becomes a plain paint layer; a folder becomes a new fill layer above it holding one image per channel (its mask baked into a painted mask) and is hidden", has_layer, flatten ), @@ -197,38 +198,137 @@ fn flatten(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.flatten", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; let layer = s.doc.project.layer(id)?.clone(); - // An instance flattens what it draws into a plain layer of its own. + + // An instance flattens what it draws into a plain layer of its own let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?; if content.is_group() { - return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into())); + return flatten_folder(s, ts, &layer); } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; s.edit("Flatten layer", |s| { - for c in Channel::ALL { - s.doc.pixels.layers.remove(&(id, c)); + for channel in Channel::ALL { + s.doc.pixels.layers.remove(&(id, channel)); } - let effects: Vec = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect(); - s.doc.pixels.masks.retain(|e, _| !effects.contains(e)); - s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e)); - for (c, (tx, ty), data) in flat { - let img = s.doc.pixels.layer_mut(id, c, size); - img.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + let effects: Vec = + layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()).map(|effect| effect.id).collect(); + s.doc.pixels.masks.retain(|effect, _| !effects.contains(effect)); + s.doc.pixels.layers.retain(|(effect, _), _| !effects.contains(effect)); + + for (channel, (tx, ty), data) in flat { + let image = s.doc.pixels.layer_mut(id, channel, size); + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); } + let channels = s.doc.project.texture_set(ts)?.channel_list(); - let l = s.doc.project.layer_mut(id)?; - l.kind = LayerKind::Paint; - l.mask = None; - l.content_effects.clear(); - l.height_mask = Default::default(); - l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect(); + let flattened = s.doc.project.layer_mut(id)?; + flattened.kind = LayerKind::Paint; + flattened.mask = None; + flattened.content_effects.clear(); + flattened.height_mask = Default::default(); + flattened.channels = content.channels.into_iter().filter(|(channel, _)| channels.contains(channel)).collect(); s.target = StackTarget::Content; Ok(()) })?; Ok(json!({ "layer": id.0 })) } +/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept +fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { + s.update(); + let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; + let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); + let (content, mask) = s + .with_inputs(ts, |inputs| texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)) + .ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; + let images = channel_images(content, size)?; + if images.is_empty() { + return Err(EngineError::Other("the folder shows nothing to flatten".into())); + } + + let flat = s.edit("Flatten folder", |s| { + let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() }; + for (channel, png) in images { + let file_name = format!("{} flattened {}.png", folder.name, channel.id()); + let name = s.add_image_resource(&file_name, png, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + fill.sources.insert(channel, Source::image(name)); + } + + // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default + let channels: Vec = fill.sources.keys().copied().collect(); + let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); + for (channel, blend) in &mut layer.channels { + blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); + } + if !mask.is_empty() { + let paint = s.doc.project.alloc_id(); + let mut baked = Mask::new(MaskBackground::Black); + baked.effects.push(Effect::new(paint, EffectKind::Paint)); + layer.mask = Some(baked); + let image = s.doc.pixels.mask_mut(paint, size); + for ((tx, ty), data) in mask { + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + } + } + + let flat = s.doc.project.insert_layer(ts, layer, Some(folder.id), false)?; + s.doc.project.layer_mut(folder.id)?.visible = false; + s.select_one(ts, flat); + s.target = StackTarget::Content; + Ok(flat) + })?; + Ok(json!({ "layer": flat.0 })) +} + +/// Flattened tiles as one 16-bit RGBA PNG per channel (straight values as a fill reads them, coverage in the alpha), in channel order +fn channel_images(tiles: Vec, size: (u32, u32)) -> Result)>> { + let (width, height) = size; + let mut by_channel: std::collections::BTreeMap)>> = Default::default(); + for (channel, tile, data) in tiles { + by_channel.entry(channel).or_default().push((tile, data)); + } + + by_channel + .into_iter() + .map(|(channel, tiles)| { + let comps = channel.components(); + let mut rgba = vec![0u16; width as usize * height as usize * 4]; + for ((tx, ty), data) in tiles { + for (offset, texel) in data.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + offset as u32 % TILE, ty * TILE + offset as u32 / TILE); + let coverage = texel.get(comps).copied().map_or(0.0, from_u16); + if x >= width || y >= height || coverage <= 0.0 { + continue; + } + + let straight = |i: usize| { + let premultiplied = texel.get(i).copied().unwrap_or(0); + let value = if channel.kind() == ChannelKind::Signed { from_u16_signed(premultiplied) } else { from_u16(premultiplied) }; + value / coverage + }; + let rgb = match channel.kind() { + ChannelKind::Color => [0, 1, 2].map(|i| linear_to_srgb(straight(i))), + ChannelKind::NormalMap => [0, 1, 2].map(straight), + ChannelKind::Scalar => [straight(0); 3], + + // A fill reads a signed channel's image gray as -1..1 + ChannelKind::Signed => [(straight(0) + 1.0) * 0.5; 3], + }; + let start = (y as usize * width as usize + x as usize) * 4; + if let Some(pixel) = rgba.get_mut(start..start + 4) { + pixel.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), to_u16(coverage)]); + } + } + } + let png = + texturecraft_formats::rgba16_png(width, height, &rgba).map_err(|error| EngineError::Other(format!("flattened {}: {error}", channel.id())))?; + Ok((channel, png)) + }) + .collect() +} + impl Session { /// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per /// channel over the set's covered tiles. None for folders or a set not ready. diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs new file mode 100644 index 00000000..741f7e80 --- /dev/null +++ b/crates/engine/tests/it/flatten_folder.rs @@ -0,0 +1,99 @@ +//! Flattening a folder: a new fill layer above it reads one image per channel and its mask is baked, so the stack looks the same with the folder hidden + +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// The test project's texture size +const RESOLUTION: u32 = 256; + +/// Largest difference a flattened texel may show (16-bit images, straight values recovered from premultiplied ones) +const TOLERANCE: f32 = 4e-3; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) { + execute(s, "tool.brush", &json!({"size": size, "hardness": 40})).unwrap(); + execute(s, "tool.stroke", &json!({ "points": points })).unwrap(); +} + +/// Every channel's composited value at every texel +fn composite(s: &mut Session) -> Vec<[f32; 3]> { + s.update(); + let channels = s.doc.project.texture_set(0).unwrap().channel_list(); + let cache = &s.caches[0]; + channels.iter().flat_map(|c| (0..RESOLUTION).flat_map(move |y| (0..RESOLUTION).map(move |x| cache.composite.value(*c, x, y)))).collect() +} + +fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) +} + +#[test] +fn a_flattened_folder_looks_the_same_as_the_folder_and_undoes_in_one_step() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "roughness": 0.2, "height": -0.3})).unwrap()); + let below = composite(&mut s); + + // A folder over it: a masked red fill and a soft roughness stroke, with a stroke in the folder's own mask + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.9, "height": 0.4})).unwrap()); + s.target = StackTarget::Mask; + stroke(&mut s, 30, [[170, 200], [230, 200]]); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.6})).unwrap(); + stroke(&mut s, 20, [[200, 160], [200, 240]]); + execute(&mut s, "layer.select", &json!({"layer": folder})).unwrap(); + s.target = StackTarget::Mask; + stroke(&mut s, 40, [[160, 215], [240, 215]]); + let before = composite(&mut s); + + assert!(largest_difference(&before, &below) > 0.1, "the folder shows over the layer below"); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + let after = composite(&mut s); + + assert!(matches!(s.doc.project.layer(LayerId(flat)).unwrap().kind, LayerKind::Fill(_)), "the folder becomes a fill layer"); + assert!(!s.doc.project.layer(LayerId(folder)).unwrap().visible, "the folder is hidden under it"); + assert!(s.doc.project.layer(LayerId(flat)).unwrap().mask.is_some(), "the folder's mask is baked into the new layer"); + assert!(largest_difference(&after, &before) < TOLERANCE, "{}", largest_difference(&after, &before)); + + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + + assert!(largest_difference(&composite(&mut reopened), &before) < TOLERANCE, "the baked images keep their coverage when reopened"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + assert!(s.doc.project.layer(LayerId(flat)).is_err(), "one undo step removes the flattened layer"); + assert!(s.doc.project.layer(LayerId(folder)).unwrap().visible, "and shows the folder again"); +} + +#[test] +fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": folder})).unwrap(); + let before = composite(&mut s); + + id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2047f670..a1cf0a97 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -33,6 +33,7 @@ mod filter_support; mod filter_swap; mod filter_transform; mod filters; +mod flatten_folder; mod folder_contents; mod frame_selection; mod generator_inputs; diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 903b5b53..55754cba 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -173,6 +173,17 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator Result> { + let texels = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)"))); + } + + let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?; + encode_resource_png(&image) +} + fn encode_resource_png(image: &Image) -> Result> { let options = EncodeOptions { png_compression: PngCompression::Fast, ..EncodeOptions::default() }; craft_image_codecs::encode(image, Format::Png, &options).map_err(|error| FormatError::Invalid(error.to_string())) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..2e6fa186 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -45,7 +45,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names, }; -pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; +pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_png}; pub use mesh_export::{ GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings, diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 0eda8d6b..3204a6e6 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1406,7 +1406,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con ui.separator(); solo_menu(app, ui, layer.id); ui.separator(); - run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group()); + let flatten = if layer.is_group() { tr("Flatten folder") } else { tr("Flatten layer") }; + run(app, ui, flatten, "layer.flatten", json!({"layer": layer_id}), true); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name))); From 1ce9ff94b27e23aac50f291ef686aec5d8d8f098 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:09:34 +0000 Subject: [PATCH 06/29] Layers: move the selected effect with Alt+Up and Alt+Down --- crates/engine/src/effect_step.rs | 8 +++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 37 +++++++++++++++++++++++ crates/engine/tests/it/content_effects.rs | 19 ++++++++++++ crates/ui-egui/tests/it/effect_rows.rs | 30 ++++++++++++++++++ 5 files changed, 95 insertions(+) create mode 100644 crates/engine/src/effect_step.rs diff --git a/crates/engine/src/effect_step.rs b/crates/engine/src/effect_step.rs new file mode 100644 index 00000000..32aeb4cf --- /dev/null +++ b/crates/engine/src/effect_step.rs @@ -0,0 +1,8 @@ +//! Which way a step of `effect.moveUp` / `effect.moveDown` moves an effect + +/// Which way an effect moves one place: up is later in its stack (rows list the top first) +#[derive(Clone, Copy)] +pub(crate) enum EffectStep { + Up, + Down, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..7a700ca5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,7 @@ pub mod commands; pub mod decal_cmds; pub mod effect_blending_cmds; pub mod effect_clipboard; +mod effect_step; pub mod file_cmds; pub mod fill_alpha; pub mod fill_hit_test; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e234f654..8fe9c9f2 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_core::{ }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::effect_step::EffectStep; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::session::StackTarget; @@ -113,6 +114,24 @@ pub fn specs() -> Vec { duplicate_effect ), cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), + cmd!( + "effect.moveUp", + "Move effect up", + ["Layers"], + Some("Alt+Up"), + "{effect?: the selected effect} — one place up its stack (applied later)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Up) + ), + cmd!( + "effect.moveDown", + "Move effect down", + ["Layers"], + Some("Alt+Down"), + "{effect?: the selected effect} — one place down its stack (applied earlier)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Down) + ), cmd!( "effect.histogram", "Effect input histogram", @@ -1022,6 +1041,24 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Move an effect one place in its stack (one undo step; nothing at its end) +fn step_effect(s: &mut Session, p: &Value, step: EffectStep) -> Result { + let cmd = match step { + EffectStep::Up => "effect.moveUp", + EffectStep::Down => "effect.moveDown", + }; + let effect = effect_id(s, p, cmd)?; + let (list, index) = stack_of(&mut s.doc.project, effect).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?; + let to = match step { + EffectStep::Up if index + 1 < list.len() => index + 1, + EffectStep::Down if index > 0 => index - 1, + _ => return Ok(json!({ "moved": false })), + }; + + crate::execute(s, "effect.move", &json!({ "effect": effect.0, "index": to }))?; + Ok(json!({ "moved": true })) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index caba4447..29888e0d 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -610,3 +610,22 @@ fn a_color_histogram_has_its_components_and_luminance() { assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]); assert!(roughness.get("components").is_none(), "one value has no components"); } + +#[test] +fn a_named_effect_moves_up_and_down_while_its_layer_content_is_selected() { + let mut s = session(); + let layer = LayerId(id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let add = |s: &mut Session| id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let (bottom, top) = (add(&mut s), add(&mut s)); + let order = |s: &Session| s.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); + s.target = StackTarget::Content; + + execute(&mut s, "effect.moveUp", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [top, bottom]); + + execute(&mut s, "effect.moveDown", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [bottom, top]); +} diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index d17882ba..cccda619 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -94,6 +94,36 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); } +/// Alt+Up and Alt+Down move the selected effect one place in its stack; at its end it stays +#[test] +fn alt_up_and_down_move_the_selected_effect() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| { + harness.key_press_modifiers(egui::Modifiers::ALT, key); + harness.run_steps(3); + }; + harness.get_by_label("Effect A").click(); + harness.run_steps(3); + + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, a, c]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a], "the top effect stays"); + press(&mut harness, egui::Key::ArrowDown); + assert_eq!(order(&harness), [b, a, c]); +} + /// The cross at an effect row's right end removes that effect alone, in one undo step #[test] fn an_effect_rows_cross_removes_it() { 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 07/29] 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). From f7795c349b8a2799443d320d41b2d15c5d519e43 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:00:59 +0000 Subject: [PATCH 08/29] Layers: a height-combination mask makes the layer's height blend Normal Where the mask shows the layer, its height now replaces the height below instead of mixing with it, in the same undo step as the mask. --- crates/engine/src/add_mask_cmds.rs | 18 ++++++++++++++---- crates/engine/tests/it/add_mask_items.rs | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs index be508092..b904f4b7 100644 --- a/crates/engine/src/add_mask_cmds.rs +++ b/crates/engine/src/add_mask_cmds.rs @@ -1,10 +1,10 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection use serde_json::Value; -use texturecraft_core::{BlendMode, EffectKind, Sampling, Source}; +use texturecraft_core::{BlendMode, Channel, EffectKind, Sampling, Source}; use texturecraft_paint::alphas; -use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect}; use crate::{Result, Session, cmd}; @@ -24,9 +24,9 @@ pub fn specs() -> Vec { "Add mask with height combination", ["Layers", "Mask"], None, - "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected", + "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected. The layer's height channel, if it has one, blends Normal", has_layer, - |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(())) + |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |s| height_blends_normal(s, p)) ), cmd!( "effect.add.colorSelection", @@ -40,6 +40,16 @@ pub fn specs() -> Vec { ] } +/// Where a height-combination mask shows the layer, the layer's height replaces the height below instead of mixing with it +fn height_blends_normal(s: &mut Session, p: &Value) -> Result<()> { + let id = layer_param(s, "mask.add.heightCombination", p)?; + if let Some(blend) = s.doc.project.layers.get_mut(&id).and_then(|layer| layer.channels.get_mut(&Channel::Height)) { + blend.mode = BlendMode::Normal; + } + + Ok(()) +} + /// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource fn add_bitmap(s: &mut Session, p: &Value) -> Result { const CMD: &str = "mask.add.bitmap"; diff --git a/crates/engine/tests/it/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs index 1b93b325..94f23c86 100644 --- a/crates/engine/tests/it/add_mask_items.rs +++ b/crates/engine/tests/it/add_mask_items.rs @@ -1,7 +1,7 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; +use texturecraft_engine::core::{BlendMode, Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; use texturecraft_engine::fill_alpha::resource_name; use texturecraft_engine::geom::primitives; use texturecraft_engine::paint::alphas; @@ -75,6 +75,21 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination")); } +#[test] +fn a_height_combination_makes_the_layers_height_blend_normal_in_the_same_step() { + let (mut s, layer) = fill(); + execute(&mut s, "layer.blend", &json!({"layer": layer.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap(); + let height_mode = |s: &Session| s.doc.project.layer(layer).unwrap().channels.get(&Channel::Height).map(|blend| blend.mode); + let before = height_mode(&s); + assert!(before.is_some_and(|mode| mode != BlendMode::Normal), "the height starts out blending another way"); + + execute(&mut s, "mask.add.heightCombination", &json!({"layer": layer.0})).unwrap(); + assert_eq!(height_mode(&s), Some(BlendMode::Normal)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(height_mode(&s), before, "one undo takes the mask and the blend back"); +} + #[test] fn color_selections_go_in_the_mask_and_are_selected() { let (mut s, layer) = fill(); From 2e9c14ecd4296f5fa92e9a9da068774b699b1ae7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:26:27 +0000 Subject: [PATCH 09/29] Layers: the layers under the cursor reuse the session's projection depth maps --- crates/compose/src/eval/layers_at.rs | 10 ++++++---- crates/compose/src/projector_depth_cache.rs | 5 +++++ crates/engine/src/layer_pick.rs | 2 +- crates/engine/src/session.rs | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index 648dcb4c..4c342707 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -8,8 +8,8 @@ use super::{ /// 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)> { +/// 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. Projection depth maps come from `projectors` when it serves `inputs.mesh` +pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (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); @@ -17,8 +17,10 @@ pub fn layers_at(inputs: &Inputs, (x, y): (u32, u32), shown: &[Channel]) -> Vec< return Vec::new(); } - let projectors = ProjectorDepthCache::default(); - let inputs = &EvaluationInputs::new(inputs, &projectors); + // A cache built for another mesh would hand out its depth maps + let unbound = ProjectorDepthCache::default(); + let projectors = if projectors.serves(inputs.mesh) { projectors } else { &unbound }; + 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 diff --git a/crates/compose/src/projector_depth_cache.rs b/crates/compose/src/projector_depth_cache.rs index 47b56a76..ce289922 100644 --- a/crates/compose/src/projector_depth_cache.rs +++ b/crates/compose/src/projector_depth_cache.rs @@ -24,6 +24,11 @@ impl ProjectorDepthCache { } } + /// Whether its depth maps were built for `mesh` + pub(crate) fn serves(&self, mesh: &Mesh) -> bool { + std::ptr::eq(self.mesh.as_ptr(), mesh) + } + pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option> { // Rasterization is serial so tile workers can wait for a single build let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs index 9107fb3e..80f84c7e 100644 --- a/crates/engine/src/layer_pick.rs +++ b/crates/engine/src/layer_pick.rs @@ -25,7 +25,7 @@ impl Session { 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() + self.with_inputs(ts, |inputs| Some(texturecraft_compose::layers_at(inputs, &self.projector_depth_cache, texel, &shown))).unwrap_or_default() } /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..bbc0caa2 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -488,7 +488,7 @@ pub struct Session { /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, /// Projection fill depth maps shared by this session's tile batches. - projector_depth_cache: texturecraft_compose::ProjectorDepthCache, + pub(crate) projector_depth_cache: texturecraft_compose::ProjectorDepthCache, /// The polygon fill box being dragged pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). From 5f51194ab8f195b71b688e6c75e47652f8c3cb50 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:26:27 +0000 Subject: [PATCH 10/29] Layers: a flattened folder's images skip decoding the PNGs just written --- crates/engine/src/layer_ops.rs | 20 ++++++++++++-------- crates/engine/src/resource_cmds.rs | 27 ++++++++++++++++++++++----- crates/formats/src/image_res.rs | 27 ++++++++++++++++++++++++--- crates/formats/src/lib.rs | 2 +- 4 files changed, 59 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 1c0bc970..e11121d3 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; use crate::commands::{CommandSpec, boolp, has_layer, layer_param}; @@ -250,9 +251,9 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { let flat = s.edit("Flatten folder", |s| { let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() }; - for (channel, png) in images { + for (channel, png, image) in images { let file_name = format!("{} flattened {}.png", folder.name, channel.id()); - let name = s.add_image_resource(&file_name, png, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + let name = s.add_decoded_image_resource(&file_name, png, image)?; fill.sources.insert(channel, Source::image(name)); } @@ -282,10 +283,13 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { Ok(json!({ "layer": flat.0 })) } -/// Flattened tiles as one 16-bit RGBA PNG per channel (straight values as a fill reads them, coverage in the alpha), in channel order -fn channel_images(tiles: Vec, size: (u32, u32)) -> Result)>> { +/// One flattened tile of a channel: (tile, value + coverage data) +type ChannelTile = ((u32, u32), Vec); + +/// Flattened tiles as one 16-bit RGBA PNG per channel and its decoded pixels (straight values as a fill reads them, coverage in the alpha), in channel order +fn channel_images(tiles: Vec, size: (u32, u32)) -> Result, DecodedImage)>> { let (width, height) = size; - let mut by_channel: std::collections::BTreeMap)>> = Default::default(); + let mut by_channel: std::collections::BTreeMap> = Default::default(); for (channel, tile, data) in tiles { by_channel.entry(channel).or_default().push((tile, data)); } @@ -322,9 +326,9 @@ fn channel_images(tiles: Vec, size: (u32, u32)) -> Result Arc { Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } +/// Refuse resource files over [`MAX_BYTES`] +fn within_byte_limit(file_name: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() > MAX_BYTES { + return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); + } + + Ok(()) +} + impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { @@ -61,12 +70,21 @@ impl Session { self.add_image_resource_prefixed("", file_name, bytes, max_texels) } + /// [`Self::add_image_resource`] for an image whose decoded pixels the caller already has (bit-identical to decoding `bytes`) + pub(crate) fn add_decoded_image_resource(&mut self, file_name: &str, bytes: Vec, image: texturecraft_formats::DecodedImage) -> Result { + within_byte_limit(file_name, &bytes)?; + Ok(self.insert_image_resource("", file_name, bytes, image)) + } + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> Result { - if bytes.len() > MAX_BYTES { - return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); - } + within_byte_limit(file_name, &bytes)?; let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; + Ok(self.insert_image_resource(prefix, file_name, bytes, image)) + } + + /// Store `bytes` and their decoded `image` under a unique, sanitized name from `file_name` and `prefix`; returns the name + fn insert_image_resource(&mut self, prefix: &str, file_name: &str, bytes: Vec, image: texturecraft_formats::DecodedImage) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); let mut base = sanitize_resource_name(leaf); @@ -95,8 +113,7 @@ impl Session { self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); - - Ok(name) + name } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 55754cba..8be2475e 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -173,15 +173,19 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator Result> { +/// A 16-bit RGBA PNG of `samples` (red, green, blue and alpha per pixel, `width × height`, top row first) and its decoded pixels, as reloading it gives them: one channel of a flattened folder +pub fn rgba16_resource(width: u32, height: u32, samples: &[u16]) -> Result<(Vec, DecodedImage)> { let texels = u64::from(width) * u64::from(height); if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS { return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)"))); } let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?; - encode_resource_png(&image) + let png = encode_resource_png(&image)?; + + // Divide as the PNG decoder does for RGBA, so reload is bit-identical + let rgba = samples.as_chunks::<4>().0.iter().map(|pixel| pixel.map(|sample| f32::from(sample) / f32::from(u16::MAX))).collect(); + Ok((png, DecodedImage { width, height, rgba, srgb: true })) } fn encode_resource_png(image: &Image) -> Result> { @@ -310,6 +314,23 @@ mod tests { assert!(gray16_resource(2, 1, [0.5].into_iter()).is_err()); } + #[test] + fn generated_rgba16_resource_matches_reload_for_every_sample_value() { + // Every value in each of red, green, blue and alpha, with gray pixels as scalar channels write them + let mixed = (0..=u16::MAX).flat_map(|value| [value, value.wrapping_add(1), value.wrapping_add(2), value.wrapping_mul(3)]); + let gray = (0..=u16::MAX).flat_map(|value| [value, value, value, u16::MAX - value]); + let samples: Vec = mixed.chain(gray).collect(); + + let (png, decoded) = rgba16_resource(512, 256, &samples).unwrap(); + + let reloaded = decode_image(&png).unwrap(); + assert_eq!((decoded.width, decoded.height, decoded.srgb), (reloaded.width, reloaded.height, reloaded.srgb)); + for (index, (cached, saved)) in decoded.rgba.iter().zip(&reloaded.rgba).enumerate() { + assert_eq!(cached, saved, "pixel {index}"); + } + assert!(rgba16_resource(2, 1, &[0; 4]).is_err(), "too few samples for the size"); + } + #[test] fn gray16_stops_after_one_excess_pixel() { let mut pixels_read = 0; diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 2e6fa186..5d693a84 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -45,7 +45,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names, }; -pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_png}; +pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_resource}; pub use mesh_export::{ GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings, From b41497e8762a47564d436e83cf28ec5f83680d27 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:30:43 +0000 Subject: [PATCH 11/29] Layers: flattening a folder runs the stack below it once per texel --- crates/compose/src/eval.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 09041f47..d901bbda 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2754,6 +2754,7 @@ fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { } /// Per-texel context. +#[derive(Clone)] struct Texel<'a, 'b> { inp: &'b Inputs<'a>, x: u32, @@ -2779,6 +2780,7 @@ struct Texel<'a, 'b> { /// What a layer contributes (its mask, its content value and coverage per channel): evaluated /// (`Off`), evaluated and recorded, or replayed from a recording. +#[derive(Clone)] enum Tape<'t> { Off, Record(Vec), @@ -5035,18 +5037,15 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]); for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { - // The texel with the stack below the folder run, so masks and fills that read it or its anchors find them - let texel_over_below = || { - let mut texel = Texel::new(&visible_inputs, x, y, offset, 0.0); - if !below.is_empty() { - texel.anchors_below(&below, (id, 0)); - } - texel - }; + // The texel with the stack below the folder run once, so masks and fills that read it or its anchors find them + let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0); + if !below.is_empty() { + over_below.anchors_below(&below, (id, 0)); + } // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide let over = |background: f32| { - let mut texel = texel_over_below(); + let mut texel = over_below.clone(); let mut stack: Acc = [[background; 3]; NCH]; texel.eval(children, &mut stack); stack @@ -5072,7 +5071,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { - pixel.copy_from_slice(&[to_u16(texel_over_below().node_mask(node)), u16::MAX]); + pixel.copy_from_slice(&[to_u16(over_below.node_mask(node)), u16::MAX]); } } From 6d72dbbf940f0cb59501ceb826a8252dfc78bca5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:04:00 +0000 Subject: [PATCH 12/29] Layers: Escape closes the layer list, and a flattened folder keeps its look over the layers below and its hidden state From the first test build: Escape only took the focus off the list's top row, a folder whose layers blend with Multiply, Screen or Overlay over the layers below it flattened into a layer that looked different, and a hidden folder flattened into a visible layer. --- crates/compose/src/eval.rs | 60 ++++++++++++++++++------ crates/engine/src/layer_ops.rs | 3 +- crates/engine/tests/it/flatten_folder.rs | 35 ++++++++++++++ crates/ui-egui/src/menus.rs | 2 + crates/ui-egui/tests/it/layers_panel.rs | 10 +++- 5 files changed, 94 insertions(+), 16 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d901bbda..93c6b0c2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1369,6 +1369,17 @@ fn below_plan<'a>( return Vec::new(); } + stack_plan_below(inp, draw, channels, (tile_x, tile_y), fields) +} + +/// Plan the whole stack up to a draw, whatever the draw reads +fn stack_plan_below<'a>( + inp: &EvaluationInputs<'a>, + draw: (LayerId, usize), + channels: &[Channel], + (tile_x, tile_y): (u32, u32), + fields: Option<&'a Fields>, +) -> Vec> { let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; let compare_effects = layer_mask(inp.project, draw.0).into_iter().flat_map(|mask| mask.effects.iter()); let planned = compared_channels(compare_effects, channels.to_vec()); @@ -4988,6 +4999,26 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti Some(out.into_iter().flatten().collect()) } +/// The premultiplied value and coverage (last) of a Normal layer that shows `shown` over `under`, covering at least `coverage`, with straight values inside `range` (Multiply or Overlay hide each component by a different amount, so the coverage grows where a straight value would leave it); None where it shows the stack as it is +fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, (low, high): (f32, f32)) -> Option<[f32; 4]> { + let needed = under.iter().zip(shown).take(comps).fold(coverage, |needed, (under, shown)| { + let change = shown - under; + let room = if change > 0.0 { high - under } else { under - low }; + if change.abs() <= f32::EPSILON || room <= 0.0 { needed } else { needed.max(change.abs() / room) } + }); + let coverage = needed.min(1.0); + if coverage <= 0.0 { + return None; + } + + // Over `under`, the layer shows its premultiplied value plus what it leaves of the stack + let mut premultiplied = [0.0, 0.0, 0.0, coverage]; + for ((slot, under), shown) in premultiplied.iter_mut().zip(under).zip(shown).take(comps) { + *slot = shown - (1.0 - coverage) * under; + } + Some(premultiplied) +} + /// One tile of a flattened folder's mask: (tile, mask value + coverage data) pub type FlatMaskTile = ((u32, u32), Vec); @@ -5017,7 +5048,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(node) = nodes.first() else { return (Vec::new(), None) }; let Content::Group(children) = &node.content else { return (Vec::new(), None) }; - let below = below_plan(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields), node.lights); + let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields)); // One value + coverage buffer per channel the folder plans; signed channels start at their middle let mut buffers: Vec<(Channel, Vec, bool)> = node @@ -5039,29 +5070,30 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { // The texel with the stack below the folder run once, so masks and fills that read it or its anchors find them let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0); - if !below.is_empty() { - over_below.anchors_below(&below, (id, 0)); - } + over_below.anchors_below(&below, (id, 0)); + let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); - // Laid over an all-0 and an all-1 stack, the layers show their premultiplied value and how much of the stack they hide - let over = |background: f32| { + // The layers over an all-0 and an all-1 stack show how much of the stack they hide, and over the real stack what they show there + let over = |mut stack: Acc| { let mut texel = over_below.clone(); - let mut stack: Acc = [[background; 3]; NCH]; texel.eval(children, &mut stack); stack }; - let (low, high) = (over(0.0), over(1.0)); + let (low, high, shown) = (over([[0.0; 3]; NCH]), over([[1.0; 3]; NCH]), over(stack_below)); for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) { - let (Some(premultiplied), Some(shown)) = (low.get(planned.ch), high.get(planned.ch)) else { continue }; - let comps = planned.comps.min(3); - let hidden = premultiplied.iter().zip(shown).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; - let coverage = hidden.clamp(0.0, 1.0); - if coverage <= 0.0 { + let (Some(low), Some(high), Some(shown), Some(under)) = + (low.get(planned.ch), high.get(planned.ch), shown.get(planned.ch), stack_below.get(planned.ch)) + else { continue; - } + }; + let comps = planned.comps.min(3); + let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; + let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) }; + let Some(premultiplied) = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range) else { continue }; *laid_down = true; let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; + let coverage = premultiplied[3]; for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) { *slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) }; } diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index e11121d3..4f1cf4d1 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -236,7 +236,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } -/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept +/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; @@ -260,6 +260,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default let channels: Vec = fill.sources.keys().copied().collect(); let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); + layer.visible = folder.visible; for (channel, blend) in &mut layer.channels { blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); } diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 741f7e80..77fefc27 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -97,3 +97,38 @@ fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// Inside a folder, layers blending with Multiply, Screen or Overlay over the layers below the folder hide each part of the stack by a different amount: the flattened layer still shows what they did +#[test] +fn a_flattened_folder_looks_the_same_when_its_layers_blend_with_the_layers_below_it() { + for mode in ["multiply", "screen", "overlay"] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.8], "roughness": 0.4})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.9, 0.3, 0.1], "roughness": 0.7})).unwrap()); + for channel in ["baseColor", "roughness"] { + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": channel, "mode": mode})).unwrap(); + } + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{mode}: {}", largest_difference(&composite(&mut s), &before)); + } +} + +/// A hidden folder shows nothing, so the layer it flattens into is hidden too +#[test] +fn a_hidden_folder_flattens_into_a_hidden_layer() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder"); + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change"); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..be585658 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -528,6 +528,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; + } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.layer_pick_list = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index a2dc1368..38c865c4 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -543,7 +543,7 @@ 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 +/// 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, and Escape closes it #[test] fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() { let (mut h, _) = harness(); @@ -585,4 +585,12 @@ fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_withou 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"); + + // The first Escape moves egui's focus off the top row: the list must close on it all the same + open_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing"); } From f3d14a3ab413629f33c4f1ae428f1ab15814bda4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:01:24 +0000 Subject: [PATCH 13/29] Layers: a row's eye and blend menu act on its layer when no layer is selected --- crates/engine/src/commands.rs | 25 +++++++++++++++++++- crates/engine/tests/it/layer_multi_select.rs | 18 +++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..9d32be37 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -188,6 +188,29 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } +/// [`check_enabled`] for a run with `params`: a command that takes `layer` is checked as if the +/// layer it names were the selected one, so a row's own controls work with no layer selected +/// (after an undo, say). +fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { + let refused = match check_enabled(spec, s) { + Ok(()) => return Ok(()), + Err(why) => why, + }; + let named = u64p(params, "layer").map(texturecraft_core::LayerId).filter(|_| spec.params.contains("layer?")); + let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; + if ts != s.ts() { + return Err(refused); + } + + let selected = s.selected.insert(ts, id); + let named_refused = check_enabled(spec, s); + match selected { + Some(old) => s.selected.insert(ts, old), + None => s.selected.remove(&ts), + }; + named_refused +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { command_specs().iter().find(|c| c.id == id) } @@ -196,7 +219,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// `merge: true` its edits continue the previous undo step of the same label (drags). pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + check_enabled_for(spec, s, params).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false)); let result = (spec.run)(s, params); s.merge_edits = outer; diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs index 14c375d8..f6dfe110 100644 --- a/crates/engine/tests/it/layer_multi_select.rs +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -3,7 +3,7 @@ //! act on every selected layer in one undo step. use serde_json::{Value, json}; -use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::core::{BlendMode, Channel, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::layer_selection::stack_rows; use texturecraft_engine::{Session, execute}; @@ -523,3 +523,19 @@ fn moving_layers_into_a_folder_in_another_set_preserves_the_document() { assert_eq!(s.history_labels(), history); } } + +#[test] +fn a_rows_controls_act_on_its_layer_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + // An undo can leave no layer selected; the row's eye and blend menu still name their layer + s.selected.clear(); + + execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": a.0, "channel": "baseColor", "mode": "Multiply"})).unwrap(); + let layer = s.doc.project.layer(a).unwrap(); + assert!(!layer.visible, "the eye hid its layer"); + assert_eq!(layer.blend(Channel::BaseColor).map(|b| b.mode), Some(BlendMode::Multiply), "the blend menu changed its layer"); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); + assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on"); +} From ca4ea4bccff135ca3b843f4e0b3f2921293f5f34 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:43:49 +0000 Subject: [PATCH 14/29] Layers: shorten the enabled-check comment --- crates/engine/src/commands.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 76728ea2..04fc918c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,9 +193,7 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`: a command that takes `layer` is checked as if the -/// layer it names were the selected one, so a row's own controls work with no layer selected -/// (after an undo, say). +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer` as if the named layer were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), From 70509468e83ec2bdd3c25b93507a73b630aa14ed Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:03 +0000 Subject: [PATCH 15/29] Layers: a generator swapped in place takes its new kind's name --- crates/engine/src/mask_cmds.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 892e50f3..905c1a35 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -1122,6 +1122,13 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result { session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some(generator) = swapped_generator { + // A name taken from the kind follows the new kind, unless one is given with the change + if let EffectKind::Generator(old) = &edited.kind + && (edited.name == old.kind.label() || edited.name == FORMER_GENERATOR_NAME) + { + edited.name = generator.kind.label().to_string(); + } + edited.kind = EffectKind::Generator(generator); } if let Some((kind, label)) = swapped { @@ -1153,11 +1160,6 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result { if let Some(kind) = generator_kind && kind != generator.kind { - // A name taken from the kind follows the new kind - let named_by_kind = edited.name == generator.kind.label() || edited.name == FORMER_GENERATOR_NAME; - if named_by_kind && name_param(params).is_none() { - edited.name = kind.label().to_string(); - } generator.kind = kind; generator.detail = Generator::new(kind).detail; generator.inputs.retain(|map, _| kind.inputs().contains(map)); From 8b1b43246072cdf11ff3d2fde5385a1ccb6783e0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:52:06 +0000 Subject: [PATCH 16/29] Layers: open the effect stack from its thumbnail in the effect row tests --- crates/ui-egui/tests/it/effect_rows.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 663c57e2..27efc47b 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -74,8 +74,12 @@ fn an_effect_rows_menu_moves_it_within_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| { @@ -109,8 +113,12 @@ fn alt_up_and_down_move_the_selected_effect() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| { @@ -140,8 +148,12 @@ fn an_effect_rows_cross_removes_it() { let a = add("Effect A"); add("Effect B"); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); let undo_steps = harness.state().session.history_labels().len(); let at = harness.get_by_label("Remove effect Effect B").rect().center(); From 1f4981ea98f9866f505259eff56c8166b795ede4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:22 +0000 Subject: [PATCH 17/29] Layers: flatten folder and R + click build anchor micro heights as the composite does --- crates/compose/src/eval.rs | 3 ++- crates/compose/src/eval/layers_at.rs | 14 +++++++++++--- crates/engine/tests/it/flatten_folder.rs | 24 ++++++++++++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2433de66..51dd1b50 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -5630,7 +5630,8 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; let projectors = ProjectorDepthCache::default(); - let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let mut visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + prepare_generators(&mut visible_inputs, Some(id)); let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index 4c342707..d078629f 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -2,7 +2,7 @@ use super::{ BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, - evaluation_fields, plan, + evaluation_fields, plan, prepare_generators, }; /// Below this weight a layer leaves the texel unchanged (one 16-bit step) @@ -19,8 +19,16 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 // A cache built for another mesh would hand out its depth maps let unbound = ProjectorDepthCache::default(); - let projectors = if projectors.serves(inputs.mesh) { projectors } else { &unbound }; - let inputs = &EvaluationInputs::new(inputs, projectors); + let served = projectors.serves(inputs.mesh); + let mut inputs = EvaluationInputs::new(inputs, if served { projectors } else { &unbound }); + + // The viewport's anchor heights are kept for the next query + if served { + inputs = inputs.of_the_session_stack(); + } + prepare_generators(&mut inputs, None); + + let inputs = &inputs; 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 diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 77fefc27..4a085bce 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -34,8 +34,8 @@ fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) { fn composite(s: &mut Session) -> Vec<[f32; 3]> { s.update(); let channels = s.doc.project.texture_set(0).unwrap().channel_list(); - let cache = &s.caches[0]; - channels.iter().flat_map(|c| (0..RESOLUTION).flat_map(move |y| (0..RESOLUTION).map(move |x| cache.composite.value(*c, x, y)))).collect() + let composite = &s.caches[0].composite; + channels.iter().flat_map(|c| (0..composite.height).flat_map(move |y| (0..composite.resolution).map(move |x| composite.value(*c, x, y)))).collect() } fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { @@ -132,3 +132,23 @@ fn a_hidden_folder_flattens_into_a_hidden_layer() { assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder"); assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change"); } + +/// A generator whose micro height reads an anchor point bakes as the viewport shows it +#[test] +fn a_flattened_folder_keeps_a_generators_anchor_micro_height() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap()["effect"].as_u64().unwrap(); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); + let generator = execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} From 4c2df2a0a0287f75cb18fbf347ec1b8abe42c58c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:24 +0000 Subject: [PATCH 18/29] Layers: R + click reads each compare mask against the layers below its own layer --- crates/compose/src/eval/layers_at.rs | 29 +++++++++++++++++----------- crates/engine/tests/it/layer_pick.rs | 23 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs index d078629f..234247a8 100644 --- a/crates/compose/src/eval/layers_at.rs +++ b/crates/compose/src/eval/layers_at.rs @@ -1,8 +1,8 @@ -//! Which layers lay something down at one texel, for the viewport's Pick layer tool +//! Which layers lay something down at one texel, for R + click on the model use super::{ - BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, - evaluation_fields, plan, prepare_generators, + Acc, BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, + evaluation_fields, mix_group, plan, prepare_generators, }; /// Below this weight a layer leaves the texel unchanged (one 16-bit step) @@ -38,12 +38,9 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 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 stack = Channel::ALL.map(Channel::default_value); let mut found = Vec::new(); - texel.layers_laying_down(&nodes, [1.0; NCH], shown, &mut found); + texel.layers_laying_down(&nodes, &mut stack, [1.0; NCH], shown, &mut found); // The stack runs bottom first found.reverse(); @@ -51,11 +48,15 @@ pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32 } 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)>) { + /// Composite `nodes` (bottom first) over `stack`, pushing the leaf layers 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], stack: &mut Acc, weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { for node in nodes { + // A mask comparing with the layers below reads the stack under its own layer + self.below = Some(*stack); let mask = self.node_mask(node); if mask <= 0.0 { + // A masked-out layer still records its anchor points + self.eval(std::slice::from_ref(node), stack); continue; } @@ -67,7 +68,11 @@ impl Texel<'_, '_> { } match &node.content { - Content::Group(children) => self.layers_laying_down(children, node_weights, shown, found), + Content::Group(children) => { + let mut inner = *stack; + self.layers_laying_down(children, &mut inner, node_weights, shown, found); + mix_group(stack, &inner, &node.chans, mask); + } content => { let changed: Vec = shown .iter() @@ -87,6 +92,8 @@ impl Texel<'_, '_> { if !changed.is_empty() { found.push((node.draw.0, changed)); } + + self.eval(std::slice::from_ref(node), stack); } } } diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index dcd8d38d..f52d661f 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -100,3 +100,26 @@ fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() { 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"); } + +/// Each height-combination mask compares with the layers below its own layer, not below another's +#[test] +fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() { + let (mut s, ..) = stack(); + let add = |s: &mut Session, height: f32| id(execute(s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "height": height})).unwrap()); + let base = add(&mut s, 0.0); + let lower = add(&mut s, 0.3); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": lower})).unwrap(); + let raised = add(&mut s, 0.6); + let upper = add(&mut s, 0.9); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": upper})).unwrap(); + for layer in [base, raised] { + execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "height", "mode": "Normal"})).unwrap(); + } + execute(&mut s, "layer.blend", &json!({"layer": raised, "channel": "baseColor", "enabled": false})).unwrap(); + s.update(); + + let listed: Vec = layers_at(&mut s, MIDDLE).into_iter().map(|(layer, _)| layer).collect(); + + assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}"); + assert!(listed.contains(&upper), "and so does the upper one: {listed:?}"); +} From 03b4c60a75558e48288a7427f81d2d340c92027f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:27 +0000 Subject: [PATCH 19/29] Layers: a folder flattened inside a scaled or turned folder keeps its images in place --- crates/engine/src/layer_ops.rs | 8 +++++++- crates/engine/tests/it/flatten_folder.rs | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 4f1cf4d1..d588adc6 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; -use texturecraft_core::{Channel, ChannelKind, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source}; +use texturecraft_core::{ + Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source, +}; use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; @@ -257,6 +259,10 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { fill.sources.insert(channel, Source::image(name)); } + // The folders around lay their Scale and Rotation on the new fill too: starting it at the opposite keeps the images in place + let around = s.doc.project.contents_around(folder.id); + fill.projection = ContentsOffset::new(around.scale.recip(), -around.rotation).apply(&fill.projection); + // Only the channels the folder lays down, at its opacity (a folder mixes its result in by opacity alone, whatever its blend mode): a channel without an image would cover the stack with its default let channels: Vec = fill.sources.keys().copied().collect(); let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 4a085bce..1d364d01 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -152,3 +152,20 @@ fn a_flattened_folder_keeps_a_generators_anchor_micro_height() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// A folder holding this one lays its Scale and Rotation on every fill inside it: the baked images stay where they were baked +#[test] +fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + stroke(&mut s, 30, [[170, 190], [230, 210]]); + execute(&mut s, "folder.contents.set", &json!({"layer": outer, "scale": 2.0, "rotation": 45.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": inner})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} From 7f14dce2529782762607e3b80b068670ff1c336e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:29 +0000 Subject: [PATCH 20/29] Layers: refuse to flatten a folder of a texture set with several UV tiles --- crates/engine/src/layer_ops.rs | 5 +++++ crates/engine/tests/it/flatten_folder.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index d588adc6..587584bc 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -240,6 +240,11 @@ fn flatten(s: &mut Session, p: &Value) -> Result { /// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { + // A fill reads its image again on every UV tile, so an image of several tiles would repeat on each + if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 { + return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into())); + } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 1d364d01..4933aa18 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -169,3 +169,24 @@ fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() { assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); } + +/// A fill reads one image again on every UV tile, so a folder of a set with several tiles is refused instead of baked wrong +#[test] +fn flattening_a_folder_over_several_uv_tiles_is_refused() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": fill})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": fill, "procedural": "checker", "scale": 3.0})).unwrap(); + assert!(s.doc.project.texture_sets[0].uv_tiles.len() > 1, "the plane spans two UV tiles"); + let before = composite(&mut s); + let steps = s.history_labels().len(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert!(flattened.is_err(), "refused"); + assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); +} From 9a188f4077d39a9f57d9a69589b057b4ff811641 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:32 +0000 Subject: [PATCH 21/29] Layers: layer.pickAt refuses a layer that is no id instead of picking the top one --- crates/engine/src/layer_cmds.rs | 9 +++++++-- crates/engine/tests/it/layer_pick.rs | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 9a81da03..8aa84d9e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "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)", + "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects the top layer laying something down there in the shown channels, or `layer`, refused when it lays nothing down there (R + click)", always, pick_at ), @@ -303,7 +303,12 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { 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); + + // A `layer` that is no id is refused rather than read as none + let wanted = match p.get("layer").filter(|layer| !layer.is_null()) { + Some(_) => Some(u64p(p, "layer").map(LayerId).ok_or_else(|| bad("layer.pickAt", "`layer` must be a layer id"))?), + None => None, + }; let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?; Ok(json!({ "layer": id.0 })) } diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index f52d661f..408ecc05 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -123,3 +123,14 @@ fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() { assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}"); assert!(listed.contains(&upper), "and so does the upper one: {listed:?}"); } + +#[test] +fn a_pick_of_something_that_is_not_a_layer_id_is_refused() { + let (mut s, ..) = stack(); + let selected = s.selected_layer(); + + let reply = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": "fill"})); + + assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}"); + assert_eq!(s.selected_layer(), selected); +} From 4b2729ee715916bdc1bf95d56b951e9f2f5246f5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:35 +0000 Subject: [PATCH 22/29] Layers: the R + click list comes before an armed point or focus pick, and its closing press paints nothing in 2D --- crates/ui-egui/src/menus.rs | 5 +- crates/ui-egui/src/viewport.rs | 10 ++-- crates/ui-egui/tests/it/layers_panel.rs | 79 +++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ba37bd5e..2b1712ff 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -557,12 +557,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // The open list or export input handles the key } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; + } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The list opens over an armed point pick, so it closes first + app.layer_pick_list = None; } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; } else if !escape_is_free { // The picker window handles the key - } else if app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { - app.layer_pick_list = None; } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 561002a6..fc23cab0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -920,14 +920,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::layer_pick_list::click(app, pointer, local(pointer), rect); } + // R + click and the list it opens come before an armed point or focus pick, including the press that closes the list + let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app); + // A 3D generator's armed point pick: a click sets the point there instead of painting let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session); if let Some(pick) = point_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - - // R + click still picks a layer while a pick is armed if !alt - && !r_held + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -947,7 +948,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if picking_focus_distance { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && !r_held + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -2319,6 +2320,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let painting = tool_acts(app) && !projection_hint && app.properties_popup.is_none() + && !crate::layer_pick_list::blocks_view_input(app) && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !crate::color_picker::blocks_view_press(ui.ctx()) && !alt diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 8c670db2..fee74407 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -841,3 +841,82 @@ fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_withou assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing"); } + +/// Two fills over the whole model, so R + click opens the list; returns the 3D view +fn two_fills(h: &mut Harness<'_, TextureCraftApp>) -> egui::Rect { + for name in ["Lower fill", "Upper fill"] { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": name, "color": "#aa3322"})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + h.state().viewport_rect +} + +/// R + click at the middle of the 3D view +fn open_pick_list(h: &mut Harness<'_, TextureCraftApp>) { + let middle = h.state().viewport_rect.center(); + 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(middle); + h.run_steps(1); + click(h, middle); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().layer_pick_list.is_some(), "the list is open"); +} + +/// The list opened over an armed point pick is the innermost thing: Escape closes it first, and a press that closes it sets no point +#[test] +fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_pick() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap(); + let effect = id(execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "3dDistance"})).unwrap(), "effect"); + h.run_steps(SETTLE_FRAMES); + let generator = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone(); + let armed = + |h: &Harness<'_, TextureCraftApp>| h.get_by_label("Pick 3D Position on the mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + h.get_by_label("Pick 3D Position on the mesh").click(); + h.run_steps(SETTLE_FRAMES); + assert!(armed(&h), "the pick is armed"); + let before = generator(&h); + + open_pick_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert!(armed(&h), "and leaves the point pick armed"); + + open_pick_list(&mut h); + click(&mut h, view.center() - egui::vec2(60.0, 40.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "a press outside closes the list"); + assert_eq!(generator(&h), before, "and sets no point"); + assert!(armed(&h)); +} + +/// In the split view, a press on the 2D view that closes the list paints nothing there +#[test] +fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { + let (mut h, _) = harness(); + two_fills(&mut h); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split; + h.run_steps(SETTLE_FRAMES); + let view = h.state().viewport_rect; + let over_2d = egui::pos2(view.right() + view.width() * 0.5, view.center().y); + let steps = h.state().session.history_labels().len(); + open_pick_list(&mut h); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the press closes the list"); + assert_eq!(h.state().session.history_labels().len(), steps, "and paints no stroke"); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().session.history_labels().len() > steps, "the next press paints there"); +} From 671cdb3c5b5df80807e37ded3aa320c1eed39408 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:37 +0000 Subject: [PATCH 23/29] Layers: close the R + click list when the document changes --- crates/ui-egui/src/layer_pick_list.rs | 10 +++++++--- crates/ui-egui/tests/it/layers_panel.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs index 39558758..ab0f37c9 100644 --- a/crates/ui-egui/src/layer_pick_list.rs +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -46,6 +46,8 @@ pub struct LayerPickList { bounds: Rect, /// The layers there, top first, each with the channels it changes there rows: Vec<(LayerId, Vec)>, + /// The document revision the rows were read at: any change, or another project, closes the list + revision: u64, /// 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 @@ -59,7 +61,9 @@ type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String); 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 }), + Ok((_, rows)) if rows.len() > 1 => { + app.layer_pick_list = Some(LayerPickList { at, point, bounds, rows, revision: app.session.revision, opening: true, closing: false }); + } _ => { app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); } @@ -99,13 +103,13 @@ 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 +/// Draws the open list; a row click selects its layer; Esc, a press outside or a document change 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 app.ui.mode != Mode::Painting || escape || list.revision != app.session.revision => app.layer_pick_list = None, Some(list) if list.closing => { if !any_down { app.layer_pick_list = None; diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index fee74407..7efe5ba0 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -896,6 +896,19 @@ fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_ assert!(armed(&h)); } +/// The list names layers of the stack it was opened on: an edit, an undo or another project closes it +#[test] +fn the_layer_pick_list_closes_when_the_document_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + execute(&mut h.state_mut().session, "edit.undo", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none()); +} + /// In the split view, a press on the 2D view that closes the list paints nothing there #[test] fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { From 1f79735dcd2ce85ad7eaf6b8ac3927fac3e8e401 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:40 +0000 Subject: [PATCH 24/29] Layers: the smart material picker lists saved materials before the Assets panel has shown --- crates/ui-egui/src/layer_toolbar.rs | 7 ++++++- crates/ui-egui/src/shelf.rs | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index ec6b1eb5..1a80062a 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -489,6 +489,11 @@ fn bitmap_tabs(session: &Session) -> Vec> { /// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) { + // The saved materials are otherwise read only while the Assets panel shows + if egui::Popup::is_id_open(&anchor.ctx, popup) { + crate::shelf::scan_library(app); + } + let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default()); match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { Some(SmartMaterialChoice::BuiltIn(id)) => { @@ -501,7 +506,7 @@ fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id } } -/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved (once the shelf has read them) +/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved fn smart_material_tabs(library: &[PathBuf]) -> Vec> { let built_in = MATERIALS .iter() diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 75e72846..a7b76133 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -427,7 +427,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { /// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn scan_library(app: &mut TextureCraftApp) { +pub(crate) fn scan_library(app: &mut TextureCraftApp) { if app.library.is_some() { return; } @@ -453,7 +453,7 @@ fn scan_library(app: &mut TextureCraftApp) { } #[cfg(target_arch = "wasm32")] -fn scan_library(_: &mut TextureCraftApp) {} +pub(crate) fn scan_library(_: &mut TextureCraftApp) {} /// A saved smart material's name: its file name without the extension pub(crate) fn saved_material_name(path: &std::path::Path) -> &str { From 62051b42df30501f277677c1d4a1916020527d2a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:02:43 +0000 Subject: [PATCH 25/29] Layers: document flatten folder, effect moves and the layer commands --- docs/control-protocol.md | 13 +++++++++++-- docs/features.md | 9 +++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9c65e129..2af71ba5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -22,7 +22,8 @@ Submitting the current name leaves history unchanged. The project file keeps its `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies -one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the +one just above itself. `effect.moveUp {effect?}` / `effect.moveDown {effect?}` move the named (or +selected) effect one place and reply `{moved}` (false at that end). `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and @@ -37,7 +38,15 @@ layer, the others in stack order; `layer.duplicate` puts the copies in one block topmost selected layer. Without `layer`, `layer.remove`, `layer.duplicate`, `layer.group` and `layer.visible` act on every selected layer; each of them and `layer.move {layers, above | index}` also take an explicit `layers` list. `session.inspect` lists the -selection as `selectedLayers` (top row first). +selection as `selectedLayers` (top row first). A command that takes `layer` is checked against +the named layer of the active texture set, so it runs even with nothing selected. + +`layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a +viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels). +`layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there. +`layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's +result as image resources, and hides the folder; it is refused for a texture set with several UV +tiles. `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation diff --git a/docs/features.md b/docs/features.md index cda64d94..ec08683e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -51,6 +51,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA 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. +- **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the + folder's result as one image per channel, with the folder's mask painted into the new layer's + mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked + as they look over them at that moment. Not available for a texture set with several UV tiles. +- **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's + Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack. +- **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in + and saved smart materials. +- **Height combination masks** (Add mask menus) also set the layer's height to blend Normal. - **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). From de7c45bde07391e39160dab2d24b0e90aa065025 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:59:07 +0000 Subject: [PATCH 26/29] Layers: answer review: solo picking, flattened folder anchors and instance opacity, pick list and R key edge cases --- crates/compose/src/eval.rs | 5 +- crates/engine/src/commands.rs | 7 +- crates/engine/src/layer_ops.rs | 36 ++++++- crates/engine/src/layer_pick.rs | 9 +- crates/engine/tests/it/flatten_folder.rs | 99 ++++++++++++++++++++ crates/engine/tests/it/layer_multi_select.rs | 16 ++++ crates/engine/tests/it/layer_pick.rs | 16 +++- crates/ui-egui/src/layer_pick_list.rs | 23 ++++- crates/ui-egui/src/layer_toolbar.rs | 2 +- crates/ui-egui/src/menus.rs | 6 +- crates/ui-egui/src/viewport.rs | 22 +++-- crates/ui-egui/tests/it/layer_toolbar.rs | 20 ++++ crates/ui-egui/tests/it/layers_panel.rs | 73 +++++++++++++++ docs/control-protocol.md | 3 +- docs/features.md | 3 +- 15 files changed, 313 insertions(+), 27 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 51dd1b50..ed437f09 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -5666,6 +5666,9 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt over_below.anchors_below(&below, (id, 0)); let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + // The folder's mask goes first, as in a full render: its children can read its anchor points + let folder_mask = over_below.node_mask(node); + // The layers over an all-0 and an all-1 stack show how much of the stack they hide, and over the real stack what they show there let over = |mut stack: Acc| { let mut texel = over_below.clone(); @@ -5696,7 +5699,7 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { - pixel.copy_from_slice(&[to_u16(over_below.node_mask(node)), u16::MAX]); + pixel.copy_from_slice(&[to_u16(folder_mask), u16::MAX]); } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 04fc918c..82c18f99 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,13 +193,16 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`, checking a command that takes `layer` as if the named layer were selected +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (the effect's own) were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), Err(why) => why, }; - let named = u64p(params, "layer").map(texturecraft_core::LayerId).filter(|_| spec.params.contains("layer?")); + let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId); + let named = id_param("layer") + .filter(|_| spec.params.contains("layer?")) + .or_else(|| id_param("effect").filter(|_| spec.params.starts_with("{effect")).and_then(|effect| s.doc.project.effect(effect).map(|(owner, _)| owner))); let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; if ts != s.ts() { return Err(refused); diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 587584bc..2a146a0a 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ - Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Sampling, Source, + Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source, }; use texturecraft_formats::DecodedImage; use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; @@ -205,7 +205,7 @@ fn flatten(s: &mut Session, p: &Value) -> Result { // An instance flattens what it draws into a plain layer of its own let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?; if content.is_group() { - return flatten_folder(s, ts, &layer); + return flatten_folder(s, ts, &layer, &content); } s.update(); @@ -238,13 +238,18 @@ fn flatten(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0 })) } -/// Flatten `folder` of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did -fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { +/// Flatten `folder` (drawing `drawn`: itself, or an instance's source) of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did +fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> Result { // A fill reads its image again on every UV tile, so an image of several tiles would repeat on each if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 { return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into())); } + // Hiding the folder takes its anchor points with it: whatever reads one from outside would change + if folder.visible && anchor_read_outside(&s.doc.project, folder.id) { + return Err(EngineError::Other("a layer outside the folder reads one of its anchor points: flattening would change it".into())); + } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); @@ -273,7 +278,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); layer.visible = folder.visible; for (channel, blend) in &mut layer.channels { - blend.opacity = folder.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); + blend.opacity = drawn.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); } if !mask.is_empty() { let paint = s.doc.project.alloc_id(); @@ -295,6 +300,27 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer) -> Result { Ok(json!({ "layer": flat.0 })) } +/// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away +fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { + // An instance inside draws its source, which stays on screen where it is: the source can be such a reader + let mut hidden = std::collections::BTreeSet::new(); + let mut unvisited = vec![folder]; + while let Some(id) = unvisited.pop() { + if hidden.insert(id) { + unvisited.extend(project.layers.get(&id).into_iter().flat_map(|layer| layer.children().iter().copied())); + } + } + + let anchors = project + .render_tree(&[folder]) + .into_iter() + .filter_map(|id| project.layers.get(&id)) + .flat_map(|layer| layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter())) + .filter(|effect| matches!(effect.kind, EffectKind::Anchor)); + + anchors.flat_map(|anchor| project.anchor_readers(anchor.id)).any(|(reader, _)| !hidden.contains(&reader)) +} + /// One flattened tile of a channel: (tile, value + coverage data) type ChannelTile = ((u32, u32), Vec); diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs index 80f84c7e..404b019c 100644 --- a/crates/engine/src/layer_pick.rs +++ b/crates/engine/src/layer_pick.rs @@ -25,7 +25,14 @@ impl Session { 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, &self.projector_depth_cache, texel, &shown))).unwrap_or_default() + // A solo hides layers on screen: they are not there to pick + let solo_view = self.solo_view(); + self.with_inputs(ts, |inputs| { + let inputs = + texturecraft_compose::Inputs { project: solo_view.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs }; + Some(texturecraft_compose::layers_at(&inputs, &self.projector_depth_cache, texel, &shown)) + }) + .unwrap_or_default() } /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 4933aa18..c97f46d0 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -39,6 +39,8 @@ fn composite(s: &mut Session) -> Vec<[f32; 3]> { } fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + // `f32::max` drops a NaN operand, so a broken composite would compare as equal + assert!(a.iter().chain(b).flatten().all(|value| value.is_finite()), "the composite holds only finite values"); a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) } @@ -190,3 +192,100 @@ fn flattening_a_folder_over_several_uv_tiles_is_refused() { assert!(flattened.is_err(), "refused"); assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); } + +/// A child reading an anchor point of the folder's own mask keeps what it read +#[test] +fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": folder, "target": "mask", "value": 0.4})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// An instance of a folder draws at its source's channel opacity, so it flattens at it +#[test] +fn a_flattened_folder_instance_keeps_the_folders_opacity() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.25})).unwrap(); + + // With the folder selected the instance would go inside it + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": instance})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Hiding a folder takes its anchor points with it, so a layer outside reading one would change: refused, nothing touched +#[test] +fn flattening_a_folder_whose_anchor_point_is_read_outside_it_is_refused() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.0})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": folder})).unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor, "anchorChannel": "roughness"})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance's own mask goes with the hidden instance, and an outside layer stays on screen when only an instance of it sits in the folder +#[test] +fn flattening_is_refused_for_anchor_points_read_through_instances() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + let read = |s: &mut Session, anchor: u64| { + execute(s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + }; + let anchor = |s: &mut Session, layer: u64, target: &str| { + execute(s, "effect.add.anchor", &json!({"layer": layer, "target": target})).unwrap()["effect"].as_u64().unwrap() + }; + + // The anchor point sits in the instance's own mask + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": instance})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + let own = anchor(&mut s, instance, "mask"); + read(&mut s, own); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": instance})).is_err(), "the instance's own anchor point is read outside it"); + + // The reader is also instanced inside the folder, and reads an anchor point there + execute(&mut s, "layer.remove", &json!({"layer": instance})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap(); + let inside = anchor(&mut s, child, "content"); + read(&mut s, inside); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside"); +} diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs index f6dfe110..9d37db3d 100644 --- a/crates/engine/tests/it/layer_multi_select.rs +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -539,3 +539,19 @@ fn a_rows_controls_act_on_its_layer_with_no_layer_selected() { assert_eq!(s.selected_layer(), None, "the selection stays as it was"); assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on"); } + +#[test] +fn an_effect_rows_menu_moves_its_effect_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + let add = + |s: &mut Session| execute(s, "effect.add.filter", &json!({"layer": a.0, "target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + let (lower, upper) = (add(&mut s), add(&mut s)); + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(a).unwrap().content_effects.iter().map(|effect| effect.id.0).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs index 408ecc05..501b2267 100644 --- a/crates/engine/tests/it/layer_pick.rs +++ b/crates/engine/tests/it/layer_pick.rs @@ -1,10 +1,10 @@ //! 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::core::{LayerId, LayerKind}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, Solo, 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]; @@ -134,3 +134,15 @@ fn a_pick_of_something_that_is_not_a_layer_id_is_refused() { assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}"); assert_eq!(s.selected_layer(), selected); } + +#[test] +fn a_soloed_layer_is_the_only_one_listed_and_picked() { + let (mut s, fill, ..) = stack(); + s.set_solo(Some(Solo { layer: LayerId(fill), ignore_mask: false })); + s.update(); + + let order: Vec = layers_at(&mut s, MIDDLE).iter().map(|(layer, _)| *layer).collect(); + + assert_eq!(order, [fill], "the layers solo hides are not on screen"); + assert_eq!(click(&mut s, MIDDLE), Some(fill)); +} diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs index ab0f37c9..37165cf6 100644 --- a/crates/ui-egui/src/layer_pick_list.rs +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -4,6 +4,7 @@ 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::OrbitCamera; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::session::ViewMode; @@ -44,6 +45,8 @@ pub struct LayerPickList { point: Vec2, /// The view the list stays inside bounds: Rect, + /// The viewport size and camera `point` was taken in: a change to either closes the list + viewport_and_camera: (Vec2, OrbitCamera), /// The layers there, top first, each with the channels it changes there rows: Vec<(LayerId, Vec)>, /// The document revision the rows were read at: any change, or another project, closes the list @@ -62,7 +65,16 @@ pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Re 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, revision: app.session.revision, opening: true, closing: false }); + app.layer_pick_list = Some(LayerPickList { + at, + point, + bounds, + viewport_and_camera: (viewport, app.session.camera), + rows, + revision: app.session.revision, + opening: true, + closing: false, + }); } _ => { app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); @@ -103,7 +115,7 @@ fn area_id() -> egui::Id { egui::Id::unique("layer_pick_list") } -/// Draws the open list; a row click selects its layer; Esc, a press outside or a document change closes it +/// Draws the open list; a row click selects its layer; Esc, a press outside or a document or view change 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))); @@ -115,6 +127,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.layer_pick_list = None; } } + Some(list) if list.viewport_and_camera != (app.session.viewport, app.session.camera) => 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, _ => {} } @@ -193,7 +206,11 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Chann 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) { + + // Rows scrolled out of view ask for no thumbnail + if ui.is_rect_visible(thumbnail) + && 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); } diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 1a80062a..ae07a213 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -275,7 +275,7 @@ fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id if response.clicked() { resource_picker::toggle(ui.ctx(), popup); } - if response.hovered() || egui::Popup::is_id_open(ui.ctx(), popup) { + if response.hovered() || response.has_focus() || egui::Popup::is_id_open(ui.ctx(), popup) { ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); } button_face(ui.painter(), rect, icon, tokens); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2b1712ff..cf941ff5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -555,11 +555,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if popup_open || export_input_active { // The open list or export input handles the key + } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The list opens over an armed eyedropper or point pick, so it closes first + app.layer_pick_list = None; } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { - // The list opens over an armed point pick, so it closes first - app.layer_pick_list = None; } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; } else if !escape_is_free { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index fc23cab0..fb846e9c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -920,7 +920,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::layer_pick_list::click(app, pointer, local(pointer), rect); } - // R + click and the list it opens come before an armed point or focus pick, including the press that closes the list + // R + click and the list it opens come before an armed pick (point, focus, eyedropper, ID color), including the press that closes the list let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app); // A 3D generator's armed point pick: a click sets the point there instead of painting @@ -984,6 +984,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color); } if !alt + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(position) = response.interact_pointer_pos() { @@ -1110,11 +1111,14 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.continue_stroke(local(pointer), pressure); remember_line_anchor(app, local(pointer)); } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + } + + // A released drag ends its stroke as one undo step, also when a key held meanwhile blocks painting + if response.drag_stopped_by(PointerButton::Primary) + && app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); } let set_hover = app @@ -1796,7 +1800,7 @@ 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 +/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held, announced as it changes 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()); @@ -1813,6 +1817,10 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { egui::StrokeKind::Inside, ); painter.galley(at, galley, tokens.text); + + let announced = ui.interact(frame, egui::Id::unique("layer_pick_hint"), egui::Sense::empty()); + announced.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label)); + ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite)); } /// How far the layer pick label sits right of and below the pointer, and the room around its text (points) diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index c71a6670..2fb95c72 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -251,3 +251,23 @@ fn the_channel_list_starts_on_material_and_picks_a_channel_or_material_again() { assert!(harness.state().ui.layer_material_view, "Material shows the whole material again"); assert_eq!(harness.state().ui.layer_channel, Channel::Roughness, "the rows keep the last channel's blending"); } + +#[test] +fn add_smart_material_shows_the_keyboard_focus() { + let (mut harness, _) = app(); + let button = harness.get_by_role_and_label(Role::Button, "Add smart material").rect(); + let fills = |harness: &Harness<'_, TextureCraftApp>| { + harness + .output() + .shapes + .iter() + .filter(|clipped| matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == button && shape.fill != egui::Color32::TRANSPARENT)) + .count() + }; + assert_eq!(fills(&harness), 0, "no face at rest"); + + harness.get_by_role_and_label(Role::Button, "Add smart material").focus(); + harness.run_steps(3); + + assert!(fills(&harness) > 0, "the focused button is drawn"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7efe5ba0..d057cf51 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -933,3 +933,76 @@ fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { assert!(h.state().session.history_labels().len() > steps, "the next press paints there"); } + +/// The list holds the spot it was opened on: a view that changed size or camera no longer has it under that point +#[test] +fn the_layer_pick_list_closes_when_the_view_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + h.state_mut().session.camera.yaw += 0.5; + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the camera turned"); + + open_pick_list(&mut h); + h.set_size(egui::vec2(1300.0, 1000.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the view was resized"); +} + +#[test] +fn r_and_a_click_leaves_an_armed_eyedropper_armed() { + let (mut h, _) = harness(); + two_fills(&mut h); + h.state_mut().picking_color = Some(egui::Id::unique("armed eyedropper")); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().picking_color.is_some(), "armed before the list opens"); + + open_pick_list(&mut h); + + assert!(h.state().picking_color.is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list first"); + assert!(h.state().picking_color.is_some(), "and leaves the eyedropper armed"); +} + +#[test] +fn a_stroke_released_while_r_is_held_ends() { + let (mut h, _) = harness(); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + let middle = h.state().viewport_rect.center(); + let end = middle + egui::vec2(60.0, 0.0); + h.drag_at(middle); + h.run_steps(1); + h.hover_at(middle + egui::vec2(30.0, 0.0)); + h.run_steps(1); + assert!(h.state().session.stroke_active(), "the stroke is under way"); + + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(end); + h.run_steps(1); + h.drop_at(end); + h.run_steps(SETTLE_FRAMES); + + assert!(!h.state().session.stroke_active()); +} + +#[test] +fn the_label_under_the_pointer_is_announced_while_r_is_held() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(view.center()); + h.run_steps(SETTLE_FRAMES); + + let announced = h.query_all(by().label_contains("Upper fill +")).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite); + + assert!(announced, "the layer's name is announced without moving the focus"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2af71ba5..5c007545 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,9 +44,10 @@ the named layer of the active texture set, so it runs even with nothing selected `layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels). `layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there. +While a layer is soloed, both see only what the solo shows. `layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's result as image resources, and hides the folder; it is refused for a texture set with several UV -tiles. +tiles, and for a visible folder holding an anchor point that a layer outside it reads. `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation diff --git a/docs/features.md b/docs/features.md index ec08683e..3d380d78 100644 --- a/docs/features.md +++ b/docs/features.md @@ -54,7 +54,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the folder's result as one image per channel, with the folder's mask painted into the new layer's mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked - as they look over them at that moment. Not available for a texture set with several UV tiles. + as they look over them at that moment. Not available for a texture set with several UV tiles, or + while a layer outside the folder reads one of its anchor points. - **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack. - **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in From 5a9dbb5340dc71068224f7ca769904f610c479f8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:22:54 +0000 Subject: [PATCH 27/29] Layers: answer review follow-up: instances drawing a folder's anchor readers, effect rows of another set's source --- crates/engine/src/commands.rs | 19 +++++---- crates/engine/src/layer_ops.rs | 52 ++++++++++++++++++++---- crates/engine/tests/it/flatten_folder.rs | 39 ++++++++++++++++++ crates/engine/tests/it/instances.rs | 18 ++++++++ 4 files changed, 113 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 82c18f99..f8ca06ea 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,20 +193,23 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } -/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (the effect's own) were selected +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (one drawing the effect) were selected fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { let refused = match check_enabled(spec, s) { Ok(()) => return Ok(()), Err(why) => why, }; let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId); - let named = id_param("layer") - .filter(|_| spec.params.contains("layer?")) - .or_else(|| id_param("effect").filter(|_| spec.params.starts_with("{effect")).and_then(|effect| s.doc.project.effect(effect).map(|(owner, _)| owner))); - let Some((id, ts)) = named.and_then(|id| s.doc.project.locate(id).map(|(ts, _, _)| (id, ts))) else { return Err(refused) }; - if ts != s.ts() { - return Err(refused); - } + let ts = s.ts(); + let named = id_param("layer").filter(|_| spec.params.contains("layer?")).filter(|id| s.doc.project.locate(*id).is_some_and(|(found, _, _)| found == ts)); + + // An effect's layer may sit in another texture set, drawn here by an instance + let drawing_effect = || { + let effect = id_param("effect").filter(|_| spec.params.starts_with("{effect"))?; + let owner = s.doc.project.effect(effect)?.0; + s.doc.project.walk(ts).into_iter().map(|(id, _)| id).find(|id| s.doc.project.render_tree(&[*id]).contains(&owner)) + }; + let Some(id) = named.or_else(drawing_effect) else { return Err(refused) }; let selected = s.selected.insert(ts, id); let named_refused = check_enabled(spec, s); diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 2a146a0a..d4310282 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -1,6 +1,8 @@ //! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted //! pixels when a texture set changes size. +use std::collections::BTreeSet; + use serde_json::{Value, json}; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ @@ -303,7 +305,7 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> /// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { // An instance inside draws its source, which stays on screen where it is: the source can be such a reader - let mut hidden = std::collections::BTreeSet::new(); + let mut hidden = BTreeSet::new(); let mut unvisited = vec![folder]; while let Some(id) = unvisited.pop() { if hidden.insert(id) { @@ -311,14 +313,50 @@ fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { } } - let anchors = project - .render_tree(&[folder]) + // An instance staying on screen draws its source again, there with only the anchor points it draws itself + let drawn_again: Vec<_> = project + .locate(folder) .into_iter() - .filter_map(|id| project.layers.get(&id)) - .flat_map(|layer| layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter())) - .filter(|effect| matches!(effect.kind, EffectKind::Anchor)); + .flat_map(|(ts, _, _)| project.walk(ts)) + .filter(|(id, _)| !hidden.contains(id) && project.layers.get(id).is_some_and(|layer| layer.instance_source().is_some())) + .map(|(id, _)| mask_and_content_owners(project, id)) + .collect(); - anchors.flat_map(|anchor| project.anchor_readers(anchor.id)).any(|(reader, _)| !hidden.contains(&reader)) + let anchors = project.render_tree(&[folder]).into_iter().filter_map(|id| project.layers.get(&id)).flat_map(|layer| { + let effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()); + effects.filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(|effect| (layer.id, effect.id)) + }); + + anchors.into_iter().any(|(owner, anchor)| { + project.anchor_readers(anchor).into_iter().any(|(reader, reading)| { + !hidden.contains(&reader) || drawn_again.iter().any(|drawn| draws(project, drawn, reader, reading) && !draws(project, drawn, owner, Some(anchor))) + }) + }) +} + +/// The layers whose masks and the layers whose content drawing layer `root` reads: an instance's own mask stands in for its source's +fn mask_and_content_owners(project: &Project, root: LayerId) -> (BTreeSet, BTreeSet) { + let (mut masks, mut contents, mut visited) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + let mut unvisited = vec![root]; + while let Some(id) = unvisited.pop() { + if !visited.insert(id) { + continue; + } + + masks.insert(project.mask_owner(id)); + if let Some(content) = project.content_layer(id) { + contents.insert(content.id); + unvisited.extend(content.children().iter().copied()); + } + } + (masks, contents) +} + +/// Whether a draw reading `owners` (see [`mask_and_content_owners`]) includes `effect` of layer `layer`, or the layer's own fill when None +fn draws(project: &Project, (masks, contents): &(BTreeSet, BTreeSet), layer: LayerId, effect: Option) -> bool { + let mask = project.layers.get(&layer).and_then(|layer| layer.mask.as_ref()); + let in_mask = mask.is_some_and(|mask| mask.effects.iter().any(|other| Some(other.id) == effect)); + if in_mask { masks.contains(&layer) } else { contents.contains(&layer) } } /// One flattened tile of a channel: (tile, value + coverage data) diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index c97f46d0..7afb0f3b 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -289,3 +289,42 @@ fn flattening_is_refused_for_anchor_points_read_through_instances() { assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside"); } + +/// An instance above the folder draws a reader from inside it, without the anchor point that reader reads +#[test] +fn flattening_is_refused_when_an_instance_outside_draws_a_reader_from_inside() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance with its own mask draws the folder's children without the folder's mask and its anchor points +#[test] +fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mask() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.white", &json!({"layer": folder})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); +} diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index 099a41b0..d2be8aae 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -276,3 +276,21 @@ fn budgeted_updates_spread_work_and_end_identical() { assert!(s.caches[0].composite == full, "chunked compositing gives the same pixels"); assert!(s.memory().composites > 0); } + +#[test] +fn an_inherited_mask_effect_moves_from_another_texture_set_with_no_layer_selected() { + let mut s = session(); + let source = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": source.0})).unwrap(); + let add = |s: &mut Session| id(execute(s, "effect.add.fill", &json!({"layer": source.0, "target": "mask", "value": 0.5})).unwrap(), "effect"); + let (lower, upper) = (add(&mut s), add(&mut s)); + execute(&mut s, "layer.instance", &json!({"layer": source.0, "ts": 1})).unwrap(); + s.active_set = 1; + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower.0, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} From 2f736f3cb8eb212458930c8d5123da7a6b82918d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:28:46 +0000 Subject: [PATCH 28/29] Layers: answer the third review: image alpha once on cropped framed fills, folder flatten keeps compared channels and refuses clipped results, effect row and hover label bounds, nameable library files --- crates/compose/src/eval.rs | 88 ++++++++++++++++++---- crates/compose/src/flatten_folder_error.rs | 8 ++ crates/compose/src/lib.rs | 2 + crates/engine/src/layer_ops.rs | 13 +++- crates/engine/tests/it/flatten_folder.rs | 48 ++++++++++++ crates/ui-egui/src/dock.rs | 7 +- crates/ui-egui/src/layer_toolbar.rs | 28 ++++++- crates/ui-egui/src/viewport.rs | 30 +++++++- crates/ui-egui/tests/it/layers_panel.rs | 3 +- docs/control-protocol.md | 3 +- 10 files changed, 206 insertions(+), 24 deletions(-) create mode 100644 crates/compose/src/flatten_folder_error.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 932ca603..5d8d8120 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -34,6 +34,7 @@ use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::flatten_folder_error::FlattenFolderError; use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; @@ -3504,7 +3505,8 @@ impl<'a, 'b> Texel<'a, 'b> { }; let (coords, cover) = self.projected(proj); - if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha { + // With alpha coverage each channel's own image alpha covers it, in [`Texel::fill_texel`] + if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha || sampling.alpha_coverage { return cover * self.tile_cover(proj, &coords, sampling); } @@ -5642,11 +5644,17 @@ fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, /// One tile of a flattened folder's mask: (tile, mask value + coverage data) pub type FlatMaskTile = ((u32, u32), Vec); -/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither); None for a layer that is not a folder -pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<(Vec, Vec)> { - let set = inputs.project.texture_set(inputs.ts).ok()?; - if !inputs.project.content_layer(id)?.is_group() { - return None; +/// How far past its channel's range a folder's result may sit as rounding noise +const RANGE_TOLERANCE: f32 = 1e-3; + +/// A flattened folder: its content tiles and its mask tiles +pub type FlattenedFolder = (Vec, Vec); + +/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel and per channel a mask compares, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither) +pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Result { + let set = inputs.project.texture_set(inputs.ts).map_err(|_| FlattenFolderError::NotAFolder)?; + if !inputs.project.content_layer(id).is_some_and(Layer::is_group) { + return Err(FlattenFolderError::NotAFolder); } let channels: Vec = set.channel_list(); @@ -5663,12 +5671,13 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let planned_channels = evaluation_channels(&visible_inputs, channels.clone()); let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); - let out: Vec<(Vec, Option)> = tiles + // None for a tile where the folder's result leaves the range its image can hold + let out: Option, Option)>> = tiles .par_iter() .map(|&(tx, ty)| { - let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); - let Some(node) = nodes.first() else { return (Vec::new(), None) }; - let Content::Group(children) = &node.content else { return (Vec::new(), None) }; + let nodes = plan(&visible_inputs, &[id], &planned_channels, tx, ty, 0, Some(&fields)); + let Some(node) = nodes.first() else { return Some((Vec::new(), None)) }; + let Content::Group(children) = &node.content else { return Some((Vec::new(), None)) }; let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields)); // One value + coverage buffer per channel the folder plans; signed channels start at their middle @@ -5713,7 +5722,22 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt let comps = planned.comps.min(3); let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) }; - let Some(premultiplied) = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range) else { continue }; + let premultiplied = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range); + + // A change no Normal layer within the channel's range shows; where the folder's mask hides it, nothing is lost + let clipped = match premultiplied { + Some([.., coverage]) => premultiplied + .iter() + .flatten() + .take(comps) + .any(|value| *value < range.0 * coverage - RANGE_TOLERANCE || *value > range.1 * coverage + RANGE_TOLERANCE), + None => shown.iter().zip(under).take(comps).any(|(shown, under)| (shown - under).abs() > RANGE_TOLERANCE), + }; + if clipped && folder_mask > 0.0 { + return None; + } + + let Some(premultiplied) = premultiplied else { continue }; *laid_down = true; let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; @@ -5732,12 +5756,12 @@ pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opt } let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect(); - (content, mask.map(|mask| ((tx, ty), mask))) + Some((content, mask.map(|mask| ((tx, ty), mask)))) }) .collect(); - let (content, masks): (Vec<_>, Vec<_>) = out.into_iter().unzip(); - Some((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) + let (content, masks): (Vec<_>, Vec<_>) = out.ok_or(FlattenFolderError::ValueOutOfRange)?.into_iter().unzip(); + Ok((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) } #[cfg(test)] @@ -7874,6 +7898,42 @@ soft {soft:?}" assert!(raised.iter().zip(flattened).any(|(raised, flat)| (*raised - flat).abs() > 1e-4)); } + #[test] + fn a_cropped_framed_fill_applies_its_image_alpha_once_with_alpha_coverage() { + let mut f = fixture(); + let mut images = ImageStore::default(); + images.insert("half".to_owned(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 1.0, 1.0, 0.5]], false))); + let id = fill_layer(&mut f.project, [0.0; 3], 0.5); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sources.insert(Channel::BaseColor, Source::image("half")); + fill.projection = Projection::Planar { + scale: 1.0, + axis: 1, + offset: [0.0; 3], + uv: Default::default(), + projector: texturecraft_core::Projector { crop: texturecraft_core::ShapeCrop::Cropped, ..Default::default() }, + placed: Some(texturecraft_core::Decal { + center: [0.0; 3], + normal: [0.0, 1.0, 0.0], + up: [0.0, 0.0, -1.0], + size: [4.0, 4.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 1.0, + symmetry: None, + flip: [false; 2], + }), + }; + let plain = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sampling.alpha_coverage = true; + + let covered = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + + assert!(!close(plain, Channel::BaseColor.default_value()), "the fill lands on the plane"); + assert!(close(covered, plain), "alpha coverage {covered:?}, image alpha {plain:?}"); + } + #[test] fn micro_height_uses_the_live_stroke_and_restores_the_committed_anchor_after_cancel() { let (mut fixture, images) = micro_height_fixture(); diff --git a/crates/compose/src/flatten_folder_error.rs b/crates/compose/src/flatten_folder_error.rs new file mode 100644 index 00000000..40b0bac5 --- /dev/null +++ b/crates/compose/src/flatten_folder_error.rs @@ -0,0 +1,8 @@ +/// Why a folder can't be flattened +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlattenFolderError { + NotAFolder, + + /// Its layers add up past what an image holds, which baking would clip + ValueOutOfRange, +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a393a519..b52fade5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -27,6 +27,7 @@ pub mod fill_copies; pub mod fill_copy; mod fill_depth; mod fill_place; +mod flatten_folder_error; pub mod frame_placement; mod fur_lock; mod generator_maps; @@ -81,6 +82,7 @@ pub use eval::{ 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 flatten_folder_error::FlattenFolderError; pub use mask_gray::MaskGray; pub use padding_maps::PaddingMaps; pub use pattern_context::PatternContext; diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index d4310282..7a755bae 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; +use texturecraft_compose::FlattenFolderError; use texturecraft_compose::eval::FlatTile; use texturecraft_core::{ Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source, @@ -255,9 +256,15 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); - let (content, mask) = s - .with_inputs(ts, |inputs| texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)) - .ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; + let flattened = s + .with_inputs(ts, |inputs| Some(texturecraft_compose::flatten_folder(inputs, folder.id, &tiles))) + .ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let (content, mask) = flattened.map_err(|error| { + EngineError::Other(match error { + FlattenFolderError::NotAFolder => "nothing to flatten".into(), + FlattenFolderError::ValueOutOfRange => "the folder's layers go past what an image holds: flattening would clip them".into(), + }) + })?; let images = channel_images(content, size)?; if images.is_empty() { return Err(EngineError::Other("the folder shows nothing to flatten".into())); diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index 7afb0f3b..ca438fb8 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -328,3 +328,51 @@ fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mas assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); } + +/// A mask comparing a channel the set no longer has reads the folder's layers holding only that channel, before and after +#[test] +fn a_flattened_folder_keeps_what_its_masks_compare_in_a_removed_channel() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": top})).unwrap(); + execute(&mut s, "textureSet.channel.remove", &json!({"channel": "height"})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Linear dodge can take a folder's result past what an image holds, which the folder's opacity then mixes back: refused, not clipped +#[test] +fn flattening_a_folder_adding_up_past_white_is_refused() { + // The last folder's mask hides everything it adds, so nothing is clipped + for (added, masked, overflows) in [(0.25, false, false), (0.75, false, true), (0.75, true, false)] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.5})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.1, 0.1, 0.1], "roughness": added})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": "roughness", "mode": "linearDodge"})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.5})).unwrap(); + if masked { + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + } + let before = composite(&mut s); + let project = s.doc.project.clone(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert_eq!(flattened.is_err(), overflows, "added roughness {added}, masked {masked}: {flattened:?}"); + if overflows { + assert_eq!(s.doc.project, project, "nothing was added or hidden"); + } + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3addda00..4f0f62fc 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -311,7 +311,8 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) + let remove_column = ROW_CONTROL_GAP + EFFECT_REMOVE_WIDTH + ROW_RIGHT_PADDING; + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - remove_column).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -2746,7 +2747,9 @@ mod layer_layout_tests { let preview_left = 7.0 + indent + 22.0; let name_left = preview_left + preview + 8.0; assert!(eye_right < preview_left); - assert!(name_left + 20.0 <= width - 6.0 + 0.001); + // The cross takes the row's right end, so the name ends before it + let name_end = width - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH - ROW_RIGHT_PADDING; + assert!(name_left + MIN_NAME_WIDTH <= name_end + 0.001, "width {width}, level {level}, preview {preview}"); } } } diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 9bb066f4..a47beced 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -534,7 +534,8 @@ fn smart_material_tabs(library: &[PathBuf]) -> Vec = library .iter() - .filter(|path| !crate::shelf::is_saved_mask(path)) + // `material.load` takes the path as text: a file name that isn't text can't be named to it + .filter(|path| !crate::shelf::is_saved_mask(path) && path.to_str().is_some()) .map(|path| ResourcePickerItem { id: SmartMaterialChoice::Saved(path.clone()), label: crate::shelf::saved_material_name(path).to_owned(), @@ -548,3 +549,28 @@ fn smart_material_tabs(library: &[PathBuf]) -> Vec = tabs + .iter() + .flat_map(|tab| &tab.groups) + .flat_map(|group| &group.items) + .filter_map(|item| match &item.id { + SmartMaterialChoice::Saved(path) => Some(path.as_path()), + SmartMaterialChoice::BuiltIn(_) => None, + }) + .collect(); + + assert_eq!(saved, [std::path::Path::new("/library/steel.tcmat")]); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1265143c..56480a65 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1815,8 +1815,8 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { 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); + let frame = layer_pick_hint_frame(rect, hover, galley.size()); + let at = frame.min + vec2(LAYER_PICK_HINT_PADDING, LAYER_PICK_HINT_PADDING); painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel); painter.rect_stroke( frame, @@ -1831,6 +1831,16 @@ fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite)); } +/// The layer pick label's frame around text of `size`: beside the pointer, slid back inside `view` near its edges +fn layer_pick_hint_frame(view: Rect, hover: Pos2, size: egui::Vec2) -> Rect { + let beside = hover + vec2(LAYER_PICK_HINT_OFFSET, LAYER_PICK_HINT_OFFSET); + let frame = Rect::from_min_size(beside, size).expand(LAYER_PICK_HINT_PADDING); + let frame = frame.translate((view.max - frame.max).min(egui::Vec2::ZERO)); + + // A label wider than the view keeps its start + frame.translate((view.min - frame.min).max(egui::Vec2::ZERO)) +} + /// 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; @@ -2654,6 +2664,22 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: #[cfg(test)] mod tests { use super::*; + + #[test] + fn the_layer_pick_label_stays_inside_the_view_at_its_edges() { + let view = Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0)); + let size = vec2(120.0, 14.0); + for hover in [view.min, view.center(), view.right_center() - vec2(2.0, 0.0), view.max - vec2(2.0, 2.0)] { + let frame = layer_pick_hint_frame(view, hover, size); + + assert!(view.contains_rect(frame), "hover {hover:?}: {frame:?}"); + } + + let wide = layer_pick_hint_frame(view, view.center(), vec2(600.0, 14.0)); + + assert_eq!(wide.left(), view.left(), "a label wider than the view starts inside it"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn hovering_a_texture_set_row_previews_it_without_selecting_it() { diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index d057cf51..dd732214 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -238,7 +238,8 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); - let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); + // The nesting gives way to the row's edge, eye column, preview, gap, name and remove column + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 27.0).max(0.0); click(&mut harness, egui::pos2(row.left() + 15.0 + indent, row.center().y)); let content = &harness.state().session.doc.project.layers[&layer].content_effects; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3b614921..534cac1e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,7 +47,8 @@ viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown c While a layer is soloed, both see only what the solo shows. `layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's result as image resources, and hides the folder; it is refused for a texture set with several UV -tiles, and for a visible folder holding an anchor point that a layer outside it reads. +tiles, for a visible folder holding an anchor point that a layer outside it reads, and for a +folder whose layers' blend modes go past a channel's range (an image would clip the result). `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation From af41a430744b48e9ca94d505c7a5e7e157689b24 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:42:44 +0000 Subject: [PATCH 29/29] Layers: answer review: a failed folder flatten keeps no decoded images --- crates/engine/src/layer_ops.rs | 10 ++++++++-- crates/engine/tests/it/flatten_folder.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 7a755bae..bc16c1a7 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -305,8 +305,14 @@ fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> s.select_one(ts, flat); s.target = StackTarget::Content; Ok(flat) - })?; - Ok(json!({ "layer": flat.0 })) + }); + + // Forget images stored by an edit that rolled back + if flat.is_err() { + s.sync_images(); + } + + Ok(json!({ "layer": flat?.0 })) } /// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away diff --git a/crates/engine/tests/it/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs index ca438fb8..8ec2da0c 100644 --- a/crates/engine/tests/it/flatten_folder.rs +++ b/crates/engine/tests/it/flatten_folder.rs @@ -193,6 +193,23 @@ fn flattening_a_folder_over_several_uv_tiles_is_refused() { assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); } +/// A flatten that fails once its images are stored keeps none of their decoded pixels +#[test] +fn a_failed_folder_flatten_keeps_no_decoded_images() { + let mut s = session(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let decoded = s.images.len(); + + // The new layer gets a taken id, so placing it in the stack fails after its images are in + s.doc.project.next_id = folder; + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + let error = flattened.unwrap_err().to_string(); + assert!(error.contains("already exists"), "failed placing the new layer: {error}"); + assert_eq!(s.images.len(), decoded); +} + /// A child reading an anchor point of the folder's own mask keeps what it read #[test] fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() {